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

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

Always allocate FPU context ahead of time, even when switching is lazy

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