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

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since 207e8880 was 669f3d32, checked in by Adam Hraska <adam.hraska+hos@…>, 13 years ago

Adapted the kernel futex subsystem to use CHT.

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