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

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

Rethink scheduler entry points

Changes the way scheduler is entered, to eliminate some unnecessary
locking and interrupt disables.

  • 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>
[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 str_cpy(thread->name, THREAD_NAME_BUFLEN, name);
[a35b458]317
[da1bafb]318 thread->thread_code = func;
319 thread->thread_arg = arg;
320 thread->ucycles = 0;
321 thread->kcycles = 0;
[6eef3c4]322 thread->uncounted =
323 ((flags & THREAD_FLAG_UNCOUNTED) == THREAD_FLAG_UNCOUNTED);
[da1bafb]324 thread->priority = -1; /* Start in rq[0] */
325 thread->cpu = NULL;
[6eef3c4]326 thread->stolen = false;
327 thread->uspace =
328 ((flags & THREAD_FLAG_USPACE) == THREAD_FLAG_USPACE);
[a35b458]329
[43ac0cc]330 thread->nomigrate = 0;
[da1bafb]331 thread->state = Entering;
[a35b458]332
[111b9b9]333 atomic_init(&thread->sleep_queue, NULL);
[a35b458]334
[da1bafb]335 thread->in_copy_from_uspace = false;
336 thread->in_copy_to_uspace = false;
[a35b458]337
[da1bafb]338 thread->interrupted = false;
[111b9b9]339 atomic_init(&thread->sleep_state, SLEEP_INITIAL);
340
[da1bafb]341 waitq_initialize(&thread->join_wq);
[a35b458]342
[da1bafb]343 thread->task = task;
[a35b458]344
[6eef3c4]345 thread->fpu_context_exists = false;
[a35b458]346
[ef1eab7]347 odlink_initialize(&thread->lthreads);
[a35b458]348
[9a1b20c]349#ifdef CONFIG_UDEBUG
[5b7a107]350 /* Initialize debugging stuff */
351 thread->btrace = false;
[da1bafb]352 udebug_thread_initialize(&thread->udebug);
[9a1b20c]353#endif
[a35b458]354
[6eef3c4]355 if ((flags & THREAD_FLAG_NOATTACH) != THREAD_FLAG_NOATTACH)
[da1bafb]356 thread_attach(thread, task);
[a35b458]357
[da1bafb]358 return thread;
[d8431986]359}
360
361/** Destroy thread memory structure
362 *
363 * Detach thread from all queues, cpus etc. and destroy it.
[da1bafb]364 *
[11d2c983]365 * @param obj Thread to be destroyed.
[d8431986]366 *
367 */
[1871118]368static void thread_destroy(void *obj)
[d8431986]369{
[1871118]370 thread_t *thread = (thread_t *) obj;
371
[11d2c983]372 assert_link_not_used(&thread->rq_link);
373 assert_link_not_used(&thread->wq_link);
374
[63e27ef]375 assert(thread->task);
[11d2c983]376
377 ipl_t ipl = interrupts_disable();
378
379 /* Remove thread from global list. */
380 irq_spinlock_lock(&threads_lock, false);
381 odict_remove(&thread->lthreads);
382 irq_spinlock_unlock(&threads_lock, false);
383
[c7326f21]384 /* Remove thread from task's list and accumulate accounting. */
385 irq_spinlock_lock(&thread->task->lock, false);
386
387 list_remove(&thread->th_link);
388
389 /*
390 * No other CPU has access to this thread anymore, so we don't need
391 * thread->lock for accessing thread's fields after this point.
392 */
393
394 if (!thread->uncounted) {
395 thread->task->ucycles += thread->ucycles;
396 thread->task->kcycles += thread->kcycles;
397 }
398
399 irq_spinlock_unlock(&thread->task->lock, false);
[11d2c983]400
401 assert((thread->state == Exiting) || (thread->state == Lingering));
[a35b458]402
[c7326f21]403 /* Clear cpu->fpu_owner if set to this thread. */
[169815e]404#ifdef CONFIG_FPU_LAZY
405 if (thread->cpu) {
[f3dbe27]406 /*
407 * We need to lock for this because the old CPU can concurrently try
408 * to dump this thread's FPU state, in which case we need to wait for
409 * it to finish. An atomic compare-and-swap wouldn't be enough.
410 */
[169815e]411 irq_spinlock_lock(&thread->cpu->fpu_lock, false);
[f3dbe27]412
413 thread_t *owner = atomic_load_explicit(&thread->cpu->fpu_owner,
414 memory_order_relaxed);
415
416 if (owner == thread) {
417 atomic_store_explicit(&thread->cpu->fpu_owner, NULL,
418 memory_order_relaxed);
419 }
420
[169815e]421 irq_spinlock_unlock(&thread->cpu->fpu_lock, false);
422 }
423#endif
[a35b458]424
[11d2c983]425 interrupts_restore(ipl);
[a35b458]426
[ea7890e7]427 /*
[7ed8530]428 * Drop the reference to the containing task.
[ea7890e7]429 */
[da1bafb]430 task_release(thread->task);
[11d2c983]431 thread->task = NULL;
432
[82d515e9]433 slab_free(thread_cache, thread);
[d8431986]434}
435
[1871118]436void thread_put(thread_t *thread)
437{
438 if (refcount_down(&thread->refcount)) {
439 thread_destroy(thread);
440 }
441}
442
[d8431986]443/** Make the thread visible to the system.
444 *
445 * Attach the thread structure to the current task and make it visible in the
[5dcee525]446 * threads_tree.
[d8431986]447 *
[da1bafb]448 * @param t Thread to be attached to the task.
449 * @param task Task to which the thread is to be attached.
450 *
[d8431986]451 */
[da1bafb]452void thread_attach(thread_t *thread, task_t *task)
[d8431986]453{
[1871118]454 ipl_t ipl = interrupts_disable();
455
[d8431986]456 /*
[9a1b20c]457 * Attach to the specified task.
[d8431986]458 */
[1871118]459 irq_spinlock_lock(&task->lock, false);
[a35b458]460
[7ed8530]461 /* Hold a reference to the task. */
462 task_hold(task);
[a35b458]463
[9a1b20c]464 /* Must not count kbox thread into lifecount */
[6eef3c4]465 if (thread->uspace)
[9a1b20c]466 atomic_inc(&task->lifecount);
[a35b458]467
[55b77d9]468 list_append(&thread->th_link, &task->threads);
[a35b458]469
[1871118]470 irq_spinlock_unlock(&task->lock, false);
[a35b458]471
[bb68433]472 /*
[ef1eab7]473 * Register this thread in the system-wide dictionary.
[bb68433]474 */
[1871118]475 irq_spinlock_lock(&threads_lock, false);
[ef1eab7]476 odict_insert(&thread->lthreads, &threads, NULL);
[1871118]477 irq_spinlock_unlock(&threads_lock, false);
478
479 interrupts_restore(ipl);
[f761f1eb]480}
481
[0182a665]482/** Terminate thread.
[70527f1]483 *
[da1bafb]484 * End current thread execution and switch it to the exiting state.
485 * All pending timeouts are executed.
486 *
[70527f1]487 */
[f761f1eb]488void thread_exit(void)
489{
[6eef3c4]490 if (THREAD->uspace) {
[9a1b20c]491#ifdef CONFIG_UDEBUG
492 /* Generate udebug THREAD_E event */
493 udebug_thread_e_event();
[a35b458]494
[0ac99db]495 /*
496 * This thread will not execute any code or system calls from
497 * now on.
498 */
499 udebug_stoppable_begin();
[9a1b20c]500#endif
501 if (atomic_predec(&TASK->lifecount) == 0) {
502 /*
503 * We are the last userspace thread in the task that
504 * still has not exited. With the exception of the
505 * moment the task was created, new userspace threads
506 * can only be created by threads of the same task.
507 * We are safe to perform cleanup.
[da1bafb]508 *
[9a1b20c]509 */
[ea7890e7]510 ipc_cleanup();
[d314571]511 sys_waitq_task_cleanup();
[3bacee1]512 LOG("Cleanup of task %" PRIu64 " completed.", TASK->taskid);
[ea7890e7]513 }
514 }
[a35b458]515
[151c050]516 scheduler_enter(Exiting);
517 unreachable();
[f761f1eb]518}
519
[518dd43]520/** Interrupts an existing thread so that it may exit as soon as possible.
[1b20da0]521 *
522 * Threads that are blocked waiting for a synchronization primitive
[897fd8f1]523 * are woken up with a return code of EINTR if the
[518dd43]524 * blocking call was interruptable. See waitq_sleep_timeout().
[1b20da0]525 *
[518dd43]526 * Interrupted threads automatically exit when returning back to user space.
[1b20da0]527 *
[1871118]528 * @param thread A valid thread object.
[518dd43]529 */
[111b9b9]530void thread_interrupt(thread_t *thread)
[518dd43]531{
[63e27ef]532 assert(thread != NULL);
[111b9b9]533 thread->interrupted = true;
534 thread_wakeup(thread);
535}
[a35b458]536
[111b9b9]537/** Prepare for putting the thread to sleep.
538 *
539 * @returns whether the thread is currently terminating. If THREAD_OK
540 * is returned, the thread is guaranteed to be woken up instantly if the thread
541 * is terminated at any time between this function's return and
542 * thread_wait_finish(). If THREAD_TERMINATING is returned, the thread can still
543 * go to sleep, but doing so will delay termination.
544 */
545thread_termination_state_t thread_wait_start(void)
546{
547 assert(THREAD != NULL);
[a35b458]548
[111b9b9]549 /*
550 * This is an exchange rather than a store so that we can use the acquire
551 * semantics, which is needed to ensure that code after this operation sees
552 * memory ops made before thread_wakeup() in other thread, if that wakeup
553 * was reset by this operation.
554 *
555 * In particular, we need this to ensure we can't miss the thread being
556 * terminated concurrently with a synchronization primitive preparing to
557 * sleep.
558 */
559 (void) atomic_exchange_explicit(&THREAD->sleep_state, SLEEP_INITIAL,
560 memory_order_acquire);
[a35b458]561
[111b9b9]562 return THREAD->interrupted ? THREAD_TERMINATING : THREAD_OK;
563}
[a35b458]564
[111b9b9]565static void thread_wait_timeout_callback(void *arg)
566{
567 thread_wakeup(arg);
568}
569
570/**
571 * Suspends this thread's execution until thread_wakeup() is called on it,
572 * or deadline is reached.
573 *
574 * The way this would normally be used is that the current thread call
575 * thread_wait_start(), and if interruption has not been signaled, stores
576 * a reference to itself in a synchronized structure (such as waitq).
577 * After that, it releases any spinlocks it might hold and calls this function.
578 *
579 * The thread doing the wakeup will acquire the thread's reference from said
580 * synchronized structure and calls thread_wakeup() on it.
581 *
582 * Notably, there can be more than one thread performing wakeup.
583 * The number of performed calls to thread_wakeup(), or their relative
584 * ordering with thread_wait_finish(), does not matter. However, calls to
585 * thread_wakeup() are expected to be synchronized with thread_wait_start()
586 * with which they are associated, otherwise wakeups may be missed.
587 * However, the operation of thread_wakeup() is defined at any time,
588 * synchronization notwithstanding (in the sense of C un/defined behavior),
589 * and is in fact used to interrupt waiting threads by external events.
590 * The waiting thread must operate correctly in face of spurious wakeups,
591 * and clean up its reference in the synchronization structure if necessary.
592 *
593 * Returns THREAD_WAIT_TIMEOUT if timeout fired, which is a necessary condition
594 * for it to have been waken up by the timeout, but the caller must assume
595 * that proper wakeups, timeouts and interrupts may occur concurrently, so
596 * the fact timeout has been registered does not necessarily mean the thread
597 * has not been woken up or interrupted.
598 */
599thread_wait_result_t thread_wait_finish(deadline_t deadline)
600{
601 assert(THREAD != NULL);
602
603 timeout_t timeout;
604
[5663872]605 /* Extra check to avoid going to scheduler if we don't need to. */
606 if (atomic_load_explicit(&THREAD->sleep_state, memory_order_acquire) !=
607 SLEEP_INITIAL)
608 return THREAD_WAIT_SUCCESS;
[111b9b9]609
[5663872]610 if (deadline != DEADLINE_NEVER) {
[111b9b9]611 timeout_initialize(&timeout);
612 timeout_register_deadline(&timeout, deadline,
613 thread_wait_timeout_callback, THREAD);
614 }
615
[151c050]616 scheduler_enter(Sleeping);
[111b9b9]617
618 if (deadline != DEADLINE_NEVER && !timeout_unregister(&timeout)) {
619 return THREAD_WAIT_TIMEOUT;
620 } else {
621 return THREAD_WAIT_SUCCESS;
622 }
623}
624
625void thread_wakeup(thread_t *thread)
626{
627 assert(thread != NULL);
628
629 int state = atomic_exchange_explicit(&thread->sleep_state, SLEEP_WOKE,
[5663872]630 memory_order_acq_rel);
[111b9b9]631
632 if (state == SLEEP_ASLEEP) {
633 /*
634 * Only one thread gets to do this.
635 * The reference consumed here is the reference implicitly passed to
636 * the waking thread by the sleeper in thread_wait_finish().
637 */
638 thread_ready(thread);
639 }
[518dd43]640}
641
[43ac0cc]642/** Prevent the current thread from being migrated to another processor. */
643void thread_migration_disable(void)
644{
[63e27ef]645 assert(THREAD);
[a35b458]646
[43ac0cc]647 THREAD->nomigrate++;
648}
649
650/** Allow the current thread to be migrated to another processor. */
651void thread_migration_enable(void)
652{
[63e27ef]653 assert(THREAD);
654 assert(THREAD->nomigrate > 0);
[a35b458]655
[6eef3c4]656 if (THREAD->nomigrate > 0)
657 THREAD->nomigrate--;
[43ac0cc]658}
659
[70527f1]660/** Thread sleep
661 *
662 * Suspend execution of the current thread.
663 *
664 * @param sec Number of seconds to sleep.
665 *
666 */
[7f1c620]667void thread_sleep(uint32_t sec)
[f761f1eb]668{
[7c3fb9b]669 /*
670 * Sleep in 1000 second steps to support
671 * full argument range
672 */
[22e6802]673 while (sec > 0) {
674 uint32_t period = (sec > 1000) ? 1000 : sec;
[a35b458]675
[22e6802]676 thread_usleep(period * 1000000);
677 sec -= period;
678 }
[f761f1eb]679}
[70527f1]680
[5110d0a]681errno_t thread_join(thread_t *thread)
682{
683 return thread_join_timeout(thread, SYNCH_NO_TIMEOUT, SYNCH_FLAGS_NONE);
684}
685
[fe19611]686/** Wait for another thread to exit.
[1871118]687 * This function does not destroy the thread. Reference counting handles that.
[fe19611]688 *
[da1bafb]689 * @param thread Thread to join on exit.
690 * @param usec Timeout in microseconds.
691 * @param flags Mode of operation.
[fe19611]692 *
693 * @return An error code from errno.h or an error code from synch.h.
[da1bafb]694 *
[fe19611]695 */
[b7fd2a0]696errno_t thread_join_timeout(thread_t *thread, uint32_t usec, unsigned int flags)
[fe19611]697{
[da1bafb]698 if (thread == THREAD)
[fe19611]699 return EINVAL;
[a35b458]700
[da1bafb]701 irq_spinlock_lock(&thread->lock, true);
[1871118]702 state_t state = thread->state;
[da1bafb]703 irq_spinlock_unlock(&thread->lock, true);
[a35b458]704
[1871118]705 if (state == Exiting) {
706 return EOK;
[fe19611]707 } else {
[111b9b9]708 return _waitq_sleep_timeout(&thread->join_wq, usec, flags);
[fe19611]709 }
710}
711
[70527f1]712/** Thread usleep
713 *
714 * Suspend execution of the current thread.
715 *
716 * @param usec Number of microseconds to sleep.
717 *
[1b20da0]718 */
[7f1c620]719void thread_usleep(uint32_t usec)
[f761f1eb]720{
721 waitq_t wq;
[a35b458]722
[f761f1eb]723 waitq_initialize(&wq);
[a35b458]724
[111b9b9]725 (void) waitq_sleep_timeout(&wq, usec);
[151c050]726}
727
728/** Allow other threads to run. */
729void thread_yield(void)
730{
731 assert(THREAD != NULL);
732 scheduler_enter(Running);
[f761f1eb]733}
734
[ef1eab7]735static void thread_print(thread_t *thread, bool additional)
[5dcee525]736{
[1ba37fa]737 uint64_t ucycles, kcycles;
738 char usuffix, ksuffix;
[da1bafb]739 order_suffix(thread->ucycles, &ucycles, &usuffix);
740 order_suffix(thread->kcycles, &kcycles, &ksuffix);
[a35b458]741
[577f042a]742 char *name;
743 if (str_cmp(thread->name, "uinit") == 0)
744 name = thread->task->name;
745 else
746 name = thread->name;
[a35b458]747
[ef1eab7]748 if (additional)
[c1b073b7]749 printf("%-8" PRIu64 " %p %p %9" PRIu64 "%c %9" PRIu64 "%c ",
[577f042a]750 thread->tid, thread->thread_code, thread->kstack,
751 ucycles, usuffix, kcycles, ksuffix);
[48dcc69]752 else
[c1b073b7]753 printf("%-8" PRIu64 " %-14s %p %-8s %p %-5" PRIu32 "\n",
[577f042a]754 thread->tid, name, thread, thread_states[thread->state],
[26aafe8]755 thread->task, thread->task->container);
[a35b458]756
[ef1eab7]757 if (additional) {
[48dcc69]758 if (thread->cpu)
759 printf("%-5u", thread->cpu->id);
760 else
761 printf("none ");
[a35b458]762
[48dcc69]763 if (thread->state == Sleeping) {
[c1b073b7]764 printf(" %p", thread->sleep_queue);
[48dcc69]765 }
[a35b458]766
[48dcc69]767 printf("\n");
[43b1e86]768 }
[5dcee525]769}
770
[da1bafb]771/** Print list of threads debug info
[48dcc69]772 *
773 * @param additional Print additional information.
[da1bafb]774 *
775 */
[48dcc69]776void thread_print_list(bool additional)
[55ab0f1]777{
[ef1eab7]778 thread_t *thread;
779
[1871118]780 /* Accessing system-wide threads list through thread_first()/thread_next(). */
[da1bafb]781 irq_spinlock_lock(&threads_lock, true);
[a35b458]782
[c1b073b7]783 if (sizeof(void *) <= 4) {
784 if (additional)
785 printf("[id ] [code ] [stack ] [ucycles ] [kcycles ]"
786 " [cpu] [waitqueue]\n");
787 else
788 printf("[id ] [name ] [address ] [state ] [task ]"
789 " [ctn]\n");
790 } else {
791 if (additional) {
792 printf("[id ] [code ] [stack ] [ucycles ] [kcycles ]"
793 " [cpu] [waitqueue ]\n");
794 } else
795 printf("[id ] [name ] [address ] [state ]"
796 " [task ] [ctn]\n");
797 }
[a35b458]798
[aab5e46]799 thread = thread_first();
800 while (thread != NULL) {
[ef1eab7]801 thread_print(thread, additional);
[aab5e46]802 thread = thread_next(thread);
[ef1eab7]803 }
[a35b458]804
[da1bafb]805 irq_spinlock_unlock(&threads_lock, true);
[55ab0f1]806}
[9f52563]807
[1871118]808static bool thread_exists(thread_t *thread)
[016acbe]809{
[ef1eab7]810 odlink_t *odlink = odict_find_eq(&threads, thread, NULL);
811 return odlink != NULL;
[016acbe]812}
813
[1871118]814/** Check whether the thread exists, and if so, return a reference to it.
815 */
816thread_t *thread_try_get(thread_t *thread)
817{
818 irq_spinlock_lock(&threads_lock, true);
819
820 if (thread_exists(thread)) {
821 /* Try to strengthen the reference. */
822 thread = thread_try_ref(thread);
823 } else {
824 thread = NULL;
825 }
826
827 irq_spinlock_unlock(&threads_lock, true);
828
829 return thread;
830}
831
[cce6acf]832/** Update accounting of current thread.
833 *
834 * Note that thread_lock on THREAD must be already held and
835 * interrupts must be already disabled.
836 *
[da1bafb]837 * @param user True to update user accounting, false for kernel.
838 *
[cce6acf]839 */
[a2a00e8]840void thread_update_accounting(bool user)
[cce6acf]841{
842 uint64_t time = get_cycle();
[1d432f9]843
[63e27ef]844 assert(interrupts_disabled());
845 assert(irq_spinlock_locked(&THREAD->lock));
[a35b458]846
[da1bafb]847 if (user)
[a2a00e8]848 THREAD->ucycles += time - THREAD->last_cycle;
[da1bafb]849 else
[a2a00e8]850 THREAD->kcycles += time - THREAD->last_cycle;
[a35b458]851
[cce6acf]852 THREAD->last_cycle = time;
853}
854
[e1b6742]855/** Find thread structure corresponding to thread ID.
856 *
857 * The threads_lock must be already held by the caller of this function and
858 * interrupts must be disabled.
859 *
[1871118]860 * The returned reference is weak.
861 * If the caller needs to keep it, thread_try_ref() must be used to upgrade
862 * to a strong reference _before_ threads_lock is released.
863 *
[e1b6742]864 * @param id Thread ID.
865 *
866 * @return Thread structure address or NULL if there is no such thread ID.
867 *
868 */
869thread_t *thread_find_by_id(thread_id_t thread_id)
870{
[ef1eab7]871 thread_t *thread;
872
[63e27ef]873 assert(interrupts_disabled());
874 assert(irq_spinlock_locked(&threads_lock));
[a35b458]875
[aab5e46]876 thread = thread_first();
877 while (thread != NULL) {
[ef1eab7]878 if (thread->tid == thread_id)
879 return thread;
[a35b458]880
[aab5e46]881 thread = thread_next(thread);
[ef1eab7]882 }
[a35b458]883
[ef1eab7]884 return NULL;
[e1b6742]885}
886
[aab5e46]887/** Get count of threads.
888 *
889 * @return Number of threads in the system
890 */
891size_t thread_count(void)
892{
893 assert(interrupts_disabled());
894 assert(irq_spinlock_locked(&threads_lock));
895
896 return odict_count(&threads);
897}
898
899/** Get first thread.
900 *
901 * @return Pointer to first thread or @c NULL if there are none.
902 */
903thread_t *thread_first(void)
904{
905 odlink_t *odlink;
906
907 assert(interrupts_disabled());
908 assert(irq_spinlock_locked(&threads_lock));
909
910 odlink = odict_first(&threads);
911 if (odlink == NULL)
912 return NULL;
913
914 return odict_get_instance(odlink, thread_t, lthreads);
915}
916
917/** Get next thread.
918 *
919 * @param cur Current thread
920 * @return Pointer to next thread or @c NULL if there are no more threads.
921 */
922thread_t *thread_next(thread_t *cur)
923{
924 odlink_t *odlink;
925
926 assert(interrupts_disabled());
927 assert(irq_spinlock_locked(&threads_lock));
928
929 odlink = odict_next(&cur->lthreads, &threads);
930 if (odlink == NULL)
931 return NULL;
932
933 return odict_get_instance(odlink, thread_t, lthreads);
934}
935
[5b7a107]936#ifdef CONFIG_UDEBUG
937
[df58e44]938void thread_stack_trace(thread_id_t thread_id)
939{
940 irq_spinlock_lock(&threads_lock, true);
[1871118]941 thread_t *thread = thread_try_ref(thread_find_by_id(thread_id));
942 irq_spinlock_unlock(&threads_lock, true);
[a35b458]943
[df58e44]944 if (thread == NULL) {
945 printf("No such thread.\n");
946 return;
947 }
[a35b458]948
[df58e44]949 /*
950 * Schedule a stack trace to be printed
951 * just before the thread is scheduled next.
952 *
953 * If the thread is sleeping then try to interrupt
954 * the sleep. Any request for printing an uspace stack
955 * trace from within the kernel should be always
956 * considered a last resort debugging means, therefore
957 * forcing the thread's sleep to be interrupted
958 * is probably justifiable.
959 */
[a35b458]960
[1871118]961 irq_spinlock_lock(&thread->lock, true);
962
[df58e44]963 bool sleeping = false;
964 istate_t *istate = thread->udebug.uspace_state;
965 if (istate != NULL) {
966 printf("Scheduling thread stack trace.\n");
967 thread->btrace = true;
968 if (thread->state == Sleeping)
969 sleeping = true;
970 } else
971 printf("Thread interrupt state not available.\n");
[a35b458]972
[1871118]973 irq_spinlock_unlock(&thread->lock, true);
[a35b458]974
[df58e44]975 if (sleeping)
[111b9b9]976 thread_wakeup(thread);
[a35b458]977
[1871118]978 thread_put(thread);
[df58e44]979}
[e1b6742]980
[5b7a107]981#endif /* CONFIG_UDEBUG */
[e1b6742]982
[ef1eab7]983/** Get key function for the @c threads ordered dictionary.
984 *
985 * @param odlink Link
986 * @return Pointer to thread structure cast as 'void *'
987 */
988static void *threads_getkey(odlink_t *odlink)
989{
990 thread_t *thread = odict_get_instance(odlink, thread_t, lthreads);
991 return (void *) thread;
992}
993
994/** Key comparison function for the @c threads ordered dictionary.
995 *
996 * @param a Pointer to thread A
997 * @param b Pointer to thread B
998 * @return -1, 0, 1 iff pointer to A is less than, equal to, greater than B
999 */
1000static int threads_cmp(void *a, void *b)
1001{
1002 if (a > b)
1003 return -1;
1004 else if (a == b)
1005 return 0;
1006 else
1007 return +1;
1008}
1009
[9f52563]1010/** Process syscall to create new thread.
1011 *
1012 */
[5a5269d]1013sys_errno_t sys_thread_create(uspace_ptr_uspace_arg_t uspace_uarg, uspace_ptr_char uspace_name,
1014 size_t name_len, uspace_ptr_thread_id_t uspace_thread_id)
[9f52563]1015{
[24345a5]1016 if (name_len > THREAD_NAME_BUFLEN - 1)
[7faabb7]1017 name_len = THREAD_NAME_BUFLEN - 1;
[a35b458]1018
[da1bafb]1019 char namebuf[THREAD_NAME_BUFLEN];
[b7fd2a0]1020 errno_t rc = copy_from_uspace(namebuf, uspace_name, name_len);
[a53ed3a]1021 if (rc != EOK)
[b7fd2a0]1022 return (sys_errno_t) rc;
[a35b458]1023
[b60c582]1024 namebuf[name_len] = 0;
[a35b458]1025
[4680ef5]1026 /*
1027 * In case of failure, kernel_uarg will be deallocated in this function.
1028 * In case of success, kernel_uarg will be freed in uinit().
1029 */
[da1bafb]1030 uspace_arg_t *kernel_uarg =
[11b285d]1031 (uspace_arg_t *) malloc(sizeof(uspace_arg_t));
[7473807]1032 if (!kernel_uarg)
1033 return (sys_errno_t) ENOMEM;
[a35b458]1034
[e3c762cd]1035 rc = copy_from_uspace(kernel_uarg, uspace_uarg, sizeof(uspace_arg_t));
[a53ed3a]1036 if (rc != EOK) {
[e3c762cd]1037 free(kernel_uarg);
[b7fd2a0]1038 return (sys_errno_t) rc;
[e3c762cd]1039 }
[a35b458]1040
[da1bafb]1041 thread_t *thread = thread_create(uinit, kernel_uarg, TASK,
[6eef3c4]1042 THREAD_FLAG_USPACE | THREAD_FLAG_NOATTACH, namebuf);
[da1bafb]1043 if (thread) {
[5a5269d]1044 if (uspace_thread_id) {
[da1bafb]1045 rc = copy_to_uspace(uspace_thread_id, &thread->tid,
1046 sizeof(thread->tid));
[a53ed3a]1047 if (rc != EOK) {
[d8431986]1048 /*
1049 * We have encountered a failure, but the thread
1050 * has already been created. We need to undo its
1051 * creation now.
1052 */
[a35b458]1053
[d8431986]1054 /*
[ea7890e7]1055 * The new thread structure is initialized, but
1056 * is still not visible to the system.
[d8431986]1057 * We can safely deallocate it.
1058 */
[82d515e9]1059 slab_free(thread_cache, thread);
[da1bafb]1060 free(kernel_uarg);
[a35b458]1061
[b7fd2a0]1062 return (sys_errno_t) rc;
[3bacee1]1063 }
[d8431986]1064 }
[a35b458]1065
[9a1b20c]1066#ifdef CONFIG_UDEBUG
[13964ef]1067 /*
1068 * Generate udebug THREAD_B event and attach the thread.
1069 * This must be done atomically (with the debug locks held),
1070 * otherwise we would either miss some thread or receive
1071 * THREAD_B events for threads that already existed
1072 * and could be detected with THREAD_READ before.
1073 */
[da1bafb]1074 udebug_thread_b_event_attach(thread, TASK);
[13964ef]1075#else
[da1bafb]1076 thread_attach(thread, TASK);
[9a1b20c]1077#endif
[da1bafb]1078 thread_ready(thread);
[a35b458]1079
[d8431986]1080 return 0;
[201abde]1081 } else
[0f250f9]1082 free(kernel_uarg);
[a35b458]1083
[b7fd2a0]1084 return (sys_errno_t) ENOMEM;
[9f52563]1085}
1086
1087/** Process syscall to terminate thread.
1088 *
1089 */
[b7fd2a0]1090sys_errno_t sys_thread_exit(int uspace_status)
[9f52563]1091{
[68091bd]1092 thread_exit();
[9f52563]1093}
[b45c443]1094
[3ce7f082]1095/** Syscall for getting TID.
1096 *
[201abde]1097 * @param uspace_thread_id Userspace address of 8-byte buffer where to store
1098 * current thread ID.
1099 *
1100 * @return 0 on success or an error code from @ref errno.h.
[da1bafb]1101 *
[b45c443]1102 */
[5a5269d]1103sys_errno_t sys_thread_get_id(uspace_ptr_thread_id_t uspace_thread_id)
[3ce7f082]1104{
1105 /*
1106 * No need to acquire lock on THREAD because tid
1107 * remains constant for the lifespan of the thread.
[da1bafb]1108 *
[3ce7f082]1109 */
[b7fd2a0]1110 return (sys_errno_t) copy_to_uspace(uspace_thread_id, &THREAD->tid,
[201abde]1111 sizeof(THREAD->tid));
[3ce7f082]1112}
[6f4495f5]1113
[d9ece1cb]1114/** Syscall wrapper for sleeping. */
[b7fd2a0]1115sys_errno_t sys_thread_usleep(uint32_t usec)
[d9ece1cb]1116{
[22e6802]1117 thread_usleep(usec);
[d9ece1cb]1118 return 0;
1119}
1120
[b7fd2a0]1121sys_errno_t sys_thread_udelay(uint32_t usec)
[7e7b791]1122{
[8d6c1f1]1123 delay(usec);
[7e7b791]1124 return 0;
1125}
1126
[3ce7f082]1127/** @}
1128 */
Note: See TracBrowser for help on using the repository browser.