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

Last change on this file since ed7e057 was ed7e057, checked in by Jiří Zárevúcky <zarevucky.jiri@…>, 18 months ago

Add functions context_create(), context_replace() and context_swap()

and use them where appropriate, removing context_save() in the process.
Much like in userspace, context_swap() maintains natural control flow
as opposed to context_save()'s return-twice mechanic.

Beyond that, in the future, context_replace() and context_swap()
can be implemented more efficiently than the context_save()/
context_restore() pair. As of now, the original implementation is
retained.

  • Property mode set to 100644
File size: 28.1 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>
[23684b7]62#include <atomic.h>
[b169619]63#include <memw.h>
[bab75df6]64#include <stdio.h>
[aafed15]65#include <stdlib.h>
[9f52563]66#include <main/uinit.h>
[e3c762cd]67#include <syscall/copy.h>
68#include <errno.h>
[aae365bc]69#include <debug.h>
[111b9b9]70#include <halt.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.
[1871118]96 *
97 * This structure contains weak references. Any reference from it must not leave
98 * threads_lock critical section unless strengthened via thread_try_ref().
[88169d9]99 */
[ef1eab7]100odict_t threads;
[f761f1eb]101
[da1bafb]102IRQ_SPINLOCK_STATIC_INITIALIZE(tidlock);
103static thread_id_t last_tid = 0;
[f761f1eb]104
[82d515e9]105static slab_cache_t *thread_cache;
[da1bafb]106
[ef1eab7]107static void *threads_getkey(odlink_t *);
108static int threads_cmp(void *, void *);
109
[4e33b6b]110/** Thread wrapper.
[70527f1]111 *
[4e33b6b]112 * This wrapper is provided to ensure that every thread makes a call to
113 * thread_exit() when its implementing function returns.
[f761f1eb]114 *
[22f7769]115 * interrupts_disable() is assumed.
[70527f1]116 *
[f761f1eb]117 */
[e16e036a]118static void cushion(void)
[f761f1eb]119{
[43114c5]120 void (*f)(void *) = THREAD->thread_code;
121 void *arg = THREAD->thread_arg;
[a35b458]122
[0313ff0]123 /* This is where each thread wakes up after its creation */
[da1bafb]124 irq_spinlock_unlock(&THREAD->lock, false);
[22f7769]125 interrupts_enable();
[a35b458]126
[f761f1eb]127 f(arg);
[a35b458]128
[f761f1eb]129 thread_exit();
[a35b458]130
[da1bafb]131 /* Not reached */
[f761f1eb]132}
133
[da1bafb]134/** Initialization and allocation for thread_t structure
135 *
136 */
[b7fd2a0]137static errno_t thr_constructor(void *obj, unsigned int kmflags)
[266294a9]138{
[da1bafb]139 thread_t *thread = (thread_t *) obj;
[a35b458]140
[da1bafb]141 irq_spinlock_initialize(&thread->lock, "thread_t_lock");
142 link_initialize(&thread->rq_link);
143 link_initialize(&thread->wq_link);
144 link_initialize(&thread->th_link);
[a35b458]145
[32fffef0]146 /* call the architecture-specific part of the constructor */
[da1bafb]147 thr_constructor_arch(thread);
[a35b458]148
[38ff925]149 /*
150 * Allocate the kernel stack from the low-memory to prevent an infinite
151 * nesting of TLB-misses when accessing the stack from the part of the
152 * TLB-miss handler written in C.
153 *
154 * Note that low-memory is safe to be used for the stack as it will be
155 * covered by the kernel identity mapping, which guarantees not to
156 * nest TLB-misses infinitely (either via some hardware mechanism or
[c477c80]157 * by the construction of the assembly-language part of the TLB-miss
[38ff925]158 * handler).
159 *
160 * This restriction can be lifted once each architecture provides
[c477c80]161 * a similar guarantee, for example, by locking the kernel stack
[38ff925]162 * in the TLB whenever it is allocated from the high-memory and the
163 * thread is being scheduled to run.
164 */
165 kmflags |= FRAME_LOWMEM;
166 kmflags &= ~FRAME_HIGHMEM;
[a35b458]167
[128359eb]168 /*
169 * NOTE: All kernel stacks must be aligned to STACK_SIZE,
170 * see CURRENT.
171 */
[d1da1ff2]172
[cd3b380]173 uintptr_t stack_phys =
174 frame_alloc(STACK_FRAMES, kmflags, STACK_SIZE - 1);
[0366d09d]175 if (!stack_phys)
[7f11dc6]176 return ENOMEM;
[a35b458]177
[cd3b380]178 thread->kstack = (uint8_t *) PA2KA(stack_phys);
[a35b458]179
[9a1b20c]180#ifdef CONFIG_UDEBUG
[da1bafb]181 mutex_initialize(&thread->udebug.lock, MUTEX_PASSIVE);
[9a1b20c]182#endif
[a35b458]183
[7f11dc6]184 return EOK;
[266294a9]185}
186
187/** Destruction of thread_t object */
[da1bafb]188static size_t thr_destructor(void *obj)
[266294a9]189{
[da1bafb]190 thread_t *thread = (thread_t *) obj;
[a35b458]191
[32fffef0]192 /* call the architecture-specific part of the destructor */
[da1bafb]193 thr_destructor_arch(thread);
[a35b458]194
[5df1963]195 frame_free(KA2PA(thread->kstack), STACK_FRAMES);
[a35b458]196
[e7c4115d]197 return STACK_FRAMES; /* number of frames freed */
[266294a9]198}
[70527f1]199
200/** Initialize threads
201 *
202 * Initialize kernel threads support.
203 *
204 */
[f761f1eb]205void thread_init(void)
206{
[43114c5]207 THREAD = NULL;
[a35b458]208
[e3306d04]209 atomic_store(&nrdy, 0);
[0366d09d]210 thread_cache = slab_cache_create("thread_t", sizeof(thread_t), _Alignof(thread_t),
[6f4495f5]211 thr_constructor, thr_destructor, 0);
[a35b458]212
[ef1eab7]213 odict_initialize(&threads, threads_getkey, threads_cmp);
[016acbe]214}
[70527f1]215
[6eef3c4]216/** Wire thread to the given CPU
217 *
218 * @param cpu CPU to wire the thread to.
219 *
220 */
221void thread_wire(thread_t *thread, cpu_t *cpu)
222{
223 irq_spinlock_lock(&thread->lock, true);
224 thread->cpu = cpu;
[dd218ea]225 thread->nomigrate++;
[6eef3c4]226 irq_spinlock_unlock(&thread->lock, true);
227}
228
[0f4f1b2]229/** Start a thread that wasn't started yet since it was created.
230 *
231 * @param thread A reference to the newly created thread.
232 */
233void thread_start(thread_t *thread)
234{
235 assert(thread->state == Entering);
236 thread_ready(thread_ref(thread));
237}
238
[70527f1]239/** Make thread ready
240 *
[1871118]241 * Switch thread to the ready state. Consumes reference passed by the caller.
[70527f1]242 *
[df58e44]243 * @param thread Thread to make ready.
[70527f1]244 *
245 */
[da1bafb]246void thread_ready(thread_t *thread)
[f761f1eb]247{
[da1bafb]248 irq_spinlock_lock(&thread->lock, true);
[a35b458]249
[63e27ef]250 assert(thread->state != Ready);
[518dd43]251
[6eef3c4]252 int i = (thread->priority < RQ_COUNT - 1) ?
253 ++thread->priority : thread->priority;
[518dd43]254
[fbaf6ac]255 /* Prefer the CPU on which the thread ran last */
256 cpu_t *cpu = thread->cpu ? thread->cpu : CPU;
[a35b458]257
[da1bafb]258 thread->state = Ready;
[a35b458]259
[da1bafb]260 irq_spinlock_pass(&thread->lock, &(cpu->rq[i].lock));
[a35b458]261
[70527f1]262 /*
[da1bafb]263 * Append thread to respective ready queue
264 * on respective processor.
[f761f1eb]265 */
[a35b458]266
[55b77d9]267 list_append(&thread->rq_link, &cpu->rq[i].rq);
[da1bafb]268 cpu->rq[i].n++;
269 irq_spinlock_unlock(&(cpu->rq[i].lock), true);
[a35b458]270
[59e07c91]271 atomic_inc(&nrdy);
[248fc1a]272 atomic_inc(&cpu->nrdy);
[f761f1eb]273}
274
[70527f1]275/** Create new thread
276 *
277 * Create a new thread.
278 *
[da1bafb]279 * @param func Thread's implementing function.
280 * @param arg Thread's implementing function argument.
281 * @param task Task to which the thread belongs. The caller must
282 * guarantee that the task won't cease to exist during the
283 * call. The task's lock may not be held.
284 * @param flags Thread flags.
285 * @param name Symbolic name (a copy is made).
[70527f1]286 *
[da1bafb]287 * @return New thread's structure on success, NULL on failure.
[70527f1]288 *
289 */
[3bacee1]290thread_t *thread_create(void (*func)(void *), void *arg, task_t *task,
[6eef3c4]291 thread_flags_t flags, const char *name)
[f761f1eb]292{
[abf6c01]293 thread_t *thread = (thread_t *) slab_alloc(thread_cache, FRAME_ATOMIC);
[da1bafb]294 if (!thread)
[2a46e10]295 return NULL;
[a35b458]296
[1871118]297 refcount_init(&thread->refcount);
298
[deacd722]299 if (thread_create_arch(thread, flags) != EOK) {
300 slab_free(thread_cache, thread);
301 return NULL;
302 }
303
[bb68433]304 /* Not needed, but good for debugging */
[26aafe8]305 memsetb(thread->kstack, STACK_SIZE, 0);
[a35b458]306
[da1bafb]307 irq_spinlock_lock(&tidlock, true);
308 thread->tid = ++last_tid;
309 irq_spinlock_unlock(&tidlock, true);
[a35b458]310
[ed7e057]311 context_create(&thread->saved_context, cushion, thread->kstack, STACK_SIZE);
[a35b458]312
[a6e55886]313 current_initialize((current_t *) thread->kstack);
[a35b458]314
[da1bafb]315 str_cpy(thread->name, THREAD_NAME_BUFLEN, name);
[a35b458]316
[da1bafb]317 thread->thread_code = func;
318 thread->thread_arg = arg;
319 thread->ucycles = 0;
320 thread->kcycles = 0;
[6eef3c4]321 thread->uncounted =
322 ((flags & THREAD_FLAG_UNCOUNTED) == THREAD_FLAG_UNCOUNTED);
[da1bafb]323 thread->priority = -1; /* Start in rq[0] */
324 thread->cpu = NULL;
[6eef3c4]325 thread->stolen = false;
326 thread->uspace =
327 ((flags & THREAD_FLAG_USPACE) == THREAD_FLAG_USPACE);
[a35b458]328
[43ac0cc]329 thread->nomigrate = 0;
[da1bafb]330 thread->state = Entering;
[a35b458]331
[111b9b9]332 atomic_init(&thread->sleep_queue, NULL);
[a35b458]333
[da1bafb]334 thread->in_copy_from_uspace = false;
335 thread->in_copy_to_uspace = false;
[a35b458]336
[da1bafb]337 thread->interrupted = false;
[111b9b9]338 atomic_init(&thread->sleep_state, SLEEP_INITIAL);
339
[da1bafb]340 waitq_initialize(&thread->join_wq);
[a35b458]341
[da1bafb]342 thread->task = task;
[a35b458]343
[6eef3c4]344 thread->fpu_context_exists = false;
[a35b458]345
[ef1eab7]346 odlink_initialize(&thread->lthreads);
[a35b458]347
[9a1b20c]348#ifdef CONFIG_UDEBUG
[5b7a107]349 /* Initialize debugging stuff */
350 thread->btrace = false;
[da1bafb]351 udebug_thread_initialize(&thread->udebug);
[9a1b20c]352#endif
[a35b458]353
[6eef3c4]354 if ((flags & THREAD_FLAG_NOATTACH) != THREAD_FLAG_NOATTACH)
[da1bafb]355 thread_attach(thread, task);
[a35b458]356
[da1bafb]357 return thread;
[d8431986]358}
359
360/** Destroy thread memory structure
361 *
362 * Detach thread from all queues, cpus etc. and destroy it.
[da1bafb]363 *
[11d2c983]364 * @param obj Thread to be destroyed.
[d8431986]365 *
366 */
[1871118]367static void thread_destroy(void *obj)
[d8431986]368{
[1871118]369 thread_t *thread = (thread_t *) obj;
370
[11d2c983]371 assert_link_not_used(&thread->rq_link);
372 assert_link_not_used(&thread->wq_link);
373
[63e27ef]374 assert(thread->task);
[11d2c983]375
376 ipl_t ipl = interrupts_disable();
377
378 /* Remove thread from global list. */
379 irq_spinlock_lock(&threads_lock, false);
380 odict_remove(&thread->lthreads);
381 irq_spinlock_unlock(&threads_lock, false);
382
[c7326f21]383 /* Remove thread from task's list and accumulate accounting. */
384 irq_spinlock_lock(&thread->task->lock, false);
385
386 list_remove(&thread->th_link);
387
388 /*
389 * No other CPU has access to this thread anymore, so we don't need
390 * thread->lock for accessing thread's fields after this point.
391 */
392
393 if (!thread->uncounted) {
394 thread->task->ucycles += thread->ucycles;
395 thread->task->kcycles += thread->kcycles;
396 }
397
398 irq_spinlock_unlock(&thread->task->lock, false);
[11d2c983]399
400 assert((thread->state == Exiting) || (thread->state == Lingering));
[a35b458]401
[c7326f21]402 /* Clear cpu->fpu_owner if set to this thread. */
[169815e]403#ifdef CONFIG_FPU_LAZY
404 if (thread->cpu) {
[f3dbe27]405 /*
406 * We need to lock for this because the old CPU can concurrently try
407 * to dump this thread's FPU state, in which case we need to wait for
408 * it to finish. An atomic compare-and-swap wouldn't be enough.
409 */
[169815e]410 irq_spinlock_lock(&thread->cpu->fpu_lock, false);
[f3dbe27]411
412 thread_t *owner = atomic_load_explicit(&thread->cpu->fpu_owner,
413 memory_order_relaxed);
414
415 if (owner == thread) {
416 atomic_store_explicit(&thread->cpu->fpu_owner, NULL,
417 memory_order_relaxed);
418 }
419
[169815e]420 irq_spinlock_unlock(&thread->cpu->fpu_lock, false);
421 }
422#endif
[a35b458]423
[11d2c983]424 interrupts_restore(ipl);
[a35b458]425
[ea7890e7]426 /*
[7ed8530]427 * Drop the reference to the containing task.
[ea7890e7]428 */
[da1bafb]429 task_release(thread->task);
[11d2c983]430 thread->task = NULL;
431
[82d515e9]432 slab_free(thread_cache, thread);
[d8431986]433}
434
[1871118]435void thread_put(thread_t *thread)
436{
437 if (refcount_down(&thread->refcount)) {
438 thread_destroy(thread);
439 }
440}
441
[d8431986]442/** Make the thread visible to the system.
443 *
444 * Attach the thread structure to the current task and make it visible in the
[5dcee525]445 * threads_tree.
[d8431986]446 *
[da1bafb]447 * @param t Thread to be attached to the task.
448 * @param task Task to which the thread is to be attached.
449 *
[d8431986]450 */
[da1bafb]451void thread_attach(thread_t *thread, task_t *task)
[d8431986]452{
[1871118]453 ipl_t ipl = interrupts_disable();
454
[d8431986]455 /*
[9a1b20c]456 * Attach to the specified task.
[d8431986]457 */
[1871118]458 irq_spinlock_lock(&task->lock, false);
[a35b458]459
[7ed8530]460 /* Hold a reference to the task. */
461 task_hold(task);
[a35b458]462
[9a1b20c]463 /* Must not count kbox thread into lifecount */
[6eef3c4]464 if (thread->uspace)
[9a1b20c]465 atomic_inc(&task->lifecount);
[a35b458]466
[55b77d9]467 list_append(&thread->th_link, &task->threads);
[a35b458]468
[1871118]469 irq_spinlock_unlock(&task->lock, false);
[a35b458]470
[bb68433]471 /*
[ef1eab7]472 * Register this thread in the system-wide dictionary.
[bb68433]473 */
[1871118]474 irq_spinlock_lock(&threads_lock, false);
[ef1eab7]475 odict_insert(&thread->lthreads, &threads, NULL);
[1871118]476 irq_spinlock_unlock(&threads_lock, false);
477
478 interrupts_restore(ipl);
[f761f1eb]479}
480
[0182a665]481/** Terminate thread.
[70527f1]482 *
[da1bafb]483 * End current thread execution and switch it to the exiting state.
484 * All pending timeouts are executed.
485 *
[70527f1]486 */
[f761f1eb]487void thread_exit(void)
488{
[6eef3c4]489 if (THREAD->uspace) {
[9a1b20c]490#ifdef CONFIG_UDEBUG
491 /* Generate udebug THREAD_E event */
492 udebug_thread_e_event();
[a35b458]493
[0ac99db]494 /*
495 * This thread will not execute any code or system calls from
496 * now on.
497 */
498 udebug_stoppable_begin();
[9a1b20c]499#endif
500 if (atomic_predec(&TASK->lifecount) == 0) {
501 /*
502 * We are the last userspace thread in the task that
503 * still has not exited. With the exception of the
504 * moment the task was created, new userspace threads
505 * can only be created by threads of the same task.
506 * We are safe to perform cleanup.
[da1bafb]507 *
[9a1b20c]508 */
[ea7890e7]509 ipc_cleanup();
[d314571]510 sys_waitq_task_cleanup();
[3bacee1]511 LOG("Cleanup of task %" PRIu64 " completed.", TASK->taskid);
[ea7890e7]512 }
513 }
[a35b458]514
[151c050]515 scheduler_enter(Exiting);
516 unreachable();
[f761f1eb]517}
518
[518dd43]519/** Interrupts an existing thread so that it may exit as soon as possible.
[1b20da0]520 *
521 * Threads that are blocked waiting for a synchronization primitive
[897fd8f1]522 * are woken up with a return code of EINTR if the
[518dd43]523 * blocking call was interruptable. See waitq_sleep_timeout().
[1b20da0]524 *
[518dd43]525 * Interrupted threads automatically exit when returning back to user space.
[1b20da0]526 *
[1871118]527 * @param thread A valid thread object.
[518dd43]528 */
[111b9b9]529void thread_interrupt(thread_t *thread)
[518dd43]530{
[63e27ef]531 assert(thread != NULL);
[111b9b9]532 thread->interrupted = true;
533 thread_wakeup(thread);
534}
[a35b458]535
[111b9b9]536/** Prepare for putting the thread to sleep.
537 *
538 * @returns whether the thread is currently terminating. If THREAD_OK
539 * is returned, the thread is guaranteed to be woken up instantly if the thread
540 * is terminated at any time between this function's return and
541 * thread_wait_finish(). If THREAD_TERMINATING is returned, the thread can still
542 * go to sleep, but doing so will delay termination.
543 */
544thread_termination_state_t thread_wait_start(void)
545{
546 assert(THREAD != NULL);
[a35b458]547
[111b9b9]548 /*
549 * This is an exchange rather than a store so that we can use the acquire
550 * semantics, which is needed to ensure that code after this operation sees
551 * memory ops made before thread_wakeup() in other thread, if that wakeup
552 * was reset by this operation.
553 *
554 * In particular, we need this to ensure we can't miss the thread being
555 * terminated concurrently with a synchronization primitive preparing to
556 * sleep.
557 */
558 (void) atomic_exchange_explicit(&THREAD->sleep_state, SLEEP_INITIAL,
559 memory_order_acquire);
[a35b458]560
[111b9b9]561 return THREAD->interrupted ? THREAD_TERMINATING : THREAD_OK;
562}
[a35b458]563
[111b9b9]564static void thread_wait_timeout_callback(void *arg)
565{
566 thread_wakeup(arg);
567}
568
569/**
570 * Suspends this thread's execution until thread_wakeup() is called on it,
571 * or deadline is reached.
572 *
573 * The way this would normally be used is that the current thread call
574 * thread_wait_start(), and if interruption has not been signaled, stores
575 * a reference to itself in a synchronized structure (such as waitq).
576 * After that, it releases any spinlocks it might hold and calls this function.
577 *
578 * The thread doing the wakeup will acquire the thread's reference from said
579 * synchronized structure and calls thread_wakeup() on it.
580 *
581 * Notably, there can be more than one thread performing wakeup.
582 * The number of performed calls to thread_wakeup(), or their relative
583 * ordering with thread_wait_finish(), does not matter. However, calls to
584 * thread_wakeup() are expected to be synchronized with thread_wait_start()
585 * with which they are associated, otherwise wakeups may be missed.
586 * However, the operation of thread_wakeup() is defined at any time,
587 * synchronization notwithstanding (in the sense of C un/defined behavior),
588 * and is in fact used to interrupt waiting threads by external events.
589 * The waiting thread must operate correctly in face of spurious wakeups,
590 * and clean up its reference in the synchronization structure if necessary.
591 *
592 * Returns THREAD_WAIT_TIMEOUT if timeout fired, which is a necessary condition
593 * for it to have been waken up by the timeout, but the caller must assume
594 * that proper wakeups, timeouts and interrupts may occur concurrently, so
595 * the fact timeout has been registered does not necessarily mean the thread
596 * has not been woken up or interrupted.
597 */
598thread_wait_result_t thread_wait_finish(deadline_t deadline)
599{
600 assert(THREAD != NULL);
601
602 timeout_t timeout;
603
[5663872]604 /* Extra check to avoid going to scheduler if we don't need to. */
605 if (atomic_load_explicit(&THREAD->sleep_state, memory_order_acquire) !=
606 SLEEP_INITIAL)
607 return THREAD_WAIT_SUCCESS;
[111b9b9]608
[5663872]609 if (deadline != DEADLINE_NEVER) {
[111b9b9]610 timeout_initialize(&timeout);
611 timeout_register_deadline(&timeout, deadline,
612 thread_wait_timeout_callback, THREAD);
613 }
614
[151c050]615 scheduler_enter(Sleeping);
[111b9b9]616
617 if (deadline != DEADLINE_NEVER && !timeout_unregister(&timeout)) {
618 return THREAD_WAIT_TIMEOUT;
619 } else {
620 return THREAD_WAIT_SUCCESS;
621 }
622}
623
624void thread_wakeup(thread_t *thread)
625{
626 assert(thread != NULL);
627
628 int state = atomic_exchange_explicit(&thread->sleep_state, SLEEP_WOKE,
[5663872]629 memory_order_acq_rel);
[111b9b9]630
631 if (state == SLEEP_ASLEEP) {
632 /*
633 * Only one thread gets to do this.
634 * The reference consumed here is the reference implicitly passed to
635 * the waking thread by the sleeper in thread_wait_finish().
636 */
637 thread_ready(thread);
638 }
[518dd43]639}
640
[43ac0cc]641/** Prevent the current thread from being migrated to another processor. */
642void thread_migration_disable(void)
643{
[63e27ef]644 assert(THREAD);
[a35b458]645
[43ac0cc]646 THREAD->nomigrate++;
647}
648
649/** Allow the current thread to be migrated to another processor. */
650void thread_migration_enable(void)
651{
[63e27ef]652 assert(THREAD);
653 assert(THREAD->nomigrate > 0);
[a35b458]654
[6eef3c4]655 if (THREAD->nomigrate > 0)
656 THREAD->nomigrate--;
[43ac0cc]657}
658
[70527f1]659/** Thread sleep
660 *
661 * Suspend execution of the current thread.
662 *
663 * @param sec Number of seconds to sleep.
664 *
665 */
[7f1c620]666void thread_sleep(uint32_t sec)
[f761f1eb]667{
[7c3fb9b]668 /*
669 * Sleep in 1000 second steps to support
670 * full argument range
671 */
[22e6802]672 while (sec > 0) {
673 uint32_t period = (sec > 1000) ? 1000 : sec;
[a35b458]674
[22e6802]675 thread_usleep(period * 1000000);
676 sec -= period;
677 }
[f761f1eb]678}
[70527f1]679
[5110d0a]680errno_t thread_join(thread_t *thread)
681{
682 return thread_join_timeout(thread, SYNCH_NO_TIMEOUT, SYNCH_FLAGS_NONE);
683}
684
[fe19611]685/** Wait for another thread to exit.
[a064d4f]686 * After successful wait, the thread reference is destroyed.
[fe19611]687 *
[da1bafb]688 * @param thread Thread to join on exit.
689 * @param usec Timeout in microseconds.
690 * @param flags Mode of operation.
[fe19611]691 *
692 * @return An error code from errno.h or an error code from synch.h.
[da1bafb]693 *
[fe19611]694 */
[b7fd2a0]695errno_t thread_join_timeout(thread_t *thread, uint32_t usec, unsigned int flags)
[fe19611]696{
[0f4f1b2]697 assert(thread != NULL);
698
[da1bafb]699 if (thread == THREAD)
[fe19611]700 return EINVAL;
[a35b458]701
[da1bafb]702 irq_spinlock_lock(&thread->lock, true);
[1871118]703 state_t state = thread->state;
[da1bafb]704 irq_spinlock_unlock(&thread->lock, true);
[a35b458]705
[a064d4f]706 errno_t rc = EOK;
707
708 if (state != Exiting)
709 rc = _waitq_sleep_timeout(&thread->join_wq, usec, flags);
710
711 if (rc == EOK)
712 thread_put(thread);
713
714 return rc;
[fe19611]715}
716
[0f4f1b2]717void thread_detach(thread_t *thread)
718{
719 thread_put(thread);
720}
721
[70527f1]722/** Thread usleep
723 *
724 * Suspend execution of the current thread.
725 *
726 * @param usec Number of microseconds to sleep.
727 *
[1b20da0]728 */
[7f1c620]729void thread_usleep(uint32_t usec)
[f761f1eb]730{
731 waitq_t wq;
[a35b458]732
[f761f1eb]733 waitq_initialize(&wq);
[a35b458]734
[111b9b9]735 (void) waitq_sleep_timeout(&wq, usec);
[151c050]736}
737
738/** Allow other threads to run. */
739void thread_yield(void)
740{
741 assert(THREAD != NULL);
742 scheduler_enter(Running);
[f761f1eb]743}
744
[ef1eab7]745static void thread_print(thread_t *thread, bool additional)
[5dcee525]746{
[1ba37fa]747 uint64_t ucycles, kcycles;
748 char usuffix, ksuffix;
[da1bafb]749 order_suffix(thread->ucycles, &ucycles, &usuffix);
750 order_suffix(thread->kcycles, &kcycles, &ksuffix);
[a35b458]751
[577f042a]752 char *name;
753 if (str_cmp(thread->name, "uinit") == 0)
754 name = thread->task->name;
755 else
756 name = thread->name;
[a35b458]757
[ef1eab7]758 if (additional)
[c1b073b7]759 printf("%-8" PRIu64 " %p %p %9" PRIu64 "%c %9" PRIu64 "%c ",
[577f042a]760 thread->tid, thread->thread_code, thread->kstack,
761 ucycles, usuffix, kcycles, ksuffix);
[48dcc69]762 else
[c1b073b7]763 printf("%-8" PRIu64 " %-14s %p %-8s %p %-5" PRIu32 "\n",
[577f042a]764 thread->tid, name, thread, thread_states[thread->state],
[26aafe8]765 thread->task, thread->task->container);
[a35b458]766
[ef1eab7]767 if (additional) {
[48dcc69]768 if (thread->cpu)
769 printf("%-5u", thread->cpu->id);
770 else
771 printf("none ");
[a35b458]772
[48dcc69]773 if (thread->state == Sleeping) {
[c1b073b7]774 printf(" %p", thread->sleep_queue);
[48dcc69]775 }
[a35b458]776
[48dcc69]777 printf("\n");
[43b1e86]778 }
[5dcee525]779}
780
[da1bafb]781/** Print list of threads debug info
[48dcc69]782 *
783 * @param additional Print additional information.
[da1bafb]784 *
785 */
[48dcc69]786void thread_print_list(bool additional)
[55ab0f1]787{
[ef1eab7]788 thread_t *thread;
789
[1871118]790 /* Accessing system-wide threads list through thread_first()/thread_next(). */
[da1bafb]791 irq_spinlock_lock(&threads_lock, true);
[a35b458]792
[c1b073b7]793 if (sizeof(void *) <= 4) {
794 if (additional)
795 printf("[id ] [code ] [stack ] [ucycles ] [kcycles ]"
796 " [cpu] [waitqueue]\n");
797 else
798 printf("[id ] [name ] [address ] [state ] [task ]"
799 " [ctn]\n");
800 } else {
801 if (additional) {
802 printf("[id ] [code ] [stack ] [ucycles ] [kcycles ]"
803 " [cpu] [waitqueue ]\n");
804 } else
805 printf("[id ] [name ] [address ] [state ]"
806 " [task ] [ctn]\n");
807 }
[a35b458]808
[aab5e46]809 thread = thread_first();
810 while (thread != NULL) {
[ef1eab7]811 thread_print(thread, additional);
[aab5e46]812 thread = thread_next(thread);
[ef1eab7]813 }
[a35b458]814
[da1bafb]815 irq_spinlock_unlock(&threads_lock, true);
[55ab0f1]816}
[9f52563]817
[1871118]818static bool thread_exists(thread_t *thread)
[016acbe]819{
[ef1eab7]820 odlink_t *odlink = odict_find_eq(&threads, thread, NULL);
821 return odlink != NULL;
[016acbe]822}
823
[1871118]824/** Check whether the thread exists, and if so, return a reference to it.
825 */
826thread_t *thread_try_get(thread_t *thread)
827{
828 irq_spinlock_lock(&threads_lock, true);
829
830 if (thread_exists(thread)) {
831 /* Try to strengthen the reference. */
832 thread = thread_try_ref(thread);
833 } else {
834 thread = NULL;
835 }
836
837 irq_spinlock_unlock(&threads_lock, true);
838
839 return thread;
840}
841
[cce6acf]842/** Update accounting of current thread.
843 *
844 * Note that thread_lock on THREAD must be already held and
845 * interrupts must be already disabled.
846 *
[da1bafb]847 * @param user True to update user accounting, false for kernel.
848 *
[cce6acf]849 */
[a2a00e8]850void thread_update_accounting(bool user)
[cce6acf]851{
852 uint64_t time = get_cycle();
[1d432f9]853
[63e27ef]854 assert(interrupts_disabled());
855 assert(irq_spinlock_locked(&THREAD->lock));
[a35b458]856
[da1bafb]857 if (user)
[a2a00e8]858 THREAD->ucycles += time - THREAD->last_cycle;
[da1bafb]859 else
[a2a00e8]860 THREAD->kcycles += time - THREAD->last_cycle;
[a35b458]861
[cce6acf]862 THREAD->last_cycle = time;
863}
864
[e1b6742]865/** Find thread structure corresponding to thread ID.
866 *
867 * The threads_lock must be already held by the caller of this function and
868 * interrupts must be disabled.
869 *
[1871118]870 * The returned reference is weak.
871 * If the caller needs to keep it, thread_try_ref() must be used to upgrade
872 * to a strong reference _before_ threads_lock is released.
873 *
[e1b6742]874 * @param id Thread ID.
875 *
876 * @return Thread structure address or NULL if there is no such thread ID.
877 *
878 */
879thread_t *thread_find_by_id(thread_id_t thread_id)
880{
[ef1eab7]881 thread_t *thread;
882
[63e27ef]883 assert(interrupts_disabled());
884 assert(irq_spinlock_locked(&threads_lock));
[a35b458]885
[aab5e46]886 thread = thread_first();
887 while (thread != NULL) {
[ef1eab7]888 if (thread->tid == thread_id)
889 return thread;
[a35b458]890
[aab5e46]891 thread = thread_next(thread);
[ef1eab7]892 }
[a35b458]893
[ef1eab7]894 return NULL;
[e1b6742]895}
896
[aab5e46]897/** Get count of threads.
898 *
899 * @return Number of threads in the system
900 */
901size_t thread_count(void)
902{
903 assert(interrupts_disabled());
904 assert(irq_spinlock_locked(&threads_lock));
905
906 return odict_count(&threads);
907}
908
909/** Get first thread.
910 *
911 * @return Pointer to first thread or @c NULL if there are none.
912 */
913thread_t *thread_first(void)
914{
915 odlink_t *odlink;
916
917 assert(interrupts_disabled());
918 assert(irq_spinlock_locked(&threads_lock));
919
920 odlink = odict_first(&threads);
921 if (odlink == NULL)
922 return NULL;
923
924 return odict_get_instance(odlink, thread_t, lthreads);
925}
926
927/** Get next thread.
928 *
929 * @param cur Current thread
930 * @return Pointer to next thread or @c NULL if there are no more threads.
931 */
932thread_t *thread_next(thread_t *cur)
933{
934 odlink_t *odlink;
935
936 assert(interrupts_disabled());
937 assert(irq_spinlock_locked(&threads_lock));
938
939 odlink = odict_next(&cur->lthreads, &threads);
940 if (odlink == NULL)
941 return NULL;
942
943 return odict_get_instance(odlink, thread_t, lthreads);
944}
945
[5b7a107]946#ifdef CONFIG_UDEBUG
947
[df58e44]948void thread_stack_trace(thread_id_t thread_id)
949{
950 irq_spinlock_lock(&threads_lock, true);
[1871118]951 thread_t *thread = thread_try_ref(thread_find_by_id(thread_id));
952 irq_spinlock_unlock(&threads_lock, true);
[a35b458]953
[df58e44]954 if (thread == NULL) {
955 printf("No such thread.\n");
956 return;
957 }
[a35b458]958
[df58e44]959 /*
960 * Schedule a stack trace to be printed
961 * just before the thread is scheduled next.
962 *
963 * If the thread is sleeping then try to interrupt
964 * the sleep. Any request for printing an uspace stack
965 * trace from within the kernel should be always
966 * considered a last resort debugging means, therefore
967 * forcing the thread's sleep to be interrupted
968 * is probably justifiable.
969 */
[a35b458]970
[1871118]971 irq_spinlock_lock(&thread->lock, true);
972
[df58e44]973 bool sleeping = false;
974 istate_t *istate = thread->udebug.uspace_state;
975 if (istate != NULL) {
976 printf("Scheduling thread stack trace.\n");
977 thread->btrace = true;
978 if (thread->state == Sleeping)
979 sleeping = true;
980 } else
981 printf("Thread interrupt state not available.\n");
[a35b458]982
[1871118]983 irq_spinlock_unlock(&thread->lock, true);
[a35b458]984
[df58e44]985 if (sleeping)
[111b9b9]986 thread_wakeup(thread);
[a35b458]987
[1871118]988 thread_put(thread);
[df58e44]989}
[e1b6742]990
[5b7a107]991#endif /* CONFIG_UDEBUG */
[e1b6742]992
[ef1eab7]993/** Get key function for the @c threads ordered dictionary.
994 *
995 * @param odlink Link
996 * @return Pointer to thread structure cast as 'void *'
997 */
998static void *threads_getkey(odlink_t *odlink)
999{
1000 thread_t *thread = odict_get_instance(odlink, thread_t, lthreads);
1001 return (void *) thread;
1002}
1003
1004/** Key comparison function for the @c threads ordered dictionary.
1005 *
1006 * @param a Pointer to thread A
1007 * @param b Pointer to thread B
1008 * @return -1, 0, 1 iff pointer to A is less than, equal to, greater than B
1009 */
1010static int threads_cmp(void *a, void *b)
1011{
1012 if (a > b)
1013 return -1;
1014 else if (a == b)
1015 return 0;
1016 else
1017 return +1;
1018}
1019
[9f52563]1020/** Process syscall to create new thread.
1021 *
1022 */
[5a5269d]1023sys_errno_t sys_thread_create(uspace_ptr_uspace_arg_t uspace_uarg, uspace_ptr_char uspace_name,
1024 size_t name_len, uspace_ptr_thread_id_t uspace_thread_id)
[9f52563]1025{
[24345a5]1026 if (name_len > THREAD_NAME_BUFLEN - 1)
[7faabb7]1027 name_len = THREAD_NAME_BUFLEN - 1;
[a35b458]1028
[da1bafb]1029 char namebuf[THREAD_NAME_BUFLEN];
[b7fd2a0]1030 errno_t rc = copy_from_uspace(namebuf, uspace_name, name_len);
[a53ed3a]1031 if (rc != EOK)
[b7fd2a0]1032 return (sys_errno_t) rc;
[a35b458]1033
[b60c582]1034 namebuf[name_len] = 0;
[a35b458]1035
[4680ef5]1036 /*
1037 * In case of failure, kernel_uarg will be deallocated in this function.
1038 * In case of success, kernel_uarg will be freed in uinit().
1039 */
[da1bafb]1040 uspace_arg_t *kernel_uarg =
[11b285d]1041 (uspace_arg_t *) malloc(sizeof(uspace_arg_t));
[7473807]1042 if (!kernel_uarg)
1043 return (sys_errno_t) ENOMEM;
[a35b458]1044
[e3c762cd]1045 rc = copy_from_uspace(kernel_uarg, uspace_uarg, sizeof(uspace_arg_t));
[a53ed3a]1046 if (rc != EOK) {
[e3c762cd]1047 free(kernel_uarg);
[b7fd2a0]1048 return (sys_errno_t) rc;
[e3c762cd]1049 }
[a35b458]1050
[da1bafb]1051 thread_t *thread = thread_create(uinit, kernel_uarg, TASK,
[6eef3c4]1052 THREAD_FLAG_USPACE | THREAD_FLAG_NOATTACH, namebuf);
[da1bafb]1053 if (thread) {
[5a5269d]1054 if (uspace_thread_id) {
[da1bafb]1055 rc = copy_to_uspace(uspace_thread_id, &thread->tid,
1056 sizeof(thread->tid));
[a53ed3a]1057 if (rc != EOK) {
[d8431986]1058 /*
1059 * We have encountered a failure, but the thread
1060 * has already been created. We need to undo its
1061 * creation now.
1062 */
[a35b458]1063
[d8431986]1064 /*
[ea7890e7]1065 * The new thread structure is initialized, but
1066 * is still not visible to the system.
[d8431986]1067 * We can safely deallocate it.
1068 */
[82d515e9]1069 slab_free(thread_cache, thread);
[da1bafb]1070 free(kernel_uarg);
[a35b458]1071
[b7fd2a0]1072 return (sys_errno_t) rc;
[3bacee1]1073 }
[d8431986]1074 }
[a35b458]1075
[9a1b20c]1076#ifdef CONFIG_UDEBUG
[13964ef]1077 /*
1078 * Generate udebug THREAD_B event and attach the thread.
1079 * This must be done atomically (with the debug locks held),
1080 * otherwise we would either miss some thread or receive
1081 * THREAD_B events for threads that already existed
1082 * and could be detected with THREAD_READ before.
1083 */
[da1bafb]1084 udebug_thread_b_event_attach(thread, TASK);
[13964ef]1085#else
[da1bafb]1086 thread_attach(thread, TASK);
[9a1b20c]1087#endif
[da1bafb]1088 thread_ready(thread);
[a35b458]1089
[d8431986]1090 return 0;
[201abde]1091 } else
[0f250f9]1092 free(kernel_uarg);
[a35b458]1093
[b7fd2a0]1094 return (sys_errno_t) ENOMEM;
[9f52563]1095}
1096
1097/** Process syscall to terminate thread.
1098 *
1099 */
[b7fd2a0]1100sys_errno_t sys_thread_exit(int uspace_status)
[9f52563]1101{
[68091bd]1102 thread_exit();
[9f52563]1103}
[b45c443]1104
[3ce7f082]1105/** Syscall for getting TID.
1106 *
[201abde]1107 * @param uspace_thread_id Userspace address of 8-byte buffer where to store
1108 * current thread ID.
1109 *
1110 * @return 0 on success or an error code from @ref errno.h.
[da1bafb]1111 *
[b45c443]1112 */
[5a5269d]1113sys_errno_t sys_thread_get_id(uspace_ptr_thread_id_t uspace_thread_id)
[3ce7f082]1114{
1115 /*
1116 * No need to acquire lock on THREAD because tid
1117 * remains constant for the lifespan of the thread.
[da1bafb]1118 *
[3ce7f082]1119 */
[b7fd2a0]1120 return (sys_errno_t) copy_to_uspace(uspace_thread_id, &THREAD->tid,
[201abde]1121 sizeof(THREAD->tid));
[3ce7f082]1122}
[6f4495f5]1123
[d9ece1cb]1124/** Syscall wrapper for sleeping. */
[b7fd2a0]1125sys_errno_t sys_thread_usleep(uint32_t usec)
[d9ece1cb]1126{
[22e6802]1127 thread_usleep(usec);
[d9ece1cb]1128 return 0;
1129}
1130
[b7fd2a0]1131sys_errno_t sys_thread_udelay(uint32_t usec)
[7e7b791]1132{
[8d6c1f1]1133 delay(usec);
[7e7b791]1134 return 0;
1135}
1136
[3ce7f082]1137/** @}
1138 */
Note: See TracBrowser for help on using the repository browser.