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

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since cd3b380 was cd3b380, checked in by Martin Decky <martin@…>, 12 years ago

due to the removal of FRAME_KA, the return value of frame_alloc*() needs to be checked before converting the physical address to kernel address

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