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

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

Remove unnecessary function

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