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

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since 207e8880 was 669f3d32, checked in by Adam Hraska <adam.hraska+hos@…>, 13 years ago

Adapted the kernel futex subsystem to use CHT.

  • Property mode set to 100644
File size: 25.4 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
[f761f1eb]38#include <proc/scheduler.h>
39#include <proc/thread.h>
40#include <proc/task.h>
41#include <mm/frame.h>
42#include <mm/page.h>
43#include <arch/asm.h>
[cce6acf]44#include <arch/cycle.h>
[f761f1eb]45#include <arch.h>
46#include <synch/spinlock.h>
47#include <synch/waitq.h>
[8a64e81e]48#include <synch/workqueue.h>
[181a746]49#include <synch/rcu.h>
[f761f1eb]50#include <cpu.h>
[e535eeb]51#include <str.h>
[f761f1eb]52#include <context.h>
[5dcee525]53#include <adt/avl.h>
[5c9a08b]54#include <adt/list.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>
[9c0a9b3]63#include <memstr.h>
[55ab0f1]64#include <print.h>
[266294a9]65#include <mm/slab.h>
66#include <debug.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
[266294a9]105static slab_cache_t *thread_slab;
[da1bafb]106
[0f81ceb7]107#ifdef CONFIG_FPU
[f76fed4]108slab_cache_t *fpu_context_slab;
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 */
155static int 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 */
171 thread->saved_fpu_context = slab_alloc(fpu_context_slab, kmflags);
172 if (!thread->saved_fpu_context)
[f76fed4]173 return -1;
[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
[da1bafb]196 thread->kstack = (uint8_t *) frame_alloc(STACK_FRAMES, FRAME_KA | kmflags);
197 if (!thread->kstack) {
[0f81ceb7]198#ifdef CONFIG_FPU
[da1bafb]199 if (thread->saved_fpu_context)
200 slab_free(fpu_context_slab, thread->saved_fpu_context);
[f76fed4]201#endif
[266294a9]202 return -1;
[f76fed4]203 }
[da1bafb]204
[9a1b20c]205#ifdef CONFIG_UDEBUG
[da1bafb]206 mutex_initialize(&thread->udebug.lock, MUTEX_PASSIVE);
[9a1b20c]207#endif
[da1bafb]208
[266294a9]209 return 0;
210}
211
212/** Destruction of thread_t object */
[da1bafb]213static size_t thr_destructor(void *obj)
[266294a9]214{
[da1bafb]215 thread_t *thread = (thread_t *) obj;
216
[32fffef0]217 /* call the architecture-specific part of the destructor */
[da1bafb]218 thr_destructor_arch(thread);
219
220 frame_free(KA2PA(thread->kstack));
221
[0f81ceb7]222#ifdef CONFIG_FPU
[da1bafb]223 if (thread->saved_fpu_context)
224 slab_free(fpu_context_slab, thread->saved_fpu_context);
[f76fed4]225#endif
[da1bafb]226
227 return 1; /* One page freed */
[266294a9]228}
[70527f1]229
230/** Initialize threads
231 *
232 * Initialize kernel threads support.
233 *
234 */
[f761f1eb]235void thread_init(void)
236{
[43114c5]237 THREAD = NULL;
[da1bafb]238
[7217199]239 atomic_set(&nrdy, 0);
[f97f1e51]240 thread_slab = slab_cache_create("thread_t", sizeof(thread_t), 0,
[6f4495f5]241 thr_constructor, thr_destructor, 0);
[da1bafb]242
[0f81ceb7]243#ifdef CONFIG_FPU
[f97f1e51]244 fpu_context_slab = slab_cache_create("fpu_context_t",
245 sizeof(fpu_context_t), FPU_CONTEXT_ALIGN, NULL, NULL, 0);
[f76fed4]246#endif
[da1bafb]247
[5dcee525]248 avltree_create(&threads_tree);
[016acbe]249}
[70527f1]250
[6eef3c4]251/** Wire thread to the given CPU
252 *
253 * @param cpu CPU to wire the thread to.
254 *
255 */
256void thread_wire(thread_t *thread, cpu_t *cpu)
257{
258 irq_spinlock_lock(&thread->lock, true);
259 thread->cpu = cpu;
260 thread->wired = true;
261 irq_spinlock_unlock(&thread->lock, true);
262}
263
[8a64e81e]264/** Invoked right before thread_ready() readies the thread. thread is locked. */
265static void before_thread_is_ready(thread_t *thread)
266{
267 ASSERT(irq_spinlock_locked(&thread->lock));
268 workq_before_thread_is_ready(thread);
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);
[f761f1eb]281
[df58e44]282 ASSERT(thread->state != Ready);
[518dd43]283
[8a64e81e]284 before_thread_is_ready(thread);
285
[6eef3c4]286 int i = (thread->priority < RQ_COUNT - 1) ?
287 ++thread->priority : thread->priority;
[518dd43]288
289 /* Check that thread->cpu is set whenever it needs to be. */
290 ASSERT(thread->cpu != NULL ||
291 (!thread->wired && !thread->nomigrate && !thread->fpu_context_engaged));
292
293 /*
294 * Prefer to run on the same cpu as the last time. Used by wired
295 * threads as well as threads with disabled migration.
296 */
297 cpu_t *cpu = thread->cpu;
298 if (cpu == NULL)
[6eef3c4]299 cpu = CPU;
300
[da1bafb]301 thread->state = Ready;
302
303 irq_spinlock_pass(&thread->lock, &(cpu->rq[i].lock));
[f761f1eb]304
[70527f1]305 /*
[da1bafb]306 * Append thread to respective ready queue
307 * on respective processor.
[f761f1eb]308 */
[da1bafb]309
[55b77d9]310 list_append(&thread->rq_link, &cpu->rq[i].rq);
[da1bafb]311 cpu->rq[i].n++;
312 irq_spinlock_unlock(&(cpu->rq[i].lock), true);
313
[59e07c91]314 atomic_inc(&nrdy);
[da1bafb]315 // FIXME: Why is the avg value not used
316 // avg = atomic_get(&nrdy) / config.cpu_active;
[248fc1a]317 atomic_inc(&cpu->nrdy);
[f761f1eb]318}
319
[70527f1]320/** Create new thread
321 *
322 * Create a new thread.
323 *
[da1bafb]324 * @param func Thread's implementing function.
325 * @param arg Thread's implementing function argument.
326 * @param task Task to which the thread belongs. The caller must
327 * guarantee that the task won't cease to exist during the
328 * call. The task's lock may not be held.
329 * @param flags Thread flags.
330 * @param name Symbolic name (a copy is made).
[70527f1]331 *
[da1bafb]332 * @return New thread's structure on success, NULL on failure.
[70527f1]333 *
334 */
[4e33b6b]335thread_t *thread_create(void (* func)(void *), void *arg, task_t *task,
[6eef3c4]336 thread_flags_t flags, const char *name)
[f761f1eb]337{
[da1bafb]338 thread_t *thread = (thread_t *) slab_alloc(thread_slab, 0);
339 if (!thread)
[2a46e10]340 return NULL;
[aa8d0f7]341
[bb68433]342 /* Not needed, but good for debugging */
[26aafe8]343 memsetb(thread->kstack, STACK_SIZE, 0);
[bb68433]344
[da1bafb]345 irq_spinlock_lock(&tidlock, true);
346 thread->tid = ++last_tid;
347 irq_spinlock_unlock(&tidlock, true);
[bb68433]348
[da1bafb]349 context_save(&thread->saved_context);
350 context_set(&thread->saved_context, FADDR(cushion),
[26aafe8]351 (uintptr_t) thread->kstack, STACK_SIZE);
[bb68433]352
[da1bafb]353 the_initialize((the_t *) thread->kstack);
[bb68433]354
[da1bafb]355 ipl_t ipl = interrupts_disable();
356 thread->saved_context.ipl = interrupts_read();
[bb68433]357 interrupts_restore(ipl);
358
[da1bafb]359 str_cpy(thread->name, THREAD_NAME_BUFLEN, name);
360
361 thread->thread_code = func;
362 thread->thread_arg = arg;
363 thread->ticks = -1;
364 thread->ucycles = 0;
365 thread->kcycles = 0;
[6eef3c4]366 thread->uncounted =
367 ((flags & THREAD_FLAG_UNCOUNTED) == THREAD_FLAG_UNCOUNTED);
[da1bafb]368 thread->priority = -1; /* Start in rq[0] */
369 thread->cpu = NULL;
[6eef3c4]370 thread->wired = false;
371 thread->stolen = false;
372 thread->uspace =
373 ((flags & THREAD_FLAG_USPACE) == THREAD_FLAG_USPACE);
374
[43ac0cc]375 thread->nomigrate = 0;
[da1bafb]376 thread->state = Entering;
377
378 timeout_initialize(&thread->sleep_timeout);
379 thread->sleep_interruptible = false;
380 thread->sleep_queue = NULL;
381 thread->timeout_pending = false;
382
383 thread->in_copy_from_uspace = false;
384 thread->in_copy_to_uspace = false;
385
386 thread->interrupted = false;
387 thread->detached = false;
388 waitq_initialize(&thread->join_wq);
389
390 thread->task = task;
391
[8a64e81e]392 thread->workq = NULL;
393
[6eef3c4]394 thread->fpu_context_exists = false;
395 thread->fpu_context_engaged = false;
[da1bafb]396
397 avltree_node_initialize(&thread->threads_tree_node);
398 thread->threads_tree_node.key = (uintptr_t) thread;
[bb68433]399
[9a1b20c]400#ifdef CONFIG_UDEBUG
[5b7a107]401 /* Initialize debugging stuff */
402 thread->btrace = false;
[da1bafb]403 udebug_thread_initialize(&thread->udebug);
[9a1b20c]404#endif
[da1bafb]405
406 /* Might depend on previous initialization */
407 thread_create_arch(thread);
408
[181a746]409 rcu_thread_init(thread);
410
[6eef3c4]411 if ((flags & THREAD_FLAG_NOATTACH) != THREAD_FLAG_NOATTACH)
[da1bafb]412 thread_attach(thread, task);
413
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{
[2d3ddad]428 ASSERT(irq_spinlock_locked(&thread->lock));
[da1bafb]429 ASSERT((thread->state == Exiting) || (thread->state == Lingering));
430 ASSERT(thread->task);
431 ASSERT(thread->cpu);
432
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);
437
438 irq_spinlock_pass(&thread->lock, &threads_lock);
439
440 avltree_delete(&threads_tree, &thread->threads_tree_node);
441
442 irq_spinlock_pass(&threads_lock, &thread->task->lock);
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);
449
[ea7890e7]450 /*
[7ed8530]451 * Drop the reference to the containing task.
[ea7890e7]452 */
[da1bafb]453 task_release(thread->task);
454 slab_free(thread_slab, 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);
472
[7ed8530]473 /* Hold a reference to the task. */
474 task_hold(task);
[da1bafb]475
[9a1b20c]476 /* Must not count kbox thread into lifecount */
[6eef3c4]477 if (thread->uspace)
[9a1b20c]478 atomic_inc(&task->lifecount);
[da1bafb]479
[55b77d9]480 list_append(&thread->th_link, &task->threads);
[da1bafb]481
482 irq_spinlock_pass(&task->lock, &threads_lock);
483
[bb68433]484 /*
485 * Register this thread in the system-wide list.
486 */
[da1bafb]487 avltree_insert(&threads_tree, &thread->threads_tree_node);
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();
[6eef3c4]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();
[52755f1]521 LOG("Cleanup of task %" PRIu64" completed.", TASK->taskid);
[ea7890e7]522 }
523 }
[da1bafb]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 }
[ea7890e7]532
[43114c5]533 THREAD->state = Exiting;
[da1bafb]534 irq_spinlock_unlock(&THREAD->lock, true);
535
[f761f1eb]536 scheduler();
[da1bafb]537
[874621f]538 /* Not reached */
[da1bafb]539 while (true);
[f761f1eb]540}
541
[518dd43]542/** Interrupts an existing thread so that it may exit as soon as possible.
543 *
544 * Threads that are blocked waiting for a synchronization primitive
545 * are woken up with a return code of ESYNCH_INTERRUPTED if the
546 * blocking call was interruptable. See waitq_sleep_timeout().
547 *
548 * The caller must guarantee the thread object is valid during the entire
549 * function, eg by holding the threads_lock lock.
550 *
551 * Interrupted threads automatically exit when returning back to user space.
552 *
553 * @param thread A valid thread object. The caller must guarantee it
554 * will remain valid until thread_interrupt() exits.
555 */
556void thread_interrupt(thread_t *thread)
557{
558 ASSERT(thread != NULL);
559
560 irq_spinlock_lock(&thread->lock, true);
561
562 thread->interrupted = true;
563 bool sleeping = (thread->state == Sleeping);
564
565 irq_spinlock_unlock(&thread->lock, true);
566
567 if (sleeping)
568 waitq_interrupt_sleep(thread);
569}
570
571/** Returns true if the thread was interrupted.
572 *
573 * @param thread A valid thread object. User must guarantee it will
574 * be alive during the entire call.
575 * @return true if the thread was already interrupted via thread_interrupt().
576 */
577bool thread_interrupted(thread_t *thread)
578{
579 ASSERT(thread != NULL);
580
581 bool interrupted;
582
583 irq_spinlock_lock(&thread->lock, true);
584 interrupted = thread->interrupted;
585 irq_spinlock_unlock(&thread->lock, true);
586
587 return interrupted;
588}
589
[43ac0cc]590/** Prevent the current thread from being migrated to another processor. */
591void thread_migration_disable(void)
592{
593 ASSERT(THREAD);
[6eef3c4]594
[43ac0cc]595 THREAD->nomigrate++;
596}
597
598/** Allow the current thread to be migrated to another processor. */
599void thread_migration_enable(void)
600{
601 ASSERT(THREAD);
602 ASSERT(THREAD->nomigrate > 0);
[6eef3c4]603
604 if (THREAD->nomigrate > 0)
605 THREAD->nomigrate--;
[43ac0cc]606}
607
[70527f1]608/** Thread sleep
609 *
610 * Suspend execution of the current thread.
611 *
612 * @param sec Number of seconds to sleep.
613 *
614 */
[7f1c620]615void thread_sleep(uint32_t sec)
[f761f1eb]616{
[22e6802]617 /* Sleep in 1000 second steps to support
618 full argument range */
619 while (sec > 0) {
620 uint32_t period = (sec > 1000) ? 1000 : sec;
[da1bafb]621
[22e6802]622 thread_usleep(period * 1000000);
623 sec -= period;
624 }
[f761f1eb]625}
[70527f1]626
[fe19611]627/** Wait for another thread to exit.
628 *
[da1bafb]629 * @param thread Thread to join on exit.
630 * @param usec Timeout in microseconds.
631 * @param flags Mode of operation.
[fe19611]632 *
633 * @return An error code from errno.h or an error code from synch.h.
[da1bafb]634 *
[fe19611]635 */
[da1bafb]636int thread_join_timeout(thread_t *thread, uint32_t usec, unsigned int flags)
[fe19611]637{
[da1bafb]638 if (thread == THREAD)
[fe19611]639 return EINVAL;
[da1bafb]640
[fe19611]641 /*
642 * Since thread join can only be called once on an undetached thread,
643 * the thread pointer is guaranteed to be still valid.
644 */
645
[da1bafb]646 irq_spinlock_lock(&thread->lock, true);
647 ASSERT(!thread->detached);
648 irq_spinlock_unlock(&thread->lock, true);
[0182a665]649
[da1bafb]650 return waitq_sleep_timeout(&thread->join_wq, usec, flags);
[fe19611]651}
652
653/** Detach thread.
654 *
[df58e44]655 * Mark the thread as detached. If the thread is already
656 * in the Lingering state, deallocate its resources.
[fe19611]657 *
[da1bafb]658 * @param thread Thread to be detached.
659 *
[fe19611]660 */
[da1bafb]661void thread_detach(thread_t *thread)
[fe19611]662{
663 /*
[31d8e10]664 * Since the thread is expected not to be already detached,
[fe19611]665 * pointer to it must be still valid.
666 */
[da1bafb]667 irq_spinlock_lock(&thread->lock, true);
668 ASSERT(!thread->detached);
669
670 if (thread->state == Lingering) {
671 /*
672 * Unlock &thread->lock and restore
673 * interrupts in thread_destroy().
674 */
675 thread_destroy(thread, true);
[fe19611]676 return;
677 } else {
[da1bafb]678 thread->detached = true;
[fe19611]679 }
[da1bafb]680
681 irq_spinlock_unlock(&thread->lock, true);
[fe19611]682}
683
[70527f1]684/** Thread usleep
685 *
686 * Suspend execution of the current thread.
687 *
688 * @param usec Number of microseconds to sleep.
689 *
690 */
[7f1c620]691void thread_usleep(uint32_t usec)
[f761f1eb]692{
693 waitq_t wq;
[22e6802]694
[f761f1eb]695 waitq_initialize(&wq);
[22e6802]696
[116d1ef4]697 (void) waitq_sleep_timeout(&wq, usec, SYNCH_FLAGS_NON_BLOCKING);
[f761f1eb]698}
699
[b76a2217]700static bool thread_walker(avltree_node_t *node, void *arg)
[5dcee525]701{
[48dcc69]702 bool *additional = (bool *) arg;
[da1bafb]703 thread_t *thread = avltree_get_instance(node, thread_t, threads_tree_node);
[52755f1]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);
709
[577f042a]710 char *name;
711 if (str_cmp(thread->name, "uinit") == 0)
712 name = thread->task->name;
713 else
714 name = thread->name;
715
[52755f1]716#ifdef __32_BITS__
[48dcc69]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
[da1bafb]726
[52755f1]727#ifdef __64_BITS__
[48dcc69]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
[da1bafb]738
[48dcc69]739 if (*additional) {
740 if (thread->cpu)
741 printf("%-5u", thread->cpu->id);
742 else
743 printf("none ");
744
745 if (thread->state == Sleeping) {
[52755f1]746#ifdef __32_BITS__
[48dcc69]747 printf(" %10p", thread->sleep_queue);
[52755f1]748#endif
[48dcc69]749
[52755f1]750#ifdef __64_BITS__
[48dcc69]751 printf(" %18p", thread->sleep_queue);
[52755f1]752#endif
[48dcc69]753 }
754
755 printf("\n");
[43b1e86]756 }
[da1bafb]757
[b76a2217]758 return true;
[5dcee525]759}
760
[da1bafb]761/** Print list of threads debug info
[48dcc69]762 *
763 * @param additional Print additional information.
[da1bafb]764 *
765 */
[48dcc69]766void thread_print_list(bool additional)
[55ab0f1]767{
768 /* Messing with thread structures, avoid deadlock */
[da1bafb]769 irq_spinlock_lock(&threads_lock, true);
770
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
[da1bafb]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
[da1bafb]788
[48dcc69]789 avltree_walk(&threads_tree, thread_walker, &additional);
[da1bafb]790
791 irq_spinlock_unlock(&threads_lock, true);
[55ab0f1]792}
[9f52563]793
[016acbe]794/** Check whether thread exists.
795 *
796 * Note that threads_lock must be already held and
797 * interrupts must be already disabled.
798 *
[da1bafb]799 * @param thread Pointer to thread.
[016acbe]800 *
801 * @return True if thread t is known to the system, false otherwise.
[da1bafb]802 *
[016acbe]803 */
[da1bafb]804bool thread_exists(thread_t *thread)
[016acbe]805{
[1d432f9]806 ASSERT(interrupts_disabled());
807 ASSERT(irq_spinlock_locked(&threads_lock));
808
[da1bafb]809 avltree_node_t *node =
810 avltree_search(&threads_tree, (avltree_key_t) ((uintptr_t) thread));
[016acbe]811
[5dcee525]812 return node != NULL;
[016acbe]813}
814
[cce6acf]815/** Update accounting of current thread.
816 *
817 * Note that thread_lock on THREAD must be already held and
818 * interrupts must be already disabled.
819 *
[da1bafb]820 * @param user True to update user accounting, false for kernel.
821 *
[cce6acf]822 */
[a2a00e8]823void thread_update_accounting(bool user)
[cce6acf]824{
825 uint64_t time = get_cycle();
[1d432f9]826
827 ASSERT(interrupts_disabled());
828 ASSERT(irq_spinlock_locked(&THREAD->lock));
[da1bafb]829
830 if (user)
[a2a00e8]831 THREAD->ucycles += time - THREAD->last_cycle;
[da1bafb]832 else
[a2a00e8]833 THREAD->kcycles += time - THREAD->last_cycle;
[da1bafb]834
[cce6acf]835 THREAD->last_cycle = time;
836}
837
[e1b6742]838static bool thread_search_walker(avltree_node_t *node, void *arg)
839{
840 thread_t *thread =
841 (thread_t *) avltree_get_instance(node, thread_t, threads_tree_node);
842 thread_iterator_t *iterator = (thread_iterator_t *) arg;
843
844 if (thread->tid == iterator->thread_id) {
845 iterator->thread = thread;
846 return false;
847 }
848
849 return true;
850}
851
852/** Find thread structure corresponding to thread ID.
853 *
854 * The threads_lock must be already held by the caller of this function and
855 * interrupts must be disabled.
856 *
857 * @param id Thread ID.
858 *
859 * @return Thread structure address or NULL if there is no such thread ID.
860 *
861 */
862thread_t *thread_find_by_id(thread_id_t thread_id)
863{
[1d432f9]864 ASSERT(interrupts_disabled());
865 ASSERT(irq_spinlock_locked(&threads_lock));
[df58e44]866
[e1b6742]867 thread_iterator_t iterator;
868
869 iterator.thread_id = thread_id;
870 iterator.thread = NULL;
871
872 avltree_walk(&threads_tree, thread_search_walker, (void *) &iterator);
873
874 return iterator.thread;
875}
876
[5b7a107]877#ifdef CONFIG_UDEBUG
878
[df58e44]879void thread_stack_trace(thread_id_t thread_id)
880{
881 irq_spinlock_lock(&threads_lock, true);
882
883 thread_t *thread = thread_find_by_id(thread_id);
884 if (thread == NULL) {
885 printf("No such thread.\n");
886 irq_spinlock_unlock(&threads_lock, true);
887 return;
888 }
889
890 irq_spinlock_lock(&thread->lock, false);
891
892 /*
893 * Schedule a stack trace to be printed
894 * just before the thread is scheduled next.
895 *
896 * If the thread is sleeping then try to interrupt
897 * the sleep. Any request for printing an uspace stack
898 * trace from within the kernel should be always
899 * considered a last resort debugging means, therefore
900 * forcing the thread's sleep to be interrupted
901 * is probably justifiable.
902 */
903
904 bool sleeping = false;
905 istate_t *istate = thread->udebug.uspace_state;
906 if (istate != NULL) {
907 printf("Scheduling thread stack trace.\n");
908 thread->btrace = true;
909 if (thread->state == Sleeping)
910 sleeping = true;
911 } else
912 printf("Thread interrupt state not available.\n");
913
914 irq_spinlock_unlock(&thread->lock, false);
915
916 if (sleeping)
917 waitq_interrupt_sleep(thread);
918
919 irq_spinlock_unlock(&threads_lock, true);
920}
[e1b6742]921
[5b7a107]922#endif /* CONFIG_UDEBUG */
[e1b6742]923
[9f52563]924/** Process syscall to create new thread.
925 *
926 */
[96b02eb9]927sysarg_t sys_thread_create(uspace_arg_t *uspace_uarg, char *uspace_name,
[7faabb7]928 size_t name_len, thread_id_t *uspace_thread_id)
[9f52563]929{
[24345a5]930 if (name_len > THREAD_NAME_BUFLEN - 1)
[7faabb7]931 name_len = THREAD_NAME_BUFLEN - 1;
[da1bafb]932
933 char namebuf[THREAD_NAME_BUFLEN];
934 int rc = copy_from_uspace(namebuf, uspace_name, name_len);
[e3c762cd]935 if (rc != 0)
[96b02eb9]936 return (sysarg_t) rc;
[da1bafb]937
[b60c582]938 namebuf[name_len] = 0;
[da1bafb]939
[4680ef5]940 /*
941 * In case of failure, kernel_uarg will be deallocated in this function.
942 * In case of success, kernel_uarg will be freed in uinit().
943 */
[da1bafb]944 uspace_arg_t *kernel_uarg =
945 (uspace_arg_t *) malloc(sizeof(uspace_arg_t), 0);
[4680ef5]946
[e3c762cd]947 rc = copy_from_uspace(kernel_uarg, uspace_uarg, sizeof(uspace_arg_t));
948 if (rc != 0) {
949 free(kernel_uarg);
[96b02eb9]950 return (sysarg_t) rc;
[e3c762cd]951 }
[da1bafb]952
953 thread_t *thread = thread_create(uinit, kernel_uarg, TASK,
[6eef3c4]954 THREAD_FLAG_USPACE | THREAD_FLAG_NOATTACH, namebuf);
[da1bafb]955 if (thread) {
[d8431986]956 if (uspace_thread_id != NULL) {
[da1bafb]957 rc = copy_to_uspace(uspace_thread_id, &thread->tid,
958 sizeof(thread->tid));
[d8431986]959 if (rc != 0) {
960 /*
961 * We have encountered a failure, but the thread
962 * has already been created. We need to undo its
963 * creation now.
964 */
[da1bafb]965
[d8431986]966 /*
[ea7890e7]967 * The new thread structure is initialized, but
968 * is still not visible to the system.
[d8431986]969 * We can safely deallocate it.
970 */
[da1bafb]971 slab_free(thread_slab, thread);
972 free(kernel_uarg);
973
[96b02eb9]974 return (sysarg_t) rc;
[d8431986]975 }
976 }
[da1bafb]977
[9a1b20c]978#ifdef CONFIG_UDEBUG
[13964ef]979 /*
980 * Generate udebug THREAD_B event and attach the thread.
981 * This must be done atomically (with the debug locks held),
982 * otherwise we would either miss some thread or receive
983 * THREAD_B events for threads that already existed
984 * and could be detected with THREAD_READ before.
985 */
[da1bafb]986 udebug_thread_b_event_attach(thread, TASK);
[13964ef]987#else
[da1bafb]988 thread_attach(thread, TASK);
[9a1b20c]989#endif
[da1bafb]990 thread_ready(thread);
991
[d8431986]992 return 0;
[201abde]993 } else
[0f250f9]994 free(kernel_uarg);
[da1bafb]995
[96b02eb9]996 return (sysarg_t) ENOMEM;
[9f52563]997}
998
999/** Process syscall to terminate thread.
1000 *
1001 */
[96b02eb9]1002sysarg_t sys_thread_exit(int uspace_status)
[9f52563]1003{
[68091bd]1004 thread_exit();
[da1bafb]1005
[68091bd]1006 /* Unreachable */
1007 return 0;
[9f52563]1008}
[b45c443]1009
[3ce7f082]1010/** Syscall for getting TID.
1011 *
[201abde]1012 * @param uspace_thread_id Userspace address of 8-byte buffer where to store
1013 * current thread ID.
1014 *
1015 * @return 0 on success or an error code from @ref errno.h.
[da1bafb]1016 *
[b45c443]1017 */
[96b02eb9]1018sysarg_t sys_thread_get_id(thread_id_t *uspace_thread_id)
[3ce7f082]1019{
1020 /*
1021 * No need to acquire lock on THREAD because tid
1022 * remains constant for the lifespan of the thread.
[da1bafb]1023 *
[3ce7f082]1024 */
[96b02eb9]1025 return (sysarg_t) copy_to_uspace(uspace_thread_id, &THREAD->tid,
[201abde]1026 sizeof(THREAD->tid));
[3ce7f082]1027}
[6f4495f5]1028
[d9ece1cb]1029/** Syscall wrapper for sleeping. */
[96b02eb9]1030sysarg_t sys_thread_usleep(uint32_t usec)
[d9ece1cb]1031{
[22e6802]1032 thread_usleep(usec);
[d9ece1cb]1033 return 0;
1034}
1035
[7e7b791]1036sysarg_t sys_thread_udelay(uint32_t usec)
1037{
[8d6c1f1]1038 delay(usec);
[7e7b791]1039 return 0;
1040}
1041
[3ce7f082]1042/** @}
1043 */
Note: See TracBrowser for help on using the repository browser.