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

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since 55b77d9 was 55b77d9, checked in by Jiri Svoboda <jiri@…>, 14 years ago

Separate list_t typedef from link_t (kernel part).

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