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

ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since c7326f21 was c7326f21, checked in by Jiří Zárevúcky <zarevucky.jiri@…>, 2 years ago

Move some oddly placed accounting code

Thread ucycles and kcycles should be transferred to the task
accounting when a thread is destroyed, regardless of the
circumstances of its exit. The original code seems to only
do so when a thread returns from its implementing function.

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