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

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

preemption_disable: Replaced memory barriers with compiler barriers. Added checks if reschedule is needed once preemption is enabled.

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