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

Last change on this file since 8300c72 was f35749e, checked in by Jiri Svoboda <jiri@…>, 10 months ago

System restart via shutdown -r

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