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

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

thread: thread_ready() new prefers cpus where thread last ran. Added thread_interrupt().

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