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

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

do not provide general access to kernel headers from uspace, only allow specific headers to be accessed or shared
externalize headers which serve as kernel/uspace API/ABI into a special tree

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