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

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

Allow thread_create_arch() to fail

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