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

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since 0cfc18d3 was b1c57a8, checked in by Jakub Jermar <jakub@…>, 11 years ago

Merge from lp:~adam-hraska+lp/helenos/rcu/.

Only merge from the feature branch and resolve all conflicts.

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