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

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

Change (rc != 0) to (rc != EOK), where appropriate.

  • Property mode set to 100644
File size: 25.5 KB
RevLine 
[f761f1eb]1/*
[7ed8530]2 * Copyright (c) 2010 Jakub Jermar
[f761f1eb]3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 *
9 * - Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 * - The name of the author may not be used to endorse or promote products
15 * derived from this software without specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 */
28
[cc73a8a1]29/** @addtogroup genericproc
[b45c443]30 * @{
31 */
32
[9179d0a]33/**
[b45c443]34 * @file
[da1bafb]35 * @brief Thread management functions.
[9179d0a]36 */
37
[63e27ef]38#include <assert.h>
[f761f1eb]39#include <proc/scheduler.h>
40#include <proc/thread.h>
41#include <proc/task.h>
42#include <mm/frame.h>
43#include <mm/page.h>
44#include <arch/asm.h>
[cce6acf]45#include <arch/cycle.h>
[f761f1eb]46#include <arch.h>
47#include <synch/spinlock.h>
48#include <synch/waitq.h>
[8a64e81e]49#include <synch/workqueue.h>
[181a746]50#include <synch/rcu.h>
[f761f1eb]51#include <cpu.h>
[e535eeb]52#include <str.h>
[f761f1eb]53#include <context.h>
[5dcee525]54#include <adt/avl.h>
[5c9a08b]55#include <adt/list.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>
[55ab0f1]65#include <print.h>
[266294a9]66#include <mm/slab.h>
[9f52563]67#include <main/uinit.h>
[e3c762cd]68#include <syscall/copy.h>
69#include <errno.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
82typedef struct {
83 thread_id_t thread_id;
84 thread_t *thread;
85} thread_iterator_t;
[f761f1eb]86
[5dcee525]87/** Lock protecting the threads_tree AVL tree.
[4e33b6b]88 *
89 * For locking rules, see declaration thereof.
[da1bafb]90 *
[4e33b6b]91 */
[da1bafb]92IRQ_SPINLOCK_INITIALIZE(threads_lock);
[88169d9]93
[81c0171e]94/** AVL tree of all threads.
[88169d9]95 *
[5dcee525]96 * When a thread is found in the threads_tree AVL tree, it is guaranteed to
[4e33b6b]97 * exist as long as the threads_lock is held.
[da1bafb]98 *
[88169d9]99 */
[da1bafb]100avltree_t threads_tree;
[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
[0f81ceb7]107#ifdef CONFIG_FPU
[82d515e9]108slab_cache_t *fpu_context_cache;
[f76fed4]109#endif
[266294a9]110
[4e33b6b]111/** Thread wrapper.
[70527f1]112 *
[4e33b6b]113 * This wrapper is provided to ensure that every thread makes a call to
114 * thread_exit() when its implementing function returns.
[f761f1eb]115 *
[22f7769]116 * interrupts_disable() is assumed.
[70527f1]117 *
[f761f1eb]118 */
[e16e036a]119static void cushion(void)
[f761f1eb]120{
[43114c5]121 void (*f)(void *) = THREAD->thread_code;
122 void *arg = THREAD->thread_arg;
[449dc1ed]123 THREAD->last_cycle = get_cycle();
[da1bafb]124
[0313ff0]125 /* This is where each thread wakes up after its creation */
[da1bafb]126 irq_spinlock_unlock(&THREAD->lock, false);
[22f7769]127 interrupts_enable();
[da1bafb]128
[f761f1eb]129 f(arg);
[0313ff0]130
131 /* Accumulate accounting to the task */
[da1bafb]132 irq_spinlock_lock(&THREAD->lock, true);
[62b6d17]133 if (!THREAD->uncounted) {
[a2a00e8]134 thread_update_accounting(true);
135 uint64_t ucycles = THREAD->ucycles;
136 THREAD->ucycles = 0;
137 uint64_t kcycles = THREAD->kcycles;
138 THREAD->kcycles = 0;
[62b6d17]139
[da1bafb]140 irq_spinlock_pass(&THREAD->lock, &TASK->lock);
[a2a00e8]141 TASK->ucycles += ucycles;
142 TASK->kcycles += kcycles;
[da1bafb]143 irq_spinlock_unlock(&TASK->lock, true);
[62b6d17]144 } else
[da1bafb]145 irq_spinlock_unlock(&THREAD->lock, true);
[0313ff0]146
[f761f1eb]147 thread_exit();
[da1bafb]148
149 /* Not reached */
[f761f1eb]150}
151
[da1bafb]152/** Initialization and allocation for thread_t structure
153 *
154 */
[b7fd2a0]155static errno_t thr_constructor(void *obj, unsigned int kmflags)
[266294a9]156{
[da1bafb]157 thread_t *thread = (thread_t *) obj;
158
159 irq_spinlock_initialize(&thread->lock, "thread_t_lock");
160 link_initialize(&thread->rq_link);
161 link_initialize(&thread->wq_link);
162 link_initialize(&thread->th_link);
163
[32fffef0]164 /* call the architecture-specific part of the constructor */
[da1bafb]165 thr_constructor_arch(thread);
[266294a9]166
[0f81ceb7]167#ifdef CONFIG_FPU
[d8431986]168#ifdef CONFIG_FPU_LAZY
[da1bafb]169 thread->saved_fpu_context = NULL;
170#else /* CONFIG_FPU_LAZY */
[82d515e9]171 thread->saved_fpu_context = slab_alloc(fpu_context_cache, kmflags);
[da1bafb]172 if (!thread->saved_fpu_context)
[7f11dc6]173 return ENOMEM;
[da1bafb]174#endif /* CONFIG_FPU_LAZY */
175#endif /* CONFIG_FPU */
176
[38ff925]177 /*
178 * Allocate the kernel stack from the low-memory to prevent an infinite
179 * nesting of TLB-misses when accessing the stack from the part of the
180 * TLB-miss handler written in C.
181 *
182 * Note that low-memory is safe to be used for the stack as it will be
183 * covered by the kernel identity mapping, which guarantees not to
184 * nest TLB-misses infinitely (either via some hardware mechanism or
185 * by the construciton of the assembly-language part of the TLB-miss
186 * handler).
187 *
188 * This restriction can be lifted once each architecture provides
189 * a similar guarantee, for example by locking the kernel stack
190 * in the TLB whenever it is allocated from the high-memory and the
191 * thread is being scheduled to run.
192 */
193 kmflags |= FRAME_LOWMEM;
194 kmflags &= ~FRAME_HIGHMEM;
[6eef3c4]195
[cd3b380]196 uintptr_t stack_phys =
197 frame_alloc(STACK_FRAMES, kmflags, STACK_SIZE - 1);
198 if (!stack_phys) {
[0f81ceb7]199#ifdef CONFIG_FPU
[da1bafb]200 if (thread->saved_fpu_context)
[82d515e9]201 slab_free(fpu_context_cache, thread->saved_fpu_context);
[f76fed4]202#endif
[7f11dc6]203 return ENOMEM;
[f76fed4]204 }
[da1bafb]205
[cd3b380]206 thread->kstack = (uint8_t *) PA2KA(stack_phys);
207
[9a1b20c]208#ifdef CONFIG_UDEBUG
[da1bafb]209 mutex_initialize(&thread->udebug.lock, MUTEX_PASSIVE);
[9a1b20c]210#endif
[da1bafb]211
[7f11dc6]212 return EOK;
[266294a9]213}
214
215/** Destruction of thread_t object */
[da1bafb]216static size_t thr_destructor(void *obj)
[266294a9]217{
[da1bafb]218 thread_t *thread = (thread_t *) obj;
219
[32fffef0]220 /* call the architecture-specific part of the destructor */
[da1bafb]221 thr_destructor_arch(thread);
222
[5df1963]223 frame_free(KA2PA(thread->kstack), STACK_FRAMES);
[da1bafb]224
[0f81ceb7]225#ifdef CONFIG_FPU
[da1bafb]226 if (thread->saved_fpu_context)
[82d515e9]227 slab_free(fpu_context_cache, thread->saved_fpu_context);
[f76fed4]228#endif
[da1bafb]229
[e7c4115d]230 return STACK_FRAMES; /* number of frames freed */
[266294a9]231}
[70527f1]232
233/** Initialize threads
234 *
235 * Initialize kernel threads support.
236 *
237 */
[f761f1eb]238void thread_init(void)
239{
[43114c5]240 THREAD = NULL;
[da1bafb]241
[7217199]242 atomic_set(&nrdy, 0);
[82d515e9]243 thread_cache = slab_cache_create("thread_t", sizeof(thread_t), 0,
[6f4495f5]244 thr_constructor, thr_destructor, 0);
[da1bafb]245
[0f81ceb7]246#ifdef CONFIG_FPU
[82d515e9]247 fpu_context_cache = slab_cache_create("fpu_context_t",
[f97f1e51]248 sizeof(fpu_context_t), FPU_CONTEXT_ALIGN, NULL, NULL, 0);
[f76fed4]249#endif
[da1bafb]250
[5dcee525]251 avltree_create(&threads_tree);
[016acbe]252}
[70527f1]253
[6eef3c4]254/** Wire thread to the given CPU
255 *
256 * @param cpu CPU to wire the thread to.
257 *
258 */
259void thread_wire(thread_t *thread, cpu_t *cpu)
260{
261 irq_spinlock_lock(&thread->lock, true);
262 thread->cpu = cpu;
263 thread->wired = true;
264 irq_spinlock_unlock(&thread->lock, true);
265}
266
[8a64e81e]267/** Invoked right before thread_ready() readies the thread. thread is locked. */
268static void before_thread_is_ready(thread_t *thread)
269{
[63e27ef]270 assert(irq_spinlock_locked(&thread->lock));
[8a64e81e]271 workq_before_thread_is_ready(thread);
272}
273
[70527f1]274/** Make thread ready
275 *
[da1bafb]276 * Switch thread to the ready state.
[70527f1]277 *
[df58e44]278 * @param thread Thread to make ready.
[70527f1]279 *
280 */
[da1bafb]281void thread_ready(thread_t *thread)
[f761f1eb]282{
[da1bafb]283 irq_spinlock_lock(&thread->lock, true);
[f761f1eb]284
[63e27ef]285 assert(thread->state != Ready);
[518dd43]286
[8a64e81e]287 before_thread_is_ready(thread);
[da1bafb]288
[6eef3c4]289 int i = (thread->priority < RQ_COUNT - 1) ?
290 ++thread->priority : thread->priority;
[518dd43]291
[8ad7dd1]292 cpu_t *cpu;
293 if (thread->wired || thread->nomigrate || thread->fpu_context_engaged) {
294 /* Cannot ready to another CPU */
[63e27ef]295 assert(thread->cpu != NULL);
[8ad7dd1]296 cpu = thread->cpu;
297 } else if (thread->stolen) {
298 /* Ready to the stealing CPU */
[6eef3c4]299 cpu = CPU;
[8ad7dd1]300 } else if (thread->cpu) {
301 /* Prefer the CPU on which the thread ran last */
[63e27ef]302 assert(thread->cpu != NULL);
[8ad7dd1]303 cpu = thread->cpu;
304 } else {
305 cpu = CPU;
306 }
[6eef3c4]307
[da1bafb]308 thread->state = Ready;
309
310 irq_spinlock_pass(&thread->lock, &(cpu->rq[i].lock));
[f761f1eb]311
[70527f1]312 /*
[da1bafb]313 * Append thread to respective ready queue
314 * on respective processor.
[f761f1eb]315 */
[da1bafb]316
[55b77d9]317 list_append(&thread->rq_link, &cpu->rq[i].rq);
[da1bafb]318 cpu->rq[i].n++;
319 irq_spinlock_unlock(&(cpu->rq[i].lock), true);
320
[59e07c91]321 atomic_inc(&nrdy);
[248fc1a]322 atomic_inc(&cpu->nrdy);
[f761f1eb]323}
324
[70527f1]325/** Create new thread
326 *
327 * Create a new thread.
328 *
[da1bafb]329 * @param func Thread's implementing function.
330 * @param arg Thread's implementing function argument.
331 * @param task Task to which the thread belongs. The caller must
332 * guarantee that the task won't cease to exist during the
333 * call. The task's lock may not be held.
334 * @param flags Thread flags.
335 * @param name Symbolic name (a copy is made).
[70527f1]336 *
[da1bafb]337 * @return New thread's structure on success, NULL on failure.
[70527f1]338 *
339 */
[4e33b6b]340thread_t *thread_create(void (* func)(void *), void *arg, task_t *task,
[6eef3c4]341 thread_flags_t flags, const char *name)
[f761f1eb]342{
[82d515e9]343 thread_t *thread = (thread_t *) slab_alloc(thread_cache, 0);
[da1bafb]344 if (!thread)
[2a46e10]345 return NULL;
[aa8d0f7]346
[bb68433]347 /* Not needed, but good for debugging */
[26aafe8]348 memsetb(thread->kstack, STACK_SIZE, 0);
[bb68433]349
[da1bafb]350 irq_spinlock_lock(&tidlock, true);
351 thread->tid = ++last_tid;
352 irq_spinlock_unlock(&tidlock, true);
[bb68433]353
[da1bafb]354 context_save(&thread->saved_context);
355 context_set(&thread->saved_context, FADDR(cushion),
[26aafe8]356 (uintptr_t) thread->kstack, STACK_SIZE);
[bb68433]357
[da1bafb]358 the_initialize((the_t *) thread->kstack);
[bb68433]359
[da1bafb]360 ipl_t ipl = interrupts_disable();
361 thread->saved_context.ipl = interrupts_read();
[bb68433]362 interrupts_restore(ipl);
363
[da1bafb]364 str_cpy(thread->name, THREAD_NAME_BUFLEN, name);
365
366 thread->thread_code = func;
367 thread->thread_arg = arg;
368 thread->ticks = -1;
369 thread->ucycles = 0;
370 thread->kcycles = 0;
[6eef3c4]371 thread->uncounted =
372 ((flags & THREAD_FLAG_UNCOUNTED) == THREAD_FLAG_UNCOUNTED);
[da1bafb]373 thread->priority = -1; /* Start in rq[0] */
374 thread->cpu = NULL;
[6eef3c4]375 thread->wired = false;
376 thread->stolen = false;
377 thread->uspace =
378 ((flags & THREAD_FLAG_USPACE) == THREAD_FLAG_USPACE);
379
[43ac0cc]380 thread->nomigrate = 0;
[da1bafb]381 thread->state = Entering;
382
383 timeout_initialize(&thread->sleep_timeout);
384 thread->sleep_interruptible = false;
385 thread->sleep_queue = NULL;
386 thread->timeout_pending = false;
387
388 thread->in_copy_from_uspace = false;
389 thread->in_copy_to_uspace = false;
390
391 thread->interrupted = false;
392 thread->detached = false;
393 waitq_initialize(&thread->join_wq);
394
395 thread->task = task;
396
[8a64e81e]397 thread->workq = NULL;
398
[6eef3c4]399 thread->fpu_context_exists = false;
400 thread->fpu_context_engaged = false;
[da1bafb]401
402 avltree_node_initialize(&thread->threads_tree_node);
403 thread->threads_tree_node.key = (uintptr_t) thread;
[bb68433]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
[da1bafb]410
411 /* Might depend on previous initialization */
412 thread_create_arch(thread);
413
[181a746]414 rcu_thread_init(thread);
415
[6eef3c4]416 if ((flags & THREAD_FLAG_NOATTACH) != THREAD_FLAG_NOATTACH)
[da1bafb]417 thread_attach(thread, task);
418
419 return thread;
[d8431986]420}
421
422/** Destroy thread memory structure
423 *
424 * Detach thread from all queues, cpus etc. and destroy it.
[da1bafb]425 *
426 * @param thread Thread to be destroyed.
427 * @param irq_res Indicate whether it should unlock thread->lock
428 * in interrupts-restore mode.
[d8431986]429 *
430 */
[da1bafb]431void thread_destroy(thread_t *thread, bool irq_res)
[d8431986]432{
[63e27ef]433 assert(irq_spinlock_locked(&thread->lock));
434 assert((thread->state == Exiting) || (thread->state == Lingering));
435 assert(thread->task);
436 assert(thread->cpu);
[da1bafb]437
438 irq_spinlock_lock(&thread->cpu->lock, false);
439 if (thread->cpu->fpu_owner == thread)
440 thread->cpu->fpu_owner = NULL;
441 irq_spinlock_unlock(&thread->cpu->lock, false);
442
443 irq_spinlock_pass(&thread->lock, &threads_lock);
444
445 avltree_delete(&threads_tree, &thread->threads_tree_node);
446
447 irq_spinlock_pass(&threads_lock, &thread->task->lock);
448
[d8431986]449 /*
450 * Detach from the containing task.
451 */
[da1bafb]452 list_remove(&thread->th_link);
453 irq_spinlock_unlock(&thread->task->lock, irq_res);
454
[ea7890e7]455 /*
[7ed8530]456 * Drop the reference to the containing task.
[ea7890e7]457 */
[da1bafb]458 task_release(thread->task);
[82d515e9]459 slab_free(thread_cache, thread);
[d8431986]460}
461
462/** Make the thread visible to the system.
463 *
464 * Attach the thread structure to the current task and make it visible in the
[5dcee525]465 * threads_tree.
[d8431986]466 *
[da1bafb]467 * @param t Thread to be attached to the task.
468 * @param task Task to which the thread is to be attached.
469 *
[d8431986]470 */
[da1bafb]471void thread_attach(thread_t *thread, task_t *task)
[d8431986]472{
473 /*
[9a1b20c]474 * Attach to the specified task.
[d8431986]475 */
[da1bafb]476 irq_spinlock_lock(&task->lock, true);
477
[7ed8530]478 /* Hold a reference to the task. */
479 task_hold(task);
[da1bafb]480
[9a1b20c]481 /* Must not count kbox thread into lifecount */
[6eef3c4]482 if (thread->uspace)
[9a1b20c]483 atomic_inc(&task->lifecount);
[da1bafb]484
[55b77d9]485 list_append(&thread->th_link, &task->threads);
[da1bafb]486
487 irq_spinlock_pass(&task->lock, &threads_lock);
488
[bb68433]489 /*
490 * Register this thread in the system-wide list.
491 */
[da1bafb]492 avltree_insert(&threads_tree, &thread->threads_tree_node);
493 irq_spinlock_unlock(&threads_lock, true);
[f761f1eb]494}
495
[0182a665]496/** Terminate thread.
[70527f1]497 *
[da1bafb]498 * End current thread execution and switch it to the exiting state.
499 * All pending timeouts are executed.
500 *
[70527f1]501 */
[f761f1eb]502void thread_exit(void)
503{
[6eef3c4]504 if (THREAD->uspace) {
[9a1b20c]505#ifdef CONFIG_UDEBUG
506 /* Generate udebug THREAD_E event */
507 udebug_thread_e_event();
[6eef3c4]508
[0ac99db]509 /*
510 * This thread will not execute any code or system calls from
511 * now on.
512 */
513 udebug_stoppable_begin();
[9a1b20c]514#endif
515 if (atomic_predec(&TASK->lifecount) == 0) {
516 /*
517 * We are the last userspace thread in the task that
518 * still has not exited. With the exception of the
519 * moment the task was created, new userspace threads
520 * can only be created by threads of the same task.
521 * We are safe to perform cleanup.
[da1bafb]522 *
[9a1b20c]523 */
[ea7890e7]524 ipc_cleanup();
[669f3d32]525 futex_task_cleanup();
[52755f1]526 LOG("Cleanup of task %" PRIu64" completed.", TASK->taskid);
[ea7890e7]527 }
528 }
[da1bafb]529
[f761f1eb]530restart:
[da1bafb]531 irq_spinlock_lock(&THREAD->lock, true);
532 if (THREAD->timeout_pending) {
533 /* Busy waiting for timeouts in progress */
534 irq_spinlock_unlock(&THREAD->lock, true);
[f761f1eb]535 goto restart;
536 }
[ea7890e7]537
[43114c5]538 THREAD->state = Exiting;
[da1bafb]539 irq_spinlock_unlock(&THREAD->lock, true);
540
[f761f1eb]541 scheduler();
[da1bafb]542
[874621f]543 /* Not reached */
[da1bafb]544 while (true);
[f761f1eb]545}
546
[518dd43]547/** Interrupts an existing thread so that it may exit as soon as possible.
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().
552 *
553 * The caller must guarantee the thread object is valid during the entire
554 * function, eg by holding the threads_lock lock.
555 *
556 * Interrupted threads automatically exit when returning back to user space.
557 *
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);
[518dd43]564
565 irq_spinlock_lock(&thread->lock, true);
566
567 thread->interrupted = true;
568 bool sleeping = (thread->state == Sleeping);
569
570 irq_spinlock_unlock(&thread->lock, true);
571
572 if (sleeping)
573 waitq_interrupt_sleep(thread);
574}
575
576/** Returns true if the thread was interrupted.
577 *
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);
[518dd43]585
586 bool interrupted;
587
588 irq_spinlock_lock(&thread->lock, true);
589 interrupted = thread->interrupted;
590 irq_spinlock_unlock(&thread->lock, true);
591
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);
[6eef3c4]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);
[6eef3c4]608
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{
[22e6802]622 /* Sleep in 1000 second steps to support
623 full argument range */
624 while (sec > 0) {
625 uint32_t period = (sec > 1000) ? 1000 : sec;
[da1bafb]626
[22e6802]627 thread_usleep(period * 1000000);
628 sec -= period;
629 }
[f761f1eb]630}
[70527f1]631
[fe19611]632/** Wait for another thread to exit.
633 *
[da1bafb]634 * @param thread Thread to join on exit.
635 * @param usec Timeout in microseconds.
636 * @param flags Mode of operation.
[fe19611]637 *
638 * @return An error code from errno.h or an error code from synch.h.
[da1bafb]639 *
[fe19611]640 */
[b7fd2a0]641errno_t thread_join_timeout(thread_t *thread, uint32_t usec, unsigned int flags)
[fe19611]642{
[da1bafb]643 if (thread == THREAD)
[fe19611]644 return EINVAL;
[da1bafb]645
[fe19611]646 /*
647 * Since thread join can only be called once on an undetached thread,
648 * the thread pointer is guaranteed to be still valid.
649 */
650
[da1bafb]651 irq_spinlock_lock(&thread->lock, true);
[63e27ef]652 assert(!thread->detached);
[da1bafb]653 irq_spinlock_unlock(&thread->lock, true);
[0182a665]654
[897fd8f1]655 return waitq_sleep_timeout(&thread->join_wq, usec, flags, NULL);
[fe19611]656}
657
658/** Detach thread.
659 *
[df58e44]660 * Mark the thread as detached. If the thread is already
661 * in the Lingering state, deallocate its resources.
[fe19611]662 *
[da1bafb]663 * @param thread Thread to be detached.
664 *
[fe19611]665 */
[da1bafb]666void thread_detach(thread_t *thread)
[fe19611]667{
668 /*
[31d8e10]669 * Since the thread is expected not to be already detached,
[fe19611]670 * pointer to it must be still valid.
671 */
[da1bafb]672 irq_spinlock_lock(&thread->lock, true);
[63e27ef]673 assert(!thread->detached);
[da1bafb]674
675 if (thread->state == Lingering) {
676 /*
677 * Unlock &thread->lock and restore
678 * interrupts in thread_destroy().
679 */
680 thread_destroy(thread, true);
[fe19611]681 return;
682 } else {
[da1bafb]683 thread->detached = true;
[fe19611]684 }
[da1bafb]685
686 irq_spinlock_unlock(&thread->lock, true);
[fe19611]687}
688
[70527f1]689/** Thread usleep
690 *
691 * Suspend execution of the current thread.
692 *
693 * @param usec Number of microseconds to sleep.
694 *
695 */
[7f1c620]696void thread_usleep(uint32_t usec)
[f761f1eb]697{
698 waitq_t wq;
[22e6802]699
[f761f1eb]700 waitq_initialize(&wq);
[22e6802]701
[897fd8f1]702 (void) waitq_sleep_timeout(&wq, usec, SYNCH_FLAGS_NON_BLOCKING, NULL);
[f761f1eb]703}
704
[b76a2217]705static bool thread_walker(avltree_node_t *node, void *arg)
[5dcee525]706{
[48dcc69]707 bool *additional = (bool *) arg;
[da1bafb]708 thread_t *thread = avltree_get_instance(node, thread_t, threads_tree_node);
[52755f1]709
[1ba37fa]710 uint64_t ucycles, kcycles;
711 char usuffix, ksuffix;
[da1bafb]712 order_suffix(thread->ucycles, &ucycles, &usuffix);
713 order_suffix(thread->kcycles, &kcycles, &ksuffix);
714
[577f042a]715 char *name;
716 if (str_cmp(thread->name, "uinit") == 0)
717 name = thread->task->name;
718 else
719 name = thread->name;
720
[52755f1]721#ifdef __32_BITS__
[48dcc69]722 if (*additional)
[ae0300b5]723 printf("%-8" PRIu64 " %10p %10p %9" PRIu64 "%c %9" PRIu64 "%c ",
[577f042a]724 thread->tid, thread->thread_code, thread->kstack,
725 ucycles, usuffix, kcycles, ksuffix);
[48dcc69]726 else
[ae0300b5]727 printf("%-8" PRIu64 " %-14s %10p %-8s %10p %-5" PRIu32 "\n",
[577f042a]728 thread->tid, name, thread, thread_states[thread->state],
[26aafe8]729 thread->task, thread->task->container);
[52755f1]730#endif
[da1bafb]731
[52755f1]732#ifdef __64_BITS__
[48dcc69]733 if (*additional)
[ae0300b5]734 printf("%-8" PRIu64 " %18p %18p\n"
[48dcc69]735 " %9" PRIu64 "%c %9" PRIu64 "%c ",
736 thread->tid, thread->thread_code, thread->kstack,
737 ucycles, usuffix, kcycles, ksuffix);
[5dcee525]738 else
[ae0300b5]739 printf("%-8" PRIu64 " %-14s %18p %-8s %18p %-5" PRIu32 "\n",
[577f042a]740 thread->tid, name, thread, thread_states[thread->state],
[26aafe8]741 thread->task, thread->task->container);
[48dcc69]742#endif
[da1bafb]743
[48dcc69]744 if (*additional) {
745 if (thread->cpu)
746 printf("%-5u", thread->cpu->id);
747 else
748 printf("none ");
749
750 if (thread->state == Sleeping) {
[52755f1]751#ifdef __32_BITS__
[48dcc69]752 printf(" %10p", thread->sleep_queue);
[52755f1]753#endif
[48dcc69]754
[52755f1]755#ifdef __64_BITS__
[48dcc69]756 printf(" %18p", thread->sleep_queue);
[52755f1]757#endif
[48dcc69]758 }
759
760 printf("\n");
[43b1e86]761 }
[da1bafb]762
[b76a2217]763 return true;
[5dcee525]764}
765
[da1bafb]766/** Print list of threads debug info
[48dcc69]767 *
768 * @param additional Print additional information.
[da1bafb]769 *
770 */
[48dcc69]771void thread_print_list(bool additional)
[55ab0f1]772{
773 /* Messing with thread structures, avoid deadlock */
[da1bafb]774 irq_spinlock_lock(&threads_lock, true);
775
776#ifdef __32_BITS__
[48dcc69]777 if (additional)
[577f042a]778 printf("[id ] [code ] [stack ] [ucycles ] [kcycles ]"
779 " [cpu] [waitqueue]\n");
[48dcc69]780 else
781 printf("[id ] [name ] [address ] [state ] [task ]"
[26aafe8]782 " [ctn]\n");
[52755f1]783#endif
[da1bafb]784
[52755f1]785#ifdef __64_BITS__
[48dcc69]786 if (additional) {
787 printf("[id ] [code ] [stack ]\n"
788 " [ucycles ] [kcycles ] [cpu] [waitqueue ]\n");
789 } else
790 printf("[id ] [name ] [address ] [state ]"
[26aafe8]791 " [task ] [ctn]\n");
[52755f1]792#endif
[da1bafb]793
[48dcc69]794 avltree_walk(&threads_tree, thread_walker, &additional);
[da1bafb]795
796 irq_spinlock_unlock(&threads_lock, true);
[55ab0f1]797}
[9f52563]798
[016acbe]799/** Check whether thread exists.
800 *
801 * Note that threads_lock must be already held and
802 * interrupts must be already disabled.
803 *
[da1bafb]804 * @param thread Pointer to thread.
[016acbe]805 *
806 * @return True if thread t is known to the system, false otherwise.
[da1bafb]807 *
[016acbe]808 */
[da1bafb]809bool thread_exists(thread_t *thread)
[016acbe]810{
[63e27ef]811 assert(interrupts_disabled());
812 assert(irq_spinlock_locked(&threads_lock));
[1d432f9]813
[da1bafb]814 avltree_node_t *node =
815 avltree_search(&threads_tree, (avltree_key_t) ((uintptr_t) thread));
[016acbe]816
[5dcee525]817 return node != NULL;
[016acbe]818}
819
[cce6acf]820/** Update accounting of current thread.
821 *
822 * Note that thread_lock on THREAD must be already held and
823 * interrupts must be already disabled.
824 *
[da1bafb]825 * @param user True to update user accounting, false for kernel.
826 *
[cce6acf]827 */
[a2a00e8]828void thread_update_accounting(bool user)
[cce6acf]829{
830 uint64_t time = get_cycle();
[1d432f9]831
[63e27ef]832 assert(interrupts_disabled());
833 assert(irq_spinlock_locked(&THREAD->lock));
[da1bafb]834
835 if (user)
[a2a00e8]836 THREAD->ucycles += time - THREAD->last_cycle;
[da1bafb]837 else
[a2a00e8]838 THREAD->kcycles += time - THREAD->last_cycle;
[da1bafb]839
[cce6acf]840 THREAD->last_cycle = time;
841}
842
[e1b6742]843static bool thread_search_walker(avltree_node_t *node, void *arg)
844{
845 thread_t *thread =
846 (thread_t *) avltree_get_instance(node, thread_t, threads_tree_node);
847 thread_iterator_t *iterator = (thread_iterator_t *) arg;
848
849 if (thread->tid == iterator->thread_id) {
850 iterator->thread = thread;
851 return false;
852 }
853
854 return true;
855}
856
857/** Find thread structure corresponding to thread ID.
858 *
859 * The threads_lock must be already held by the caller of this function and
860 * interrupts must be disabled.
861 *
862 * @param id Thread ID.
863 *
864 * @return Thread structure address or NULL if there is no such thread ID.
865 *
866 */
867thread_t *thread_find_by_id(thread_id_t thread_id)
868{
[63e27ef]869 assert(interrupts_disabled());
870 assert(irq_spinlock_locked(&threads_lock));
[df58e44]871
[e1b6742]872 thread_iterator_t iterator;
873
874 iterator.thread_id = thread_id;
875 iterator.thread = NULL;
876
877 avltree_walk(&threads_tree, thread_search_walker, (void *) &iterator);
878
879 return iterator.thread;
880}
881
[5b7a107]882#ifdef CONFIG_UDEBUG
883
[df58e44]884void thread_stack_trace(thread_id_t thread_id)
885{
886 irq_spinlock_lock(&threads_lock, true);
887
888 thread_t *thread = thread_find_by_id(thread_id);
889 if (thread == NULL) {
890 printf("No such thread.\n");
891 irq_spinlock_unlock(&threads_lock, true);
892 return;
893 }
894
895 irq_spinlock_lock(&thread->lock, false);
896
897 /*
898 * Schedule a stack trace to be printed
899 * just before the thread is scheduled next.
900 *
901 * If the thread is sleeping then try to interrupt
902 * the sleep. Any request for printing an uspace stack
903 * trace from within the kernel should be always
904 * considered a last resort debugging means, therefore
905 * forcing the thread's sleep to be interrupted
906 * is probably justifiable.
907 */
908
909 bool sleeping = false;
910 istate_t *istate = thread->udebug.uspace_state;
911 if (istate != NULL) {
912 printf("Scheduling thread stack trace.\n");
913 thread->btrace = true;
914 if (thread->state == Sleeping)
915 sleeping = true;
916 } else
917 printf("Thread interrupt state not available.\n");
918
919 irq_spinlock_unlock(&thread->lock, false);
920
921 if (sleeping)
922 waitq_interrupt_sleep(thread);
923
924 irq_spinlock_unlock(&threads_lock, true);
925}
[e1b6742]926
[5b7a107]927#endif /* CONFIG_UDEBUG */
[e1b6742]928
[9f52563]929/** Process syscall to create new thread.
930 *
931 */
[b7fd2a0]932sys_errno_t sys_thread_create(uspace_arg_t *uspace_uarg, char *uspace_name,
[7faabb7]933 size_t name_len, thread_id_t *uspace_thread_id)
[9f52563]934{
[24345a5]935 if (name_len > THREAD_NAME_BUFLEN - 1)
[7faabb7]936 name_len = THREAD_NAME_BUFLEN - 1;
[da1bafb]937
938 char namebuf[THREAD_NAME_BUFLEN];
[b7fd2a0]939 errno_t rc = copy_from_uspace(namebuf, uspace_name, name_len);
[a53ed3a]940 if (rc != EOK)
[b7fd2a0]941 return (sys_errno_t) rc;
[da1bafb]942
[b60c582]943 namebuf[name_len] = 0;
[da1bafb]944
[4680ef5]945 /*
946 * In case of failure, kernel_uarg will be deallocated in this function.
947 * In case of success, kernel_uarg will be freed in uinit().
948 */
[da1bafb]949 uspace_arg_t *kernel_uarg =
950 (uspace_arg_t *) malloc(sizeof(uspace_arg_t), 0);
[4680ef5]951
[e3c762cd]952 rc = copy_from_uspace(kernel_uarg, uspace_uarg, sizeof(uspace_arg_t));
[a53ed3a]953 if (rc != EOK) {
[e3c762cd]954 free(kernel_uarg);
[b7fd2a0]955 return (sys_errno_t) rc;
[e3c762cd]956 }
[da1bafb]957
958 thread_t *thread = thread_create(uinit, kernel_uarg, TASK,
[6eef3c4]959 THREAD_FLAG_USPACE | THREAD_FLAG_NOATTACH, namebuf);
[da1bafb]960 if (thread) {
[d8431986]961 if (uspace_thread_id != NULL) {
[da1bafb]962 rc = copy_to_uspace(uspace_thread_id, &thread->tid,
963 sizeof(thread->tid));
[a53ed3a]964 if (rc != EOK) {
[d8431986]965 /*
966 * We have encountered a failure, but the thread
967 * has already been created. We need to undo its
968 * creation now.
969 */
[da1bafb]970
[d8431986]971 /*
[ea7890e7]972 * The new thread structure is initialized, but
973 * is still not visible to the system.
[d8431986]974 * We can safely deallocate it.
975 */
[82d515e9]976 slab_free(thread_cache, thread);
[da1bafb]977 free(kernel_uarg);
978
[b7fd2a0]979 return (sys_errno_t) rc;
[d8431986]980 }
981 }
[da1bafb]982
[9a1b20c]983#ifdef CONFIG_UDEBUG
[13964ef]984 /*
985 * Generate udebug THREAD_B event and attach the thread.
986 * This must be done atomically (with the debug locks held),
987 * otherwise we would either miss some thread or receive
988 * THREAD_B events for threads that already existed
989 * and could be detected with THREAD_READ before.
990 */
[da1bafb]991 udebug_thread_b_event_attach(thread, TASK);
[13964ef]992#else
[da1bafb]993 thread_attach(thread, TASK);
[9a1b20c]994#endif
[da1bafb]995 thread_ready(thread);
996
[d8431986]997 return 0;
[201abde]998 } else
[0f250f9]999 free(kernel_uarg);
[da1bafb]1000
[b7fd2a0]1001 return (sys_errno_t) ENOMEM;
[9f52563]1002}
1003
1004/** Process syscall to terminate thread.
1005 *
1006 */
[b7fd2a0]1007sys_errno_t sys_thread_exit(int uspace_status)
[9f52563]1008{
[68091bd]1009 thread_exit();
[9f52563]1010}
[b45c443]1011
[3ce7f082]1012/** Syscall for getting TID.
1013 *
[201abde]1014 * @param uspace_thread_id Userspace address of 8-byte buffer where to store
1015 * current thread ID.
1016 *
1017 * @return 0 on success or an error code from @ref errno.h.
[da1bafb]1018 *
[b45c443]1019 */
[b7fd2a0]1020sys_errno_t sys_thread_get_id(thread_id_t *uspace_thread_id)
[3ce7f082]1021{
1022 /*
1023 * No need to acquire lock on THREAD because tid
1024 * remains constant for the lifespan of the thread.
[da1bafb]1025 *
[3ce7f082]1026 */
[b7fd2a0]1027 return (sys_errno_t) copy_to_uspace(uspace_thread_id, &THREAD->tid,
[201abde]1028 sizeof(THREAD->tid));
[3ce7f082]1029}
[6f4495f5]1030
[d9ece1cb]1031/** Syscall wrapper for sleeping. */
[b7fd2a0]1032sys_errno_t sys_thread_usleep(uint32_t usec)
[d9ece1cb]1033{
[22e6802]1034 thread_usleep(usec);
[d9ece1cb]1035 return 0;
1036}
1037
[b7fd2a0]1038sys_errno_t sys_thread_udelay(uint32_t usec)
[7e7b791]1039{
[8d6c1f1]1040 delay(usec);
[7e7b791]1041 return 0;
1042}
1043
[3ce7f082]1044/** @}
1045 */
Note: See TracBrowser for help on using the repository browser.