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

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since a5c468e was aafed15, checked in by Jiří Zárevúcky <zarevucky.jiri@…>, 7 years ago

Declare malloc() etc in standard <stdlib.h> rather than <mm/slab.h>

  • 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 <cpu.h>
51#include <str.h>
52#include <context.h>
53#include <adt/list.h>
54#include <adt/odict.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 <mem.h>
64#include <stdio.h>
65#include <stdlib.h>
66#include <main/uinit.h>
67#include <syscall/copy.h>
68#include <errno.h>
69#include <debug.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
82/** Lock protecting the @c threads ordered dictionary .
83 *
84 * For locking rules, see declaration thereof.
85 */
86IRQ_SPINLOCK_INITIALIZE(threads_lock);
87
88/** Ordered dictionary of all threads by their address (i.e. pointer to
89 * the thread_t structure).
90 *
91 * When a thread is found in the @c threads ordered dictionary, it is
92 * guaranteed to exist as long as the @c threads_lock is held.
93 *
94 * Members are of type thread_t.
95 */
96odict_t threads;
97
98IRQ_SPINLOCK_STATIC_INITIALIZE(tidlock);
99static thread_id_t last_tid = 0;
100
101static slab_cache_t *thread_cache;
102
103#ifdef CONFIG_FPU
104slab_cache_t *fpu_context_cache;
105#endif
106
107static void *threads_getkey(odlink_t *);
108static int threads_cmp(void *, void *);
109
110/** Thread wrapper.
111 *
112 * This wrapper is provided to ensure that every thread makes a call to
113 * thread_exit() when its implementing function returns.
114 *
115 * interrupts_disable() is assumed.
116 *
117 */
118static void cushion(void)
119{
120 void (*f)(void *) = THREAD->thread_code;
121 void *arg = THREAD->thread_arg;
122 THREAD->last_cycle = get_cycle();
123
124 /* This is where each thread wakes up after its creation */
125 irq_spinlock_unlock(&THREAD->lock, false);
126 interrupts_enable();
127
128 f(arg);
129
130 /* Accumulate accounting to the task */
131 irq_spinlock_lock(&THREAD->lock, true);
132 if (!THREAD->uncounted) {
133 thread_update_accounting(true);
134 uint64_t ucycles = THREAD->ucycles;
135 THREAD->ucycles = 0;
136 uint64_t kcycles = THREAD->kcycles;
137 THREAD->kcycles = 0;
138
139 irq_spinlock_pass(&THREAD->lock, &TASK->lock);
140 TASK->ucycles += ucycles;
141 TASK->kcycles += kcycles;
142 irq_spinlock_unlock(&TASK->lock, true);
143 } else
144 irq_spinlock_unlock(&THREAD->lock, true);
145
146 thread_exit();
147
148 /* Not reached */
149}
150
151/** Initialization and allocation for thread_t structure
152 *
153 */
154static errno_t thr_constructor(void *obj, unsigned int kmflags)
155{
156 thread_t *thread = (thread_t *) obj;
157
158 irq_spinlock_initialize(&thread->lock, "thread_t_lock");
159 link_initialize(&thread->rq_link);
160 link_initialize(&thread->wq_link);
161 link_initialize(&thread->th_link);
162
163 /* call the architecture-specific part of the constructor */
164 thr_constructor_arch(thread);
165
166#ifdef CONFIG_FPU
167 thread->saved_fpu_context = slab_alloc(fpu_context_cache,
168 FRAME_ATOMIC | kmflags);
169 if (!thread->saved_fpu_context)
170 return ENOMEM;
171#endif /* CONFIG_FPU */
172
173 /*
174 * Allocate the kernel stack from the low-memory to prevent an infinite
175 * nesting of TLB-misses when accessing the stack from the part of the
176 * TLB-miss handler written in C.
177 *
178 * Note that low-memory is safe to be used for the stack as it will be
179 * covered by the kernel identity mapping, which guarantees not to
180 * nest TLB-misses infinitely (either via some hardware mechanism or
181 * by the construciton of the assembly-language part of the TLB-miss
182 * handler).
183 *
184 * This restriction can be lifted once each architecture provides
185 * a similar guarantee, for example by locking the kernel stack
186 * in the TLB whenever it is allocated from the high-memory and the
187 * thread is being scheduled to run.
188 */
189 kmflags |= FRAME_LOWMEM;
190 kmflags &= ~FRAME_HIGHMEM;
191
192 // NOTE: All kernel stacks must be aligned to STACK_SIZE,
193 // see get_stack_base().
194
195 uintptr_t stack_phys =
196 frame_alloc(STACK_FRAMES, kmflags, STACK_SIZE - 1);
197 if (!stack_phys) {
198#ifdef CONFIG_FPU
199 assert(thread->saved_fpu_context);
200 slab_free(fpu_context_cache, thread->saved_fpu_context);
201#endif
202 return ENOMEM;
203 }
204
205 thread->kstack = (uint8_t *) PA2KA(stack_phys);
206
207#ifdef CONFIG_UDEBUG
208 mutex_initialize(&thread->udebug.lock, MUTEX_PASSIVE);
209#endif
210
211 return EOK;
212}
213
214/** Destruction of thread_t object */
215static size_t thr_destructor(void *obj)
216{
217 thread_t *thread = (thread_t *) obj;
218
219 /* call the architecture-specific part of the destructor */
220 thr_destructor_arch(thread);
221
222 frame_free(KA2PA(thread->kstack), STACK_FRAMES);
223
224#ifdef CONFIG_FPU
225 assert(thread->saved_fpu_context);
226 slab_free(fpu_context_cache, thread->saved_fpu_context);
227#endif
228
229 return STACK_FRAMES; /* number of frames freed */
230}
231
232/** Initialize threads
233 *
234 * Initialize kernel threads support.
235 *
236 */
237void thread_init(void)
238{
239 THREAD = NULL;
240
241 atomic_store(&nrdy, 0);
242 thread_cache = slab_cache_create("thread_t", sizeof(thread_t), 0,
243 thr_constructor, thr_destructor, 0);
244
245#ifdef CONFIG_FPU
246 fpu_context_cache = slab_cache_create("fpu_context_t",
247 sizeof(fpu_context_t), FPU_CONTEXT_ALIGN, NULL, NULL, 0);
248#endif
249
250 odict_initialize(&threads, threads_getkey, threads_cmp);
251}
252
253/** Wire thread to the given CPU
254 *
255 * @param cpu CPU to wire the thread to.
256 *
257 */
258void thread_wire(thread_t *thread, cpu_t *cpu)
259{
260 irq_spinlock_lock(&thread->lock, true);
261 thread->cpu = cpu;
262 thread->wired = true;
263 irq_spinlock_unlock(&thread->lock, true);
264}
265
266/** Invoked right before thread_ready() readies the thread. thread is locked. */
267static void before_thread_is_ready(thread_t *thread)
268{
269 assert(irq_spinlock_locked(&thread->lock));
270}
271
272/** Make thread ready
273 *
274 * Switch thread to the ready state.
275 *
276 * @param thread Thread to make ready.
277 *
278 */
279void thread_ready(thread_t *thread)
280{
281 irq_spinlock_lock(&thread->lock, true);
282
283 assert(thread->state != Ready);
284
285 before_thread_is_ready(thread);
286
287 int i = (thread->priority < RQ_COUNT - 1) ?
288 ++thread->priority : thread->priority;
289
290 cpu_t *cpu;
291 if (thread->wired || thread->nomigrate || thread->fpu_context_engaged) {
292 /* Cannot ready to another CPU */
293 assert(thread->cpu != NULL);
294 cpu = thread->cpu;
295 } else if (thread->stolen) {
296 /* Ready to the stealing CPU */
297 cpu = CPU;
298 } else if (thread->cpu) {
299 /* Prefer the CPU on which the thread ran last */
300 assert(thread->cpu != NULL);
301 cpu = thread->cpu;
302 } else {
303 cpu = CPU;
304 }
305
306 thread->state = Ready;
307
308 irq_spinlock_pass(&thread->lock, &(cpu->rq[i].lock));
309
310 /*
311 * Append thread to respective ready queue
312 * on respective processor.
313 */
314
315 list_append(&thread->rq_link, &cpu->rq[i].rq);
316 cpu->rq[i].n++;
317 irq_spinlock_unlock(&(cpu->rq[i].lock), true);
318
319 atomic_inc(&nrdy);
320 atomic_inc(&cpu->nrdy);
321}
322
323/** Create new thread
324 *
325 * Create a new thread.
326 *
327 * @param func Thread's implementing function.
328 * @param arg Thread's implementing function argument.
329 * @param task Task to which the thread belongs. The caller must
330 * guarantee that the task won't cease to exist during the
331 * call. The task's lock may not be held.
332 * @param flags Thread flags.
333 * @param name Symbolic name (a copy is made).
334 *
335 * @return New thread's structure on success, NULL on failure.
336 *
337 */
338thread_t *thread_create(void (*func)(void *), void *arg, task_t *task,
339 thread_flags_t flags, const char *name)
340{
341 thread_t *thread = (thread_t *) slab_alloc(thread_cache, FRAME_ATOMIC);
342 if (!thread)
343 return NULL;
344
345 if (thread_create_arch(thread, flags) != EOK) {
346 slab_free(thread_cache, thread);
347 return NULL;
348 }
349
350 /* Not needed, but good for debugging */
351 memsetb(thread->kstack, STACK_SIZE, 0);
352
353 irq_spinlock_lock(&tidlock, true);
354 thread->tid = ++last_tid;
355 irq_spinlock_unlock(&tidlock, true);
356
357 memset(&thread->saved_context, 0, sizeof(thread->saved_context));
358 context_set(&thread->saved_context, FADDR(cushion),
359 (uintptr_t) thread->kstack, STACK_SIZE);
360
361 current_initialize((current_t *) thread->kstack);
362
363 ipl_t ipl = interrupts_disable();
364 thread->saved_context.ipl = interrupts_read();
365 interrupts_restore(ipl);
366
367 str_cpy(thread->name, THREAD_NAME_BUFLEN, name);
368
369 thread->thread_code = func;
370 thread->thread_arg = arg;
371 thread->ticks = -1;
372 thread->ucycles = 0;
373 thread->kcycles = 0;
374 thread->uncounted =
375 ((flags & THREAD_FLAG_UNCOUNTED) == THREAD_FLAG_UNCOUNTED);
376 thread->priority = -1; /* Start in rq[0] */
377 thread->cpu = NULL;
378 thread->wired = false;
379 thread->stolen = false;
380 thread->uspace =
381 ((flags & THREAD_FLAG_USPACE) == THREAD_FLAG_USPACE);
382
383 thread->nomigrate = 0;
384 thread->state = Entering;
385
386 timeout_initialize(&thread->sleep_timeout);
387 thread->sleep_interruptible = false;
388 thread->sleep_composable = false;
389 thread->sleep_queue = NULL;
390 thread->timeout_pending = false;
391
392 thread->in_copy_from_uspace = false;
393 thread->in_copy_to_uspace = false;
394
395 thread->interrupted = false;
396 thread->detached = false;
397 waitq_initialize(&thread->join_wq);
398
399 thread->task = task;
400
401 thread->fpu_context_exists = false;
402 thread->fpu_context_engaged = false;
403
404 odlink_initialize(&thread->lthreads);
405
406#ifdef CONFIG_UDEBUG
407 /* Initialize debugging stuff */
408 thread->btrace = false;
409 udebug_thread_initialize(&thread->udebug);
410#endif
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 odict_remove(&thread->lthreads);
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_cache, 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 dictionary.
487 */
488 odict_insert(&thread->lthreads, &threads, NULL);
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_task_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
544/** Interrupts an existing thread so that it may exit as soon as possible.
545 *
546 * Threads that are blocked waiting for a synchronization primitive
547 * are woken up with a return code of EINTR if the
548 * blocking call was interruptable. See waitq_sleep_timeout().
549 *
550 * The caller must guarantee the thread object is valid during the entire
551 * function, eg by holding the threads_lock lock.
552 *
553 * Interrupted threads automatically exit when returning back to user space.
554 *
555 * @param thread A valid thread object. The caller must guarantee it
556 * will remain valid until thread_interrupt() exits.
557 */
558void thread_interrupt(thread_t *thread)
559{
560 assert(thread != NULL);
561
562 irq_spinlock_lock(&thread->lock, true);
563
564 thread->interrupted = true;
565 bool sleeping = (thread->state == Sleeping);
566
567 irq_spinlock_unlock(&thread->lock, true);
568
569 if (sleeping)
570 waitq_interrupt_sleep(thread);
571}
572
573/** Returns true if the thread was interrupted.
574 *
575 * @param thread A valid thread object. User must guarantee it will
576 * be alive during the entire call.
577 * @return true if the thread was already interrupted via thread_interrupt().
578 */
579bool thread_interrupted(thread_t *thread)
580{
581 assert(thread != NULL);
582
583 bool interrupted;
584
585 irq_spinlock_lock(&thread->lock, true);
586 interrupted = thread->interrupted;
587 irq_spinlock_unlock(&thread->lock, true);
588
589 return interrupted;
590}
591
592/** Prevent the current thread from being migrated to another processor. */
593void thread_migration_disable(void)
594{
595 assert(THREAD);
596
597 THREAD->nomigrate++;
598}
599
600/** Allow the current thread to be migrated to another processor. */
601void thread_migration_enable(void)
602{
603 assert(THREAD);
604 assert(THREAD->nomigrate > 0);
605
606 if (THREAD->nomigrate > 0)
607 THREAD->nomigrate--;
608}
609
610/** Thread sleep
611 *
612 * Suspend execution of the current thread.
613 *
614 * @param sec Number of seconds to sleep.
615 *
616 */
617void thread_sleep(uint32_t sec)
618{
619 /*
620 * Sleep in 1000 second steps to support
621 * full argument range
622 */
623 while (sec > 0) {
624 uint32_t period = (sec > 1000) ? 1000 : sec;
625
626 thread_usleep(period * 1000000);
627 sec -= period;
628 }
629}
630
631/** Wait for another thread to exit.
632 *
633 * @param thread Thread to join on exit.
634 * @param usec Timeout in microseconds.
635 * @param flags Mode of operation.
636 *
637 * @return An error code from errno.h or an error code from synch.h.
638 *
639 */
640errno_t thread_join_timeout(thread_t *thread, uint32_t usec, unsigned int flags)
641{
642 if (thread == THREAD)
643 return EINVAL;
644
645 /*
646 * Since thread join can only be called once on an undetached thread,
647 * the thread pointer is guaranteed to be still valid.
648 */
649
650 irq_spinlock_lock(&thread->lock, true);
651 assert(!thread->detached);
652 irq_spinlock_unlock(&thread->lock, true);
653
654 return waitq_sleep_timeout(&thread->join_wq, usec, flags, NULL);
655
656 // FIXME: join should deallocate the thread.
657 // Current code calls detach after join, that's contrary to how
658 // join is used in other threading APIs.
659}
660
661/** Detach thread.
662 *
663 * Mark the thread as detached. If the thread is already
664 * in the Lingering state, deallocate its resources.
665 *
666 * @param thread Thread to be detached.
667 *
668 */
669void thread_detach(thread_t *thread)
670{
671 /*
672 * Since the thread is expected not to be already detached,
673 * pointer to it must be still valid.
674 */
675 irq_spinlock_lock(&thread->lock, true);
676 assert(!thread->detached);
677
678 if (thread->state == Lingering) {
679 /*
680 * Unlock &thread->lock and restore
681 * interrupts in thread_destroy().
682 */
683 thread_destroy(thread, true);
684 return;
685 } else {
686 thread->detached = true;
687 }
688
689 irq_spinlock_unlock(&thread->lock, true);
690}
691
692/** Thread usleep
693 *
694 * Suspend execution of the current thread.
695 *
696 * @param usec Number of microseconds to sleep.
697 *
698 */
699void thread_usleep(uint32_t usec)
700{
701 waitq_t wq;
702
703 waitq_initialize(&wq);
704
705 (void) waitq_sleep_timeout(&wq, usec, SYNCH_FLAGS_NON_BLOCKING, NULL);
706}
707
708static void thread_print(thread_t *thread, bool additional)
709{
710 uint64_t ucycles, kcycles;
711 char usuffix, ksuffix;
712 order_suffix(thread->ucycles, &ucycles, &usuffix);
713 order_suffix(thread->kcycles, &kcycles, &ksuffix);
714
715 char *name;
716 if (str_cmp(thread->name, "uinit") == 0)
717 name = thread->task->name;
718 else
719 name = thread->name;
720
721#ifdef __32_BITS__
722 if (additional)
723 printf("%-8" PRIu64 " %10p %10p %9" PRIu64 "%c %9" PRIu64 "%c ",
724 thread->tid, thread->thread_code, thread->kstack,
725 ucycles, usuffix, kcycles, ksuffix);
726 else
727 printf("%-8" PRIu64 " %-14s %10p %-8s %10p %-5" PRIu32 "\n",
728 thread->tid, name, thread, thread_states[thread->state],
729 thread->task, thread->task->container);
730#endif
731
732#ifdef __64_BITS__
733 if (additional)
734 printf("%-8" PRIu64 " %18p %18p\n"
735 " %9" PRIu64 "%c %9" PRIu64 "%c ",
736 thread->tid, thread->thread_code, thread->kstack,
737 ucycles, usuffix, kcycles, ksuffix);
738 else
739 printf("%-8" PRIu64 " %-14s %18p %-8s %18p %-5" PRIu32 "\n",
740 thread->tid, name, thread, thread_states[thread->state],
741 thread->task, thread->task->container);
742#endif
743
744 if (additional) {
745 if (thread->cpu)
746 printf("%-5u", thread->cpu->id);
747 else
748 printf("none ");
749
750 if (thread->state == Sleeping) {
751#ifdef __32_BITS__
752 printf(" %10p", thread->sleep_queue);
753#endif
754
755#ifdef __64_BITS__
756 printf(" %18p", thread->sleep_queue);
757#endif
758 }
759
760 printf("\n");
761 }
762}
763
764/** Print list of threads debug info
765 *
766 * @param additional Print additional information.
767 *
768 */
769void thread_print_list(bool additional)
770{
771 thread_t *thread;
772
773 /* Messing with thread structures, avoid deadlock */
774 irq_spinlock_lock(&threads_lock, true);
775
776#ifdef __32_BITS__
777 if (additional)
778 printf("[id ] [code ] [stack ] [ucycles ] [kcycles ]"
779 " [cpu] [waitqueue]\n");
780 else
781 printf("[id ] [name ] [address ] [state ] [task ]"
782 " [ctn]\n");
783#endif
784
785#ifdef __64_BITS__
786 if (additional) {
787 printf("[id ] [code ] [stack ]\n"
788 " [ucycles ] [kcycles ] [cpu] [waitqueue ]\n");
789 } else
790 printf("[id ] [name ] [address ] [state ]"
791 " [task ] [ctn]\n");
792#endif
793
794 thread = thread_first();
795 while (thread != NULL) {
796 thread_print(thread, additional);
797 thread = thread_next(thread);
798 }
799
800 irq_spinlock_unlock(&threads_lock, true);
801}
802
803/** Check whether thread exists.
804 *
805 * Note that threads_lock must be already held and
806 * interrupts must be already disabled.
807 *
808 * @param thread Pointer to thread.
809 *
810 * @return True if thread t is known to the system, false otherwise.
811 *
812 */
813bool thread_exists(thread_t *thread)
814{
815 assert(interrupts_disabled());
816 assert(irq_spinlock_locked(&threads_lock));
817
818 odlink_t *odlink = odict_find_eq(&threads, thread, NULL);
819 return odlink != NULL;
820}
821
822/** Update accounting of current thread.
823 *
824 * Note that thread_lock on THREAD must be already held and
825 * interrupts must be already disabled.
826 *
827 * @param user True to update user accounting, false for kernel.
828 *
829 */
830void thread_update_accounting(bool user)
831{
832 uint64_t time = get_cycle();
833
834 assert(interrupts_disabled());
835 assert(irq_spinlock_locked(&THREAD->lock));
836
837 if (user)
838 THREAD->ucycles += time - THREAD->last_cycle;
839 else
840 THREAD->kcycles += time - THREAD->last_cycle;
841
842 THREAD->last_cycle = time;
843}
844
845/** Find thread structure corresponding to thread ID.
846 *
847 * The threads_lock must be already held by the caller of this function and
848 * interrupts must be disabled.
849 *
850 * @param id Thread ID.
851 *
852 * @return Thread structure address or NULL if there is no such thread ID.
853 *
854 */
855thread_t *thread_find_by_id(thread_id_t thread_id)
856{
857 thread_t *thread;
858
859 assert(interrupts_disabled());
860 assert(irq_spinlock_locked(&threads_lock));
861
862 thread = thread_first();
863 while (thread != NULL) {
864 if (thread->tid == thread_id)
865 return thread;
866
867 thread = thread_next(thread);
868 }
869
870 return NULL;
871}
872
873/** Get count of threads.
874 *
875 * @return Number of threads in the system
876 */
877size_t thread_count(void)
878{
879 assert(interrupts_disabled());
880 assert(irq_spinlock_locked(&threads_lock));
881
882 return odict_count(&threads);
883}
884
885/** Get first thread.
886 *
887 * @return Pointer to first thread or @c NULL if there are none.
888 */
889thread_t *thread_first(void)
890{
891 odlink_t *odlink;
892
893 assert(interrupts_disabled());
894 assert(irq_spinlock_locked(&threads_lock));
895
896 odlink = odict_first(&threads);
897 if (odlink == NULL)
898 return NULL;
899
900 return odict_get_instance(odlink, thread_t, lthreads);
901}
902
903/** Get next thread.
904 *
905 * @param cur Current thread
906 * @return Pointer to next thread or @c NULL if there are no more threads.
907 */
908thread_t *thread_next(thread_t *cur)
909{
910 odlink_t *odlink;
911
912 assert(interrupts_disabled());
913 assert(irq_spinlock_locked(&threads_lock));
914
915 odlink = odict_next(&cur->lthreads, &threads);
916 if (odlink == NULL)
917 return NULL;
918
919 return odict_get_instance(odlink, thread_t, lthreads);
920}
921
922#ifdef CONFIG_UDEBUG
923
924void thread_stack_trace(thread_id_t thread_id)
925{
926 irq_spinlock_lock(&threads_lock, true);
927
928 thread_t *thread = thread_find_by_id(thread_id);
929 if (thread == NULL) {
930 printf("No such thread.\n");
931 irq_spinlock_unlock(&threads_lock, true);
932 return;
933 }
934
935 irq_spinlock_lock(&thread->lock, false);
936
937 /*
938 * Schedule a stack trace to be printed
939 * just before the thread is scheduled next.
940 *
941 * If the thread is sleeping then try to interrupt
942 * the sleep. Any request for printing an uspace stack
943 * trace from within the kernel should be always
944 * considered a last resort debugging means, therefore
945 * forcing the thread's sleep to be interrupted
946 * is probably justifiable.
947 */
948
949 bool sleeping = false;
950 istate_t *istate = thread->udebug.uspace_state;
951 if (istate != NULL) {
952 printf("Scheduling thread stack trace.\n");
953 thread->btrace = true;
954 if (thread->state == Sleeping)
955 sleeping = true;
956 } else
957 printf("Thread interrupt state not available.\n");
958
959 irq_spinlock_unlock(&thread->lock, false);
960
961 if (sleeping)
962 waitq_interrupt_sleep(thread);
963
964 irq_spinlock_unlock(&threads_lock, true);
965}
966
967#endif /* CONFIG_UDEBUG */
968
969/** Get key function for the @c threads ordered dictionary.
970 *
971 * @param odlink Link
972 * @return Pointer to thread structure cast as 'void *'
973 */
974static void *threads_getkey(odlink_t *odlink)
975{
976 thread_t *thread = odict_get_instance(odlink, thread_t, lthreads);
977 return (void *) thread;
978}
979
980/** Key comparison function for the @c threads ordered dictionary.
981 *
982 * @param a Pointer to thread A
983 * @param b Pointer to thread B
984 * @return -1, 0, 1 iff pointer to A is less than, equal to, greater than B
985 */
986static int threads_cmp(void *a, void *b)
987{
988 if (a > b)
989 return -1;
990 else if (a == b)
991 return 0;
992 else
993 return +1;
994}
995
996/** Process syscall to create new thread.
997 *
998 */
999sys_errno_t sys_thread_create(uspace_arg_t *uspace_uarg, char *uspace_name,
1000 size_t name_len, thread_id_t *uspace_thread_id)
1001{
1002 if (name_len > THREAD_NAME_BUFLEN - 1)
1003 name_len = THREAD_NAME_BUFLEN - 1;
1004
1005 char namebuf[THREAD_NAME_BUFLEN];
1006 errno_t rc = copy_from_uspace(namebuf, uspace_name, name_len);
1007 if (rc != EOK)
1008 return (sys_errno_t) rc;
1009
1010 namebuf[name_len] = 0;
1011
1012 /*
1013 * In case of failure, kernel_uarg will be deallocated in this function.
1014 * In case of success, kernel_uarg will be freed in uinit().
1015 */
1016 uspace_arg_t *kernel_uarg =
1017 (uspace_arg_t *) malloc(sizeof(uspace_arg_t));
1018 if (!kernel_uarg)
1019 return (sys_errno_t) ENOMEM;
1020
1021 rc = copy_from_uspace(kernel_uarg, uspace_uarg, sizeof(uspace_arg_t));
1022 if (rc != EOK) {
1023 free(kernel_uarg);
1024 return (sys_errno_t) rc;
1025 }
1026
1027 thread_t *thread = thread_create(uinit, kernel_uarg, TASK,
1028 THREAD_FLAG_USPACE | THREAD_FLAG_NOATTACH, namebuf);
1029 if (thread) {
1030 if (uspace_thread_id != NULL) {
1031 rc = copy_to_uspace(uspace_thread_id, &thread->tid,
1032 sizeof(thread->tid));
1033 if (rc != EOK) {
1034 /*
1035 * We have encountered a failure, but the thread
1036 * has already been created. We need to undo its
1037 * creation now.
1038 */
1039
1040 /*
1041 * The new thread structure is initialized, but
1042 * is still not visible to the system.
1043 * We can safely deallocate it.
1044 */
1045 slab_free(thread_cache, thread);
1046 free(kernel_uarg);
1047
1048 return (sys_errno_t) rc;
1049 }
1050 }
1051
1052#ifdef CONFIG_UDEBUG
1053 /*
1054 * Generate udebug THREAD_B event and attach the thread.
1055 * This must be done atomically (with the debug locks held),
1056 * otherwise we would either miss some thread or receive
1057 * THREAD_B events for threads that already existed
1058 * and could be detected with THREAD_READ before.
1059 */
1060 udebug_thread_b_event_attach(thread, TASK);
1061#else
1062 thread_attach(thread, TASK);
1063#endif
1064 thread_ready(thread);
1065
1066 return 0;
1067 } else
1068 free(kernel_uarg);
1069
1070 return (sys_errno_t) ENOMEM;
1071}
1072
1073/** Process syscall to terminate thread.
1074 *
1075 */
1076sys_errno_t sys_thread_exit(int uspace_status)
1077{
1078 thread_exit();
1079}
1080
1081/** Syscall for getting TID.
1082 *
1083 * @param uspace_thread_id Userspace address of 8-byte buffer where to store
1084 * current thread ID.
1085 *
1086 * @return 0 on success or an error code from @ref errno.h.
1087 *
1088 */
1089sys_errno_t sys_thread_get_id(thread_id_t *uspace_thread_id)
1090{
1091 /*
1092 * No need to acquire lock on THREAD because tid
1093 * remains constant for the lifespan of the thread.
1094 *
1095 */
1096 return (sys_errno_t) copy_to_uspace(uspace_thread_id, &THREAD->tid,
1097 sizeof(THREAD->tid));
1098}
1099
1100/** Syscall wrapper for sleeping. */
1101sys_errno_t sys_thread_usleep(uint32_t usec)
1102{
1103 thread_usleep(usec);
1104 return 0;
1105}
1106
1107sys_errno_t sys_thread_udelay(uint32_t usec)
1108{
1109 delay(usec);
1110 return 0;
1111}
1112
1113/** @}
1114 */
Note: See TracBrowser for help on using the repository browser.