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

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

Reorganize locking in thread_destroy()

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