source: mainline/kernel/generic/src/proc/thread.c@ d314571

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since d314571 was d314571, checked in by Jakub Jermar <jakub@…>, 7 years ago

Turn wait queue into a kobject usable by uspace

In order to provide an elegant synchronization mechanism for userspace,
this commit adds syscalls to create, sleep on and wakeup from a wait
queue.

  • Property mode set to 100644
File size: 26.8 KB
RevLine 
[f761f1eb]1/*
[7ed8530]2 * Copyright (c) 2010 Jakub Jermar
[ef1eab7]3 * Copyright (c) 2018 Jiri Svoboda
[f761f1eb]4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 *
10 * - Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * - Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * - The name of the author may not be used to endorse or promote products
16 * derived from this software without specific prior written permission.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 */
29
[174156fd]30/** @addtogroup kernel_generic_proc
[b45c443]31 * @{
32 */
33
[9179d0a]34/**
[b45c443]35 * @file
[da1bafb]36 * @brief Thread management functions.
[9179d0a]37 */
38
[63e27ef]39#include <assert.h>
[f761f1eb]40#include <proc/scheduler.h>
41#include <proc/thread.h>
42#include <proc/task.h>
43#include <mm/frame.h>
44#include <mm/page.h>
45#include <arch/asm.h>
[cce6acf]46#include <arch/cycle.h>
[f761f1eb]47#include <arch.h>
48#include <synch/spinlock.h>
49#include <synch/waitq.h>
[d314571]50#include <synch/syswaitq.h>
[f761f1eb]51#include <cpu.h>
[e535eeb]52#include <str.h>
[f761f1eb]53#include <context.h>
[5c9a08b]54#include <adt/list.h>
[ef1eab7]55#include <adt/odict.h>
[f761f1eb]56#include <time/clock.h>
[b3f8fb7]57#include <time/timeout.h>
[8d6c1f1]58#include <time/delay.h>
[4ffa9e0]59#include <config.h>
60#include <arch/interrupt.h>
[26a8604f]61#include <smp/ipi.h>
[f2ffad4]62#include <arch/faddr.h>
[23684b7]63#include <atomic.h>
[44a7ee5]64#include <mem.h>
[bab75df6]65#include <stdio.h>
[aafed15]66#include <stdlib.h>
[9f52563]67#include <main/uinit.h>
[e3c762cd]68#include <syscall/copy.h>
69#include <errno.h>
[aae365bc]70#include <debug.h>
[52755f1]71
[fe19611]72/** Thread states */
[a000878c]73const char *thread_states[] = {
[fe19611]74 "Invalid",
75 "Running",
76 "Sleeping",
77 "Ready",
78 "Entering",
79 "Exiting",
[48d14222]80 "Lingering"
[e1b6742]81};
82
[ef1eab7]83/** Lock protecting the @c threads ordered dictionary .
[4e33b6b]84 *
85 * For locking rules, see declaration thereof.
86 */
[da1bafb]87IRQ_SPINLOCK_INITIALIZE(threads_lock);
[88169d9]88
[ef1eab7]89/** Ordered dictionary of all threads by their address (i.e. pointer to
90 * the thread_t structure).
[88169d9]91 *
[ef1eab7]92 * When a thread is found in the @c threads ordered dictionary, it is
93 * guaranteed to exist as long as the @c threads_lock is held.
[da1bafb]94 *
[ef1eab7]95 * Members are of type thread_t.
[88169d9]96 */
[ef1eab7]97odict_t threads;
[f761f1eb]98
[da1bafb]99IRQ_SPINLOCK_STATIC_INITIALIZE(tidlock);
100static thread_id_t last_tid = 0;
[f761f1eb]101
[82d515e9]102static slab_cache_t *thread_cache;
[da1bafb]103
[0f81ceb7]104#ifdef CONFIG_FPU
[82d515e9]105slab_cache_t *fpu_context_cache;
[f76fed4]106#endif
[266294a9]107
[ef1eab7]108static void *threads_getkey(odlink_t *);
109static int threads_cmp(void *, void *);
110
[4e33b6b]111/** Thread wrapper.
[70527f1]112 *
[4e33b6b]113 * This wrapper is provided to ensure that every thread makes a call to
114 * thread_exit() when its implementing function returns.
[f761f1eb]115 *
[22f7769]116 * interrupts_disable() is assumed.
[70527f1]117 *
[f761f1eb]118 */
[e16e036a]119static void cushion(void)
[f761f1eb]120{
[43114c5]121 void (*f)(void *) = THREAD->thread_code;
122 void *arg = THREAD->thread_arg;
[449dc1ed]123 THREAD->last_cycle = get_cycle();
[a35b458]124
[0313ff0]125 /* This is where each thread wakes up after its creation */
[da1bafb]126 irq_spinlock_unlock(&THREAD->lock, false);
[22f7769]127 interrupts_enable();
[a35b458]128
[f761f1eb]129 f(arg);
[a35b458]130
[0313ff0]131 /* Accumulate accounting to the task */
[da1bafb]132 irq_spinlock_lock(&THREAD->lock, true);
[62b6d17]133 if (!THREAD->uncounted) {
[a2a00e8]134 thread_update_accounting(true);
135 uint64_t ucycles = THREAD->ucycles;
136 THREAD->ucycles = 0;
137 uint64_t kcycles = THREAD->kcycles;
138 THREAD->kcycles = 0;
[a35b458]139
[da1bafb]140 irq_spinlock_pass(&THREAD->lock, &TASK->lock);
[a2a00e8]141 TASK->ucycles += ucycles;
142 TASK->kcycles += kcycles;
[da1bafb]143 irq_spinlock_unlock(&TASK->lock, true);
[62b6d17]144 } else
[da1bafb]145 irq_spinlock_unlock(&THREAD->lock, true);
[a35b458]146
[f761f1eb]147 thread_exit();
[a35b458]148
[da1bafb]149 /* Not reached */
[f761f1eb]150}
151
[da1bafb]152/** Initialization and allocation for thread_t structure
153 *
154 */
[b7fd2a0]155static errno_t thr_constructor(void *obj, unsigned int kmflags)
[266294a9]156{
[da1bafb]157 thread_t *thread = (thread_t *) obj;
[a35b458]158
[da1bafb]159 irq_spinlock_initialize(&thread->lock, "thread_t_lock");
160 link_initialize(&thread->rq_link);
161 link_initialize(&thread->wq_link);
162 link_initialize(&thread->th_link);
[a35b458]163
[32fffef0]164 /* call the architecture-specific part of the constructor */
[da1bafb]165 thr_constructor_arch(thread);
[a35b458]166
[0f81ceb7]167#ifdef CONFIG_FPU
[abf6c01]168 thread->saved_fpu_context = slab_alloc(fpu_context_cache,
169 FRAME_ATOMIC | kmflags);
[da1bafb]170 if (!thread->saved_fpu_context)
[7f11dc6]171 return ENOMEM;
[da1bafb]172#endif /* CONFIG_FPU */
[a35b458]173
[38ff925]174 /*
175 * Allocate the kernel stack from the low-memory to prevent an infinite
176 * nesting of TLB-misses when accessing the stack from the part of the
177 * TLB-miss handler written in C.
178 *
179 * Note that low-memory is safe to be used for the stack as it will be
180 * covered by the kernel identity mapping, which guarantees not to
181 * nest TLB-misses infinitely (either via some hardware mechanism or
182 * by the construciton of the assembly-language part of the TLB-miss
183 * handler).
184 *
185 * This restriction can be lifted once each architecture provides
186 * a similar guarantee, for example by locking the kernel stack
187 * in the TLB whenever it is allocated from the high-memory and the
188 * thread is being scheduled to run.
189 */
190 kmflags |= FRAME_LOWMEM;
191 kmflags &= ~FRAME_HIGHMEM;
[a35b458]192
[95d45482]193 // NOTE: All kernel stacks must be aligned to STACK_SIZE,
194 // see get_stack_base().
[d1da1ff2]195
[cd3b380]196 uintptr_t stack_phys =
197 frame_alloc(STACK_FRAMES, kmflags, STACK_SIZE - 1);
198 if (!stack_phys) {
[0f81ceb7]199#ifdef CONFIG_FPU
[ba9a150]200 assert(thread->saved_fpu_context);
201 slab_free(fpu_context_cache, thread->saved_fpu_context);
[f76fed4]202#endif
[7f11dc6]203 return ENOMEM;
[f76fed4]204 }
[a35b458]205
[cd3b380]206 thread->kstack = (uint8_t *) PA2KA(stack_phys);
[a35b458]207
[9a1b20c]208#ifdef CONFIG_UDEBUG
[da1bafb]209 mutex_initialize(&thread->udebug.lock, MUTEX_PASSIVE);
[9a1b20c]210#endif
[a35b458]211
[7f11dc6]212 return EOK;
[266294a9]213}
214
215/** Destruction of thread_t object */
[da1bafb]216static size_t thr_destructor(void *obj)
[266294a9]217{
[da1bafb]218 thread_t *thread = (thread_t *) obj;
[a35b458]219
[32fffef0]220 /* call the architecture-specific part of the destructor */
[da1bafb]221 thr_destructor_arch(thread);
[a35b458]222
[5df1963]223 frame_free(KA2PA(thread->kstack), STACK_FRAMES);
[a35b458]224
[0f81ceb7]225#ifdef CONFIG_FPU
[ba9a150]226 assert(thread->saved_fpu_context);
227 slab_free(fpu_context_cache, thread->saved_fpu_context);
[f76fed4]228#endif
[a35b458]229
[e7c4115d]230 return STACK_FRAMES; /* number of frames freed */
[266294a9]231}
[70527f1]232
233/** Initialize threads
234 *
235 * Initialize kernel threads support.
236 *
237 */
[f761f1eb]238void thread_init(void)
239{
[43114c5]240 THREAD = NULL;
[a35b458]241
[e3306d04]242 atomic_store(&nrdy, 0);
[82d515e9]243 thread_cache = slab_cache_create("thread_t", sizeof(thread_t), 0,
[6f4495f5]244 thr_constructor, thr_destructor, 0);
[a35b458]245
[0f81ceb7]246#ifdef CONFIG_FPU
[82d515e9]247 fpu_context_cache = slab_cache_create("fpu_context_t",
[f97f1e51]248 sizeof(fpu_context_t), FPU_CONTEXT_ALIGN, NULL, NULL, 0);
[f76fed4]249#endif
[a35b458]250
[ef1eab7]251 odict_initialize(&threads, threads_getkey, threads_cmp);
[016acbe]252}
[70527f1]253
[6eef3c4]254/** Wire thread to the given CPU
255 *
256 * @param cpu CPU to wire the thread to.
257 *
258 */
259void thread_wire(thread_t *thread, cpu_t *cpu)
260{
261 irq_spinlock_lock(&thread->lock, true);
262 thread->cpu = cpu;
263 thread->wired = true;
264 irq_spinlock_unlock(&thread->lock, true);
265}
266
[8a64e81e]267/** Invoked right before thread_ready() readies the thread. thread is locked. */
268static void before_thread_is_ready(thread_t *thread)
269{
[63e27ef]270 assert(irq_spinlock_locked(&thread->lock));
[8a64e81e]271}
272
[70527f1]273/** Make thread ready
274 *
[da1bafb]275 * Switch thread to the ready state.
[70527f1]276 *
[df58e44]277 * @param thread Thread to make ready.
[70527f1]278 *
279 */
[da1bafb]280void thread_ready(thread_t *thread)
[f761f1eb]281{
[da1bafb]282 irq_spinlock_lock(&thread->lock, true);
[a35b458]283
[63e27ef]284 assert(thread->state != Ready);
[518dd43]285
[8a64e81e]286 before_thread_is_ready(thread);
[a35b458]287
[6eef3c4]288 int i = (thread->priority < RQ_COUNT - 1) ?
289 ++thread->priority : thread->priority;
[518dd43]290
[8ad7dd1]291 cpu_t *cpu;
292 if (thread->wired || thread->nomigrate || thread->fpu_context_engaged) {
293 /* Cannot ready to another CPU */
[63e27ef]294 assert(thread->cpu != NULL);
[8ad7dd1]295 cpu = thread->cpu;
296 } else if (thread->stolen) {
297 /* Ready to the stealing CPU */
[6eef3c4]298 cpu = CPU;
[8ad7dd1]299 } else if (thread->cpu) {
300 /* Prefer the CPU on which the thread ran last */
[63e27ef]301 assert(thread->cpu != NULL);
[8ad7dd1]302 cpu = thread->cpu;
303 } else {
304 cpu = CPU;
305 }
[a35b458]306
[da1bafb]307 thread->state = Ready;
[a35b458]308
[da1bafb]309 irq_spinlock_pass(&thread->lock, &(cpu->rq[i].lock));
[a35b458]310
[70527f1]311 /*
[da1bafb]312 * Append thread to respective ready queue
313 * on respective processor.
[f761f1eb]314 */
[a35b458]315
[55b77d9]316 list_append(&thread->rq_link, &cpu->rq[i].rq);
[da1bafb]317 cpu->rq[i].n++;
318 irq_spinlock_unlock(&(cpu->rq[i].lock), true);
[a35b458]319
[59e07c91]320 atomic_inc(&nrdy);
[248fc1a]321 atomic_inc(&cpu->nrdy);
[f761f1eb]322}
323
[70527f1]324/** Create new thread
325 *
326 * Create a new thread.
327 *
[da1bafb]328 * @param func Thread's implementing function.
329 * @param arg Thread's implementing function argument.
330 * @param task Task to which the thread belongs. The caller must
331 * guarantee that the task won't cease to exist during the
332 * call. The task's lock may not be held.
333 * @param flags Thread flags.
334 * @param name Symbolic name (a copy is made).
[70527f1]335 *
[da1bafb]336 * @return New thread's structure on success, NULL on failure.
[70527f1]337 *
338 */
[3bacee1]339thread_t *thread_create(void (*func)(void *), void *arg, task_t *task,
[6eef3c4]340 thread_flags_t flags, const char *name)
[f761f1eb]341{
[abf6c01]342 thread_t *thread = (thread_t *) slab_alloc(thread_cache, FRAME_ATOMIC);
[da1bafb]343 if (!thread)
[2a46e10]344 return NULL;
[a35b458]345
[deacd722]346 if (thread_create_arch(thread, flags) != EOK) {
347 slab_free(thread_cache, thread);
348 return NULL;
349 }
350
[bb68433]351 /* Not needed, but good for debugging */
[26aafe8]352 memsetb(thread->kstack, STACK_SIZE, 0);
[a35b458]353
[da1bafb]354 irq_spinlock_lock(&tidlock, true);
355 thread->tid = ++last_tid;
356 irq_spinlock_unlock(&tidlock, true);
[a35b458]357
[edc64c0]358 memset(&thread->saved_context, 0, sizeof(thread->saved_context));
[da1bafb]359 context_set(&thread->saved_context, FADDR(cushion),
[26aafe8]360 (uintptr_t) thread->kstack, STACK_SIZE);
[a35b458]361
[a6e55886]362 current_initialize((current_t *) thread->kstack);
[a35b458]363
[da1bafb]364 ipl_t ipl = interrupts_disable();
365 thread->saved_context.ipl = interrupts_read();
[bb68433]366 interrupts_restore(ipl);
[a35b458]367
[da1bafb]368 str_cpy(thread->name, THREAD_NAME_BUFLEN, name);
[a35b458]369
[da1bafb]370 thread->thread_code = func;
371 thread->thread_arg = arg;
372 thread->ticks = -1;
373 thread->ucycles = 0;
374 thread->kcycles = 0;
[6eef3c4]375 thread->uncounted =
376 ((flags & THREAD_FLAG_UNCOUNTED) == THREAD_FLAG_UNCOUNTED);
[da1bafb]377 thread->priority = -1; /* Start in rq[0] */
378 thread->cpu = NULL;
[6eef3c4]379 thread->wired = false;
380 thread->stolen = false;
381 thread->uspace =
382 ((flags & THREAD_FLAG_USPACE) == THREAD_FLAG_USPACE);
[a35b458]383
[43ac0cc]384 thread->nomigrate = 0;
[da1bafb]385 thread->state = Entering;
[a35b458]386
[da1bafb]387 timeout_initialize(&thread->sleep_timeout);
388 thread->sleep_interruptible = false;
[b59318e]389 thread->sleep_composable = false;
[da1bafb]390 thread->sleep_queue = NULL;
391 thread->timeout_pending = false;
[a35b458]392
[da1bafb]393 thread->in_copy_from_uspace = false;
394 thread->in_copy_to_uspace = false;
[a35b458]395
[da1bafb]396 thread->interrupted = false;
397 thread->detached = false;
398 waitq_initialize(&thread->join_wq);
[a35b458]399
[da1bafb]400 thread->task = task;
[a35b458]401
[6eef3c4]402 thread->fpu_context_exists = false;
403 thread->fpu_context_engaged = false;
[a35b458]404
[ef1eab7]405 odlink_initialize(&thread->lthreads);
[a35b458]406
[9a1b20c]407#ifdef CONFIG_UDEBUG
[5b7a107]408 /* Initialize debugging stuff */
409 thread->btrace = false;
[da1bafb]410 udebug_thread_initialize(&thread->udebug);
[9a1b20c]411#endif
[a35b458]412
[6eef3c4]413 if ((flags & THREAD_FLAG_NOATTACH) != THREAD_FLAG_NOATTACH)
[da1bafb]414 thread_attach(thread, task);
[a35b458]415
[da1bafb]416 return thread;
[d8431986]417}
418
419/** Destroy thread memory structure
420 *
421 * Detach thread from all queues, cpus etc. and destroy it.
[da1bafb]422 *
423 * @param thread Thread to be destroyed.
424 * @param irq_res Indicate whether it should unlock thread->lock
425 * in interrupts-restore mode.
[d8431986]426 *
427 */
[da1bafb]428void thread_destroy(thread_t *thread, bool irq_res)
[d8431986]429{
[63e27ef]430 assert(irq_spinlock_locked(&thread->lock));
431 assert((thread->state == Exiting) || (thread->state == Lingering));
432 assert(thread->task);
433 assert(thread->cpu);
[a35b458]434
[da1bafb]435 irq_spinlock_lock(&thread->cpu->lock, false);
436 if (thread->cpu->fpu_owner == thread)
437 thread->cpu->fpu_owner = NULL;
438 irq_spinlock_unlock(&thread->cpu->lock, false);
[a35b458]439
[da1bafb]440 irq_spinlock_pass(&thread->lock, &threads_lock);
[a35b458]441
[ef1eab7]442 odict_remove(&thread->lthreads);
[a35b458]443
[da1bafb]444 irq_spinlock_pass(&threads_lock, &thread->task->lock);
[a35b458]445
[d8431986]446 /*
447 * Detach from the containing task.
448 */
[da1bafb]449 list_remove(&thread->th_link);
450 irq_spinlock_unlock(&thread->task->lock, irq_res);
[a35b458]451
[ea7890e7]452 /*
[7ed8530]453 * Drop the reference to the containing task.
[ea7890e7]454 */
[da1bafb]455 task_release(thread->task);
[82d515e9]456 slab_free(thread_cache, thread);
[d8431986]457}
458
459/** Make the thread visible to the system.
460 *
461 * Attach the thread structure to the current task and make it visible in the
[5dcee525]462 * threads_tree.
[d8431986]463 *
[da1bafb]464 * @param t Thread to be attached to the task.
465 * @param task Task to which the thread is to be attached.
466 *
[d8431986]467 */
[da1bafb]468void thread_attach(thread_t *thread, task_t *task)
[d8431986]469{
470 /*
[9a1b20c]471 * Attach to the specified task.
[d8431986]472 */
[da1bafb]473 irq_spinlock_lock(&task->lock, true);
[a35b458]474
[7ed8530]475 /* Hold a reference to the task. */
476 task_hold(task);
[a35b458]477
[9a1b20c]478 /* Must not count kbox thread into lifecount */
[6eef3c4]479 if (thread->uspace)
[9a1b20c]480 atomic_inc(&task->lifecount);
[a35b458]481
[55b77d9]482 list_append(&thread->th_link, &task->threads);
[a35b458]483
[da1bafb]484 irq_spinlock_pass(&task->lock, &threads_lock);
[a35b458]485
[bb68433]486 /*
[ef1eab7]487 * Register this thread in the system-wide dictionary.
[bb68433]488 */
[ef1eab7]489 odict_insert(&thread->lthreads, &threads, NULL);
[da1bafb]490 irq_spinlock_unlock(&threads_lock, true);
[f761f1eb]491}
492
[0182a665]493/** Terminate thread.
[70527f1]494 *
[da1bafb]495 * End current thread execution and switch it to the exiting state.
496 * All pending timeouts are executed.
497 *
[70527f1]498 */
[f761f1eb]499void thread_exit(void)
500{
[6eef3c4]501 if (THREAD->uspace) {
[9a1b20c]502#ifdef CONFIG_UDEBUG
503 /* Generate udebug THREAD_E event */
504 udebug_thread_e_event();
[a35b458]505
[0ac99db]506 /*
507 * This thread will not execute any code or system calls from
508 * now on.
509 */
510 udebug_stoppable_begin();
[9a1b20c]511#endif
512 if (atomic_predec(&TASK->lifecount) == 0) {
513 /*
514 * We are the last userspace thread in the task that
515 * still has not exited. With the exception of the
516 * moment the task was created, new userspace threads
517 * can only be created by threads of the same task.
518 * We are safe to perform cleanup.
[da1bafb]519 *
[9a1b20c]520 */
[ea7890e7]521 ipc_cleanup();
[669f3d32]522 futex_task_cleanup();
[d314571]523 sys_waitq_task_cleanup();
[3bacee1]524 LOG("Cleanup of task %" PRIu64 " completed.", TASK->taskid);
[ea7890e7]525 }
526 }
[a35b458]527
[f761f1eb]528restart:
[da1bafb]529 irq_spinlock_lock(&THREAD->lock, true);
530 if (THREAD->timeout_pending) {
531 /* Busy waiting for timeouts in progress */
532 irq_spinlock_unlock(&THREAD->lock, true);
[f761f1eb]533 goto restart;
534 }
[a35b458]535
[43114c5]536 THREAD->state = Exiting;
[da1bafb]537 irq_spinlock_unlock(&THREAD->lock, true);
[a35b458]538
[f761f1eb]539 scheduler();
[a35b458]540
[874621f]541 /* Not reached */
[3bacee1]542 while (true)
543 ;
[f761f1eb]544}
545
[518dd43]546/** Interrupts an existing thread so that it may exit as soon as possible.
[1b20da0]547 *
548 * Threads that are blocked waiting for a synchronization primitive
[897fd8f1]549 * are woken up with a return code of EINTR if the
[518dd43]550 * blocking call was interruptable. See waitq_sleep_timeout().
[1b20da0]551 *
[518dd43]552 * The caller must guarantee the thread object is valid during the entire
553 * function, eg by holding the threads_lock lock.
[1b20da0]554 *
[518dd43]555 * Interrupted threads automatically exit when returning back to user space.
[1b20da0]556 *
[518dd43]557 * @param thread A valid thread object. The caller must guarantee it
558 * will remain valid until thread_interrupt() exits.
559 */
560void thread_interrupt(thread_t *thread)
561{
[63e27ef]562 assert(thread != NULL);
[a35b458]563
[518dd43]564 irq_spinlock_lock(&thread->lock, true);
[a35b458]565
[518dd43]566 thread->interrupted = true;
567 bool sleeping = (thread->state == Sleeping);
[a35b458]568
[518dd43]569 irq_spinlock_unlock(&thread->lock, true);
[a35b458]570
[518dd43]571 if (sleeping)
572 waitq_interrupt_sleep(thread);
573}
574
575/** Returns true if the thread was interrupted.
[1b20da0]576 *
[518dd43]577 * @param thread A valid thread object. User must guarantee it will
578 * be alive during the entire call.
579 * @return true if the thread was already interrupted via thread_interrupt().
580 */
581bool thread_interrupted(thread_t *thread)
582{
[63e27ef]583 assert(thread != NULL);
[a35b458]584
[518dd43]585 bool interrupted;
[a35b458]586
[518dd43]587 irq_spinlock_lock(&thread->lock, true);
588 interrupted = thread->interrupted;
589 irq_spinlock_unlock(&thread->lock, true);
[a35b458]590
[518dd43]591 return interrupted;
592}
593
[43ac0cc]594/** Prevent the current thread from being migrated to another processor. */
595void thread_migration_disable(void)
596{
[63e27ef]597 assert(THREAD);
[a35b458]598
[43ac0cc]599 THREAD->nomigrate++;
600}
601
602/** Allow the current thread to be migrated to another processor. */
603void thread_migration_enable(void)
604{
[63e27ef]605 assert(THREAD);
606 assert(THREAD->nomigrate > 0);
[a35b458]607
[6eef3c4]608 if (THREAD->nomigrate > 0)
609 THREAD->nomigrate--;
[43ac0cc]610}
611
[70527f1]612/** Thread sleep
613 *
614 * Suspend execution of the current thread.
615 *
616 * @param sec Number of seconds to sleep.
617 *
618 */
[7f1c620]619void thread_sleep(uint32_t sec)
[f761f1eb]620{
[7c3fb9b]621 /*
622 * Sleep in 1000 second steps to support
623 * full argument range
624 */
[22e6802]625 while (sec > 0) {
626 uint32_t period = (sec > 1000) ? 1000 : sec;
[a35b458]627
[22e6802]628 thread_usleep(period * 1000000);
629 sec -= period;
630 }
[f761f1eb]631}
[70527f1]632
[fe19611]633/** Wait for another thread to exit.
634 *
[da1bafb]635 * @param thread Thread to join on exit.
636 * @param usec Timeout in microseconds.
637 * @param flags Mode of operation.
[fe19611]638 *
639 * @return An error code from errno.h or an error code from synch.h.
[da1bafb]640 *
[fe19611]641 */
[b7fd2a0]642errno_t thread_join_timeout(thread_t *thread, uint32_t usec, unsigned int flags)
[fe19611]643{
[da1bafb]644 if (thread == THREAD)
[fe19611]645 return EINVAL;
[a35b458]646
[fe19611]647 /*
648 * Since thread join can only be called once on an undetached thread,
649 * the thread pointer is guaranteed to be still valid.
650 */
[a35b458]651
[da1bafb]652 irq_spinlock_lock(&thread->lock, true);
[63e27ef]653 assert(!thread->detached);
[da1bafb]654 irq_spinlock_unlock(&thread->lock, true);
[a35b458]655
[897fd8f1]656 return waitq_sleep_timeout(&thread->join_wq, usec, flags, NULL);
[abf6c01]657
658 // FIXME: join should deallocate the thread.
659 // Current code calls detach after join, that's contrary to how
660 // join is used in other threading APIs.
[fe19611]661}
662
663/** Detach thread.
664 *
[df58e44]665 * Mark the thread as detached. If the thread is already
666 * in the Lingering state, deallocate its resources.
[fe19611]667 *
[da1bafb]668 * @param thread Thread to be detached.
669 *
[fe19611]670 */
[da1bafb]671void thread_detach(thread_t *thread)
[fe19611]672{
673 /*
[31d8e10]674 * Since the thread is expected not to be already detached,
[fe19611]675 * pointer to it must be still valid.
676 */
[da1bafb]677 irq_spinlock_lock(&thread->lock, true);
[63e27ef]678 assert(!thread->detached);
[a35b458]679
[da1bafb]680 if (thread->state == Lingering) {
681 /*
682 * Unlock &thread->lock and restore
683 * interrupts in thread_destroy().
684 */
685 thread_destroy(thread, true);
[fe19611]686 return;
687 } else {
[da1bafb]688 thread->detached = true;
[fe19611]689 }
[a35b458]690
[da1bafb]691 irq_spinlock_unlock(&thread->lock, true);
[fe19611]692}
693
[70527f1]694/** Thread usleep
695 *
696 * Suspend execution of the current thread.
697 *
698 * @param usec Number of microseconds to sleep.
699 *
[1b20da0]700 */
[7f1c620]701void thread_usleep(uint32_t usec)
[f761f1eb]702{
703 waitq_t wq;
[a35b458]704
[f761f1eb]705 waitq_initialize(&wq);
[a35b458]706
[897fd8f1]707 (void) waitq_sleep_timeout(&wq, usec, SYNCH_FLAGS_NON_BLOCKING, NULL);
[f761f1eb]708}
709
[ef1eab7]710static void thread_print(thread_t *thread, bool additional)
[5dcee525]711{
[1ba37fa]712 uint64_t ucycles, kcycles;
713 char usuffix, ksuffix;
[da1bafb]714 order_suffix(thread->ucycles, &ucycles, &usuffix);
715 order_suffix(thread->kcycles, &kcycles, &ksuffix);
[a35b458]716
[577f042a]717 char *name;
718 if (str_cmp(thread->name, "uinit") == 0)
719 name = thread->task->name;
720 else
721 name = thread->name;
[a35b458]722
[52755f1]723#ifdef __32_BITS__
[ef1eab7]724 if (additional)
[ae0300b5]725 printf("%-8" PRIu64 " %10p %10p %9" PRIu64 "%c %9" PRIu64 "%c ",
[577f042a]726 thread->tid, thread->thread_code, thread->kstack,
727 ucycles, usuffix, kcycles, ksuffix);
[48dcc69]728 else
[ae0300b5]729 printf("%-8" PRIu64 " %-14s %10p %-8s %10p %-5" PRIu32 "\n",
[577f042a]730 thread->tid, name, thread, thread_states[thread->state],
[26aafe8]731 thread->task, thread->task->container);
[52755f1]732#endif
[a35b458]733
[52755f1]734#ifdef __64_BITS__
[ef1eab7]735 if (additional)
[ae0300b5]736 printf("%-8" PRIu64 " %18p %18p\n"
[48dcc69]737 " %9" PRIu64 "%c %9" PRIu64 "%c ",
738 thread->tid, thread->thread_code, thread->kstack,
739 ucycles, usuffix, kcycles, ksuffix);
[5dcee525]740 else
[ae0300b5]741 printf("%-8" PRIu64 " %-14s %18p %-8s %18p %-5" PRIu32 "\n",
[577f042a]742 thread->tid, name, thread, thread_states[thread->state],
[26aafe8]743 thread->task, thread->task->container);
[48dcc69]744#endif
[a35b458]745
[ef1eab7]746 if (additional) {
[48dcc69]747 if (thread->cpu)
748 printf("%-5u", thread->cpu->id);
749 else
750 printf("none ");
[a35b458]751
[48dcc69]752 if (thread->state == Sleeping) {
[52755f1]753#ifdef __32_BITS__
[48dcc69]754 printf(" %10p", thread->sleep_queue);
[52755f1]755#endif
[a35b458]756
[52755f1]757#ifdef __64_BITS__
[48dcc69]758 printf(" %18p", thread->sleep_queue);
[52755f1]759#endif
[48dcc69]760 }
[a35b458]761
[48dcc69]762 printf("\n");
[43b1e86]763 }
[5dcee525]764}
765
[da1bafb]766/** Print list of threads debug info
[48dcc69]767 *
768 * @param additional Print additional information.
[da1bafb]769 *
770 */
[48dcc69]771void thread_print_list(bool additional)
[55ab0f1]772{
[ef1eab7]773 thread_t *thread;
774
[55ab0f1]775 /* Messing with thread structures, avoid deadlock */
[da1bafb]776 irq_spinlock_lock(&threads_lock, true);
[a35b458]777
[da1bafb]778#ifdef __32_BITS__
[48dcc69]779 if (additional)
[577f042a]780 printf("[id ] [code ] [stack ] [ucycles ] [kcycles ]"
781 " [cpu] [waitqueue]\n");
[48dcc69]782 else
783 printf("[id ] [name ] [address ] [state ] [task ]"
[26aafe8]784 " [ctn]\n");
[52755f1]785#endif
[a35b458]786
[52755f1]787#ifdef __64_BITS__
[48dcc69]788 if (additional) {
789 printf("[id ] [code ] [stack ]\n"
790 " [ucycles ] [kcycles ] [cpu] [waitqueue ]\n");
791 } else
792 printf("[id ] [name ] [address ] [state ]"
[26aafe8]793 " [task ] [ctn]\n");
[52755f1]794#endif
[a35b458]795
[aab5e46]796 thread = thread_first();
797 while (thread != NULL) {
[ef1eab7]798 thread_print(thread, additional);
[aab5e46]799 thread = thread_next(thread);
[ef1eab7]800 }
[a35b458]801
[da1bafb]802 irq_spinlock_unlock(&threads_lock, true);
[55ab0f1]803}
[9f52563]804
[016acbe]805/** Check whether thread exists.
806 *
807 * Note that threads_lock must be already held and
808 * interrupts must be already disabled.
809 *
[da1bafb]810 * @param thread Pointer to thread.
[016acbe]811 *
812 * @return True if thread t is known to the system, false otherwise.
[da1bafb]813 *
[016acbe]814 */
[da1bafb]815bool thread_exists(thread_t *thread)
[016acbe]816{
[63e27ef]817 assert(interrupts_disabled());
818 assert(irq_spinlock_locked(&threads_lock));
[1d432f9]819
[ef1eab7]820 odlink_t *odlink = odict_find_eq(&threads, thread, NULL);
821 return odlink != NULL;
[016acbe]822}
823
[cce6acf]824/** Update accounting of current thread.
825 *
826 * Note that thread_lock on THREAD must be already held and
827 * interrupts must be already disabled.
828 *
[da1bafb]829 * @param user True to update user accounting, false for kernel.
830 *
[cce6acf]831 */
[a2a00e8]832void thread_update_accounting(bool user)
[cce6acf]833{
834 uint64_t time = get_cycle();
[1d432f9]835
[63e27ef]836 assert(interrupts_disabled());
837 assert(irq_spinlock_locked(&THREAD->lock));
[a35b458]838
[da1bafb]839 if (user)
[a2a00e8]840 THREAD->ucycles += time - THREAD->last_cycle;
[da1bafb]841 else
[a2a00e8]842 THREAD->kcycles += time - THREAD->last_cycle;
[a35b458]843
[cce6acf]844 THREAD->last_cycle = time;
845}
846
[e1b6742]847/** Find thread structure corresponding to thread ID.
848 *
849 * The threads_lock must be already held by the caller of this function and
850 * interrupts must be disabled.
851 *
852 * @param id Thread ID.
853 *
854 * @return Thread structure address or NULL if there is no such thread ID.
855 *
856 */
857thread_t *thread_find_by_id(thread_id_t thread_id)
858{
[ef1eab7]859 thread_t *thread;
860
[63e27ef]861 assert(interrupts_disabled());
862 assert(irq_spinlock_locked(&threads_lock));
[a35b458]863
[aab5e46]864 thread = thread_first();
865 while (thread != NULL) {
[ef1eab7]866 if (thread->tid == thread_id)
867 return thread;
[a35b458]868
[aab5e46]869 thread = thread_next(thread);
[ef1eab7]870 }
[a35b458]871
[ef1eab7]872 return NULL;
[e1b6742]873}
874
[aab5e46]875/** Get count of threads.
876 *
877 * @return Number of threads in the system
878 */
879size_t thread_count(void)
880{
881 assert(interrupts_disabled());
882 assert(irq_spinlock_locked(&threads_lock));
883
884 return odict_count(&threads);
885}
886
887/** Get first thread.
888 *
889 * @return Pointer to first thread or @c NULL if there are none.
890 */
891thread_t *thread_first(void)
892{
893 odlink_t *odlink;
894
895 assert(interrupts_disabled());
896 assert(irq_spinlock_locked(&threads_lock));
897
898 odlink = odict_first(&threads);
899 if (odlink == NULL)
900 return NULL;
901
902 return odict_get_instance(odlink, thread_t, lthreads);
903}
904
905/** Get next thread.
906 *
907 * @param cur Current thread
908 * @return Pointer to next thread or @c NULL if there are no more threads.
909 */
910thread_t *thread_next(thread_t *cur)
911{
912 odlink_t *odlink;
913
914 assert(interrupts_disabled());
915 assert(irq_spinlock_locked(&threads_lock));
916
917 odlink = odict_next(&cur->lthreads, &threads);
918 if (odlink == NULL)
919 return NULL;
920
921 return odict_get_instance(odlink, thread_t, lthreads);
922}
923
[5b7a107]924#ifdef CONFIG_UDEBUG
925
[df58e44]926void thread_stack_trace(thread_id_t thread_id)
927{
928 irq_spinlock_lock(&threads_lock, true);
[a35b458]929
[df58e44]930 thread_t *thread = thread_find_by_id(thread_id);
931 if (thread == NULL) {
932 printf("No such thread.\n");
933 irq_spinlock_unlock(&threads_lock, true);
934 return;
935 }
[a35b458]936
[df58e44]937 irq_spinlock_lock(&thread->lock, false);
[a35b458]938
[df58e44]939 /*
940 * Schedule a stack trace to be printed
941 * just before the thread is scheduled next.
942 *
943 * If the thread is sleeping then try to interrupt
944 * the sleep. Any request for printing an uspace stack
945 * trace from within the kernel should be always
946 * considered a last resort debugging means, therefore
947 * forcing the thread's sleep to be interrupted
948 * is probably justifiable.
949 */
[a35b458]950
[df58e44]951 bool sleeping = false;
952 istate_t *istate = thread->udebug.uspace_state;
953 if (istate != NULL) {
954 printf("Scheduling thread stack trace.\n");
955 thread->btrace = true;
956 if (thread->state == Sleeping)
957 sleeping = true;
958 } else
959 printf("Thread interrupt state not available.\n");
[a35b458]960
[df58e44]961 irq_spinlock_unlock(&thread->lock, false);
[a35b458]962
[df58e44]963 if (sleeping)
964 waitq_interrupt_sleep(thread);
[a35b458]965
[df58e44]966 irq_spinlock_unlock(&threads_lock, true);
967}
[e1b6742]968
[5b7a107]969#endif /* CONFIG_UDEBUG */
[e1b6742]970
[ef1eab7]971/** Get key function for the @c threads ordered dictionary.
972 *
973 * @param odlink Link
974 * @return Pointer to thread structure cast as 'void *'
975 */
976static void *threads_getkey(odlink_t *odlink)
977{
978 thread_t *thread = odict_get_instance(odlink, thread_t, lthreads);
979 return (void *) thread;
980}
981
982/** Key comparison function for the @c threads ordered dictionary.
983 *
984 * @param a Pointer to thread A
985 * @param b Pointer to thread B
986 * @return -1, 0, 1 iff pointer to A is less than, equal to, greater than B
987 */
988static int threads_cmp(void *a, void *b)
989{
990 if (a > b)
991 return -1;
992 else if (a == b)
993 return 0;
994 else
995 return +1;
996}
997
[9f52563]998/** Process syscall to create new thread.
999 *
1000 */
[b7fd2a0]1001sys_errno_t sys_thread_create(uspace_arg_t *uspace_uarg, char *uspace_name,
[7faabb7]1002 size_t name_len, thread_id_t *uspace_thread_id)
[9f52563]1003{
[24345a5]1004 if (name_len > THREAD_NAME_BUFLEN - 1)
[7faabb7]1005 name_len = THREAD_NAME_BUFLEN - 1;
[a35b458]1006
[da1bafb]1007 char namebuf[THREAD_NAME_BUFLEN];
[b7fd2a0]1008 errno_t rc = copy_from_uspace(namebuf, uspace_name, name_len);
[a53ed3a]1009 if (rc != EOK)
[b7fd2a0]1010 return (sys_errno_t) rc;
[a35b458]1011
[b60c582]1012 namebuf[name_len] = 0;
[a35b458]1013
[4680ef5]1014 /*
1015 * In case of failure, kernel_uarg will be deallocated in this function.
1016 * In case of success, kernel_uarg will be freed in uinit().
1017 */
[da1bafb]1018 uspace_arg_t *kernel_uarg =
[11b285d]1019 (uspace_arg_t *) malloc(sizeof(uspace_arg_t));
[7473807]1020 if (!kernel_uarg)
1021 return (sys_errno_t) ENOMEM;
[a35b458]1022
[e3c762cd]1023 rc = copy_from_uspace(kernel_uarg, uspace_uarg, sizeof(uspace_arg_t));
[a53ed3a]1024 if (rc != EOK) {
[e3c762cd]1025 free(kernel_uarg);
[b7fd2a0]1026 return (sys_errno_t) rc;
[e3c762cd]1027 }
[a35b458]1028
[da1bafb]1029 thread_t *thread = thread_create(uinit, kernel_uarg, TASK,
[6eef3c4]1030 THREAD_FLAG_USPACE | THREAD_FLAG_NOATTACH, namebuf);
[da1bafb]1031 if (thread) {
[d8431986]1032 if (uspace_thread_id != NULL) {
[da1bafb]1033 rc = copy_to_uspace(uspace_thread_id, &thread->tid,
1034 sizeof(thread->tid));
[a53ed3a]1035 if (rc != EOK) {
[d8431986]1036 /*
1037 * We have encountered a failure, but the thread
1038 * has already been created. We need to undo its
1039 * creation now.
1040 */
[a35b458]1041
[d8431986]1042 /*
[ea7890e7]1043 * The new thread structure is initialized, but
1044 * is still not visible to the system.
[d8431986]1045 * We can safely deallocate it.
1046 */
[82d515e9]1047 slab_free(thread_cache, thread);
[da1bafb]1048 free(kernel_uarg);
[a35b458]1049
[b7fd2a0]1050 return (sys_errno_t) rc;
[3bacee1]1051 }
[d8431986]1052 }
[a35b458]1053
[9a1b20c]1054#ifdef CONFIG_UDEBUG
[13964ef]1055 /*
1056 * Generate udebug THREAD_B event and attach the thread.
1057 * This must be done atomically (with the debug locks held),
1058 * otherwise we would either miss some thread or receive
1059 * THREAD_B events for threads that already existed
1060 * and could be detected with THREAD_READ before.
1061 */
[da1bafb]1062 udebug_thread_b_event_attach(thread, TASK);
[13964ef]1063#else
[da1bafb]1064 thread_attach(thread, TASK);
[9a1b20c]1065#endif
[da1bafb]1066 thread_ready(thread);
[a35b458]1067
[d8431986]1068 return 0;
[201abde]1069 } else
[0f250f9]1070 free(kernel_uarg);
[a35b458]1071
[b7fd2a0]1072 return (sys_errno_t) ENOMEM;
[9f52563]1073}
1074
1075/** Process syscall to terminate thread.
1076 *
1077 */
[b7fd2a0]1078sys_errno_t sys_thread_exit(int uspace_status)
[9f52563]1079{
[68091bd]1080 thread_exit();
[9f52563]1081}
[b45c443]1082
[3ce7f082]1083/** Syscall for getting TID.
1084 *
[201abde]1085 * @param uspace_thread_id Userspace address of 8-byte buffer where to store
1086 * current thread ID.
1087 *
1088 * @return 0 on success or an error code from @ref errno.h.
[da1bafb]1089 *
[b45c443]1090 */
[b7fd2a0]1091sys_errno_t sys_thread_get_id(thread_id_t *uspace_thread_id)
[3ce7f082]1092{
1093 /*
1094 * No need to acquire lock on THREAD because tid
1095 * remains constant for the lifespan of the thread.
[da1bafb]1096 *
[3ce7f082]1097 */
[b7fd2a0]1098 return (sys_errno_t) copy_to_uspace(uspace_thread_id, &THREAD->tid,
[201abde]1099 sizeof(THREAD->tid));
[3ce7f082]1100}
[6f4495f5]1101
[d9ece1cb]1102/** Syscall wrapper for sleeping. */
[b7fd2a0]1103sys_errno_t sys_thread_usleep(uint32_t usec)
[d9ece1cb]1104{
[22e6802]1105 thread_usleep(usec);
[d9ece1cb]1106 return 0;
1107}
1108
[b7fd2a0]1109sys_errno_t sys_thread_udelay(uint32_t usec)
[7e7b791]1110{
[8d6c1f1]1111 delay(usec);
[7e7b791]1112 return 0;
1113}
1114
[3ce7f082]1115/** @}
1116 */
Note: See TracBrowser for help on using the repository browser.