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

Last change on this file since 338a1a76 was 1fb4a49, checked in by Matthieu Riolo <matthieu.riolo@…>, 7 years ago

kernel: Add exit reason parameter to EVENT_EXIT

  • So that own termination can be distinguished from kills by (typically) third party.
  • Translation from exit_reason_t to task_exit_t is left to uspace (taskman).

Conflicts:

kernel/generic/include/proc/task.h
kernel/generic/src/proc/task.c

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