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

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since 128359eb was 128359eb, checked in by Martin Decky <martin@…>, 5 years ago

Replace get_stack_base() with builtin_frame_address(0)

The usage of an intrinsic function to obtain the current stack pointer
should provide the compuler more room for performance optimizations than
the hand-written (and volatile) inline assembly block.

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