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

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

Move context switch preparation to a new separate function

This puts everything that's needed before activating a new
thread into a single place, and removes one lock/unlock pair.

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