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

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since d1da1ff2 was d1da1ff2, checked in by Jiří Zárevúcky <zarevucky.jiri@…>, 7 years ago

Fix kernel stack allocation

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