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

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

workq: Add work queues: allow blocking work items, queuing items from interrupt handlers.

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