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

Last change on this file since 5861b60 was 151c050, checked in by Jiří Zárevúcky <zarevucky.jiri@…>, 18 months ago

Rethink scheduler entry points

Changes the way scheduler is entered, to eliminate some unnecessary
locking and interrupt disables.

  • Property mode set to 100644
File size: 28.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 <memw.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#include <halt.h>
72
73/** Thread states */
74const char *thread_states[] = {
75 "Invalid",
76 "Running",
77 "Sleeping",
78 "Ready",
79 "Entering",
80 "Exiting",
81 "Lingering"
82};
83
84/** Lock protecting the @c threads ordered dictionary .
85 *
86 * For locking rules, see declaration thereof.
87 */
88IRQ_SPINLOCK_INITIALIZE(threads_lock);
89
90/** Ordered dictionary of all threads by their address (i.e. pointer to
91 * the thread_t structure).
92 *
93 * When a thread is found in the @c threads ordered dictionary, it is
94 * guaranteed to exist as long as the @c threads_lock is held.
95 *
96 * Members are of type thread_t.
97 *
98 * This structure contains weak references. Any reference from it must not leave
99 * threads_lock critical section unless strengthened via thread_try_ref().
100 */
101odict_t threads;
102
103IRQ_SPINLOCK_STATIC_INITIALIZE(tidlock);
104static thread_id_t last_tid = 0;
105
106static slab_cache_t *thread_cache;
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
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 thread_exit();
131
132 /* Not reached */
133}
134
135/** Initialization and allocation for thread_t structure
136 *
137 */
138static errno_t thr_constructor(void *obj, unsigned int kmflags)
139{
140 thread_t *thread = (thread_t *) obj;
141
142 irq_spinlock_initialize(&thread->lock, "thread_t_lock");
143 link_initialize(&thread->rq_link);
144 link_initialize(&thread->wq_link);
145 link_initialize(&thread->th_link);
146
147 /* call the architecture-specific part of the constructor */
148 thr_constructor_arch(thread);
149
150 /*
151 * Allocate the kernel stack from the low-memory to prevent an infinite
152 * nesting of TLB-misses when accessing the stack from the part of the
153 * TLB-miss handler written in C.
154 *
155 * Note that low-memory is safe to be used for the stack as it will be
156 * covered by the kernel identity mapping, which guarantees not to
157 * nest TLB-misses infinitely (either via some hardware mechanism or
158 * by the construction of the assembly-language part of the TLB-miss
159 * handler).
160 *
161 * This restriction can be lifted once each architecture provides
162 * a similar guarantee, for example, by locking the kernel stack
163 * in the TLB whenever it is allocated from the high-memory and the
164 * thread is being scheduled to run.
165 */
166 kmflags |= FRAME_LOWMEM;
167 kmflags &= ~FRAME_HIGHMEM;
168
169 /*
170 * NOTE: All kernel stacks must be aligned to STACK_SIZE,
171 * see CURRENT.
172 */
173
174 uintptr_t stack_phys =
175 frame_alloc(STACK_FRAMES, kmflags, STACK_SIZE - 1);
176 if (!stack_phys)
177 return ENOMEM;
178
179 thread->kstack = (uint8_t *) PA2KA(stack_phys);
180
181#ifdef CONFIG_UDEBUG
182 mutex_initialize(&thread->udebug.lock, MUTEX_PASSIVE);
183#endif
184
185 return EOK;
186}
187
188/** Destruction of thread_t object */
189static size_t thr_destructor(void *obj)
190{
191 thread_t *thread = (thread_t *) obj;
192
193 /* call the architecture-specific part of the destructor */
194 thr_destructor_arch(thread);
195
196 frame_free(KA2PA(thread->kstack), STACK_FRAMES);
197
198 return STACK_FRAMES; /* number of frames freed */
199}
200
201/** Initialize threads
202 *
203 * Initialize kernel threads support.
204 *
205 */
206void thread_init(void)
207{
208 THREAD = NULL;
209
210 atomic_store(&nrdy, 0);
211 thread_cache = slab_cache_create("thread_t", sizeof(thread_t), _Alignof(thread_t),
212 thr_constructor, thr_destructor, 0);
213
214 odict_initialize(&threads, threads_getkey, threads_cmp);
215}
216
217/** Wire thread to the given CPU
218 *
219 * @param cpu CPU to wire the thread to.
220 *
221 */
222void thread_wire(thread_t *thread, cpu_t *cpu)
223{
224 irq_spinlock_lock(&thread->lock, true);
225 thread->cpu = cpu;
226 thread->nomigrate++;
227 irq_spinlock_unlock(&thread->lock, true);
228}
229
230/** Invoked right before thread_ready() readies the thread. thread is locked. */
231static void before_thread_is_ready(thread_t *thread)
232{
233 assert(irq_spinlock_locked(&thread->lock));
234}
235
236/** Make thread ready
237 *
238 * Switch thread to the ready state. Consumes reference passed by the caller.
239 *
240 * @param thread Thread to make ready.
241 *
242 */
243void thread_ready(thread_t *thread)
244{
245 irq_spinlock_lock(&thread->lock, true);
246
247 assert(thread->state != Ready);
248
249 before_thread_is_ready(thread);
250
251 int i = (thread->priority < RQ_COUNT - 1) ?
252 ++thread->priority : thread->priority;
253
254 /* Prefer the CPU on which the thread ran last */
255 cpu_t *cpu = thread->cpu ? thread->cpu : CPU;
256
257 thread->state = Ready;
258
259 irq_spinlock_pass(&thread->lock, &(cpu->rq[i].lock));
260
261 /*
262 * Append thread to respective ready queue
263 * on respective processor.
264 */
265
266 list_append(&thread->rq_link, &cpu->rq[i].rq);
267 cpu->rq[i].n++;
268 irq_spinlock_unlock(&(cpu->rq[i].lock), true);
269
270 atomic_inc(&nrdy);
271 atomic_inc(&cpu->nrdy);
272}
273
274/** Create new thread
275 *
276 * Create a new thread.
277 *
278 * @param func Thread's implementing function.
279 * @param arg Thread's implementing function argument.
280 * @param task Task to which the thread belongs. The caller must
281 * guarantee that the task won't cease to exist during the
282 * call. The task's lock may not be held.
283 * @param flags Thread flags.
284 * @param name Symbolic name (a copy is made).
285 *
286 * @return New thread's structure on success, NULL on failure.
287 *
288 */
289thread_t *thread_create(void (*func)(void *), void *arg, task_t *task,
290 thread_flags_t flags, const char *name)
291{
292 thread_t *thread = (thread_t *) slab_alloc(thread_cache, FRAME_ATOMIC);
293 if (!thread)
294 return NULL;
295
296 refcount_init(&thread->refcount);
297
298 if (thread_create_arch(thread, flags) != EOK) {
299 slab_free(thread_cache, thread);
300 return NULL;
301 }
302
303 /* Not needed, but good for debugging */
304 memsetb(thread->kstack, STACK_SIZE, 0);
305
306 irq_spinlock_lock(&tidlock, true);
307 thread->tid = ++last_tid;
308 irq_spinlock_unlock(&tidlock, true);
309
310 memset(&thread->saved_context, 0, sizeof(thread->saved_context));
311 context_set(&thread->saved_context, FADDR(cushion),
312 (uintptr_t) thread->kstack, STACK_SIZE);
313
314 current_initialize((current_t *) thread->kstack);
315
316 str_cpy(thread->name, THREAD_NAME_BUFLEN, name);
317
318 thread->thread_code = func;
319 thread->thread_arg = arg;
320 thread->ucycles = 0;
321 thread->kcycles = 0;
322 thread->uncounted =
323 ((flags & THREAD_FLAG_UNCOUNTED) == THREAD_FLAG_UNCOUNTED);
324 thread->priority = -1; /* Start in rq[0] */
325 thread->cpu = NULL;
326 thread->stolen = false;
327 thread->uspace =
328 ((flags & THREAD_FLAG_USPACE) == THREAD_FLAG_USPACE);
329
330 thread->nomigrate = 0;
331 thread->state = Entering;
332
333 atomic_init(&thread->sleep_queue, NULL);
334
335 thread->in_copy_from_uspace = false;
336 thread->in_copy_to_uspace = false;
337
338 thread->interrupted = false;
339 atomic_init(&thread->sleep_state, SLEEP_INITIAL);
340
341 waitq_initialize(&thread->join_wq);
342
343 thread->task = task;
344
345 thread->fpu_context_exists = false;
346
347 odlink_initialize(&thread->lthreads);
348
349#ifdef CONFIG_UDEBUG
350 /* Initialize debugging stuff */
351 thread->btrace = false;
352 udebug_thread_initialize(&thread->udebug);
353#endif
354
355 if ((flags & THREAD_FLAG_NOATTACH) != THREAD_FLAG_NOATTACH)
356 thread_attach(thread, task);
357
358 return thread;
359}
360
361/** Destroy thread memory structure
362 *
363 * Detach thread from all queues, cpus etc. and destroy it.
364 *
365 * @param obj Thread to be destroyed.
366 *
367 */
368static void thread_destroy(void *obj)
369{
370 thread_t *thread = (thread_t *) obj;
371
372 assert_link_not_used(&thread->rq_link);
373 assert_link_not_used(&thread->wq_link);
374
375 assert(thread->task);
376
377 ipl_t ipl = interrupts_disable();
378
379 /* Remove thread from global list. */
380 irq_spinlock_lock(&threads_lock, false);
381 odict_remove(&thread->lthreads);
382 irq_spinlock_unlock(&threads_lock, false);
383
384 /* Remove thread from task's list and accumulate accounting. */
385 irq_spinlock_lock(&thread->task->lock, false);
386
387 list_remove(&thread->th_link);
388
389 /*
390 * No other CPU has access to this thread anymore, so we don't need
391 * thread->lock for accessing thread's fields after this point.
392 */
393
394 if (!thread->uncounted) {
395 thread->task->ucycles += thread->ucycles;
396 thread->task->kcycles += thread->kcycles;
397 }
398
399 irq_spinlock_unlock(&thread->task->lock, false);
400
401 assert((thread->state == Exiting) || (thread->state == Lingering));
402
403 /* Clear cpu->fpu_owner if set to this thread. */
404#ifdef CONFIG_FPU_LAZY
405 if (thread->cpu) {
406 /*
407 * We need to lock for this because the old CPU can concurrently try
408 * to dump this thread's FPU state, in which case we need to wait for
409 * it to finish. An atomic compare-and-swap wouldn't be enough.
410 */
411 irq_spinlock_lock(&thread->cpu->fpu_lock, false);
412
413 thread_t *owner = atomic_load_explicit(&thread->cpu->fpu_owner,
414 memory_order_relaxed);
415
416 if (owner == thread) {
417 atomic_store_explicit(&thread->cpu->fpu_owner, NULL,
418 memory_order_relaxed);
419 }
420
421 irq_spinlock_unlock(&thread->cpu->fpu_lock, false);
422 }
423#endif
424
425 interrupts_restore(ipl);
426
427 /*
428 * Drop the reference to the containing task.
429 */
430 task_release(thread->task);
431 thread->task = NULL;
432
433 slab_free(thread_cache, thread);
434}
435
436void thread_put(thread_t *thread)
437{
438 if (refcount_down(&thread->refcount)) {
439 thread_destroy(thread);
440 }
441}
442
443/** Make the thread visible to the system.
444 *
445 * Attach the thread structure to the current task and make it visible in the
446 * threads_tree.
447 *
448 * @param t Thread to be attached to the task.
449 * @param task Task to which the thread is to be attached.
450 *
451 */
452void thread_attach(thread_t *thread, task_t *task)
453{
454 ipl_t ipl = interrupts_disable();
455
456 /*
457 * Attach to the specified task.
458 */
459 irq_spinlock_lock(&task->lock, false);
460
461 /* Hold a reference to the task. */
462 task_hold(task);
463
464 /* Must not count kbox thread into lifecount */
465 if (thread->uspace)
466 atomic_inc(&task->lifecount);
467
468 list_append(&thread->th_link, &task->threads);
469
470 irq_spinlock_unlock(&task->lock, false);
471
472 /*
473 * Register this thread in the system-wide dictionary.
474 */
475 irq_spinlock_lock(&threads_lock, false);
476 odict_insert(&thread->lthreads, &threads, NULL);
477 irq_spinlock_unlock(&threads_lock, false);
478
479 interrupts_restore(ipl);
480}
481
482/** Terminate thread.
483 *
484 * End current thread execution and switch it to the exiting state.
485 * All pending timeouts are executed.
486 *
487 */
488void thread_exit(void)
489{
490 if (THREAD->uspace) {
491#ifdef CONFIG_UDEBUG
492 /* Generate udebug THREAD_E event */
493 udebug_thread_e_event();
494
495 /*
496 * This thread will not execute any code or system calls from
497 * now on.
498 */
499 udebug_stoppable_begin();
500#endif
501 if (atomic_predec(&TASK->lifecount) == 0) {
502 /*
503 * We are the last userspace thread in the task that
504 * still has not exited. With the exception of the
505 * moment the task was created, new userspace threads
506 * can only be created by threads of the same task.
507 * We are safe to perform cleanup.
508 *
509 */
510 ipc_cleanup();
511 sys_waitq_task_cleanup();
512 LOG("Cleanup of task %" PRIu64 " completed.", TASK->taskid);
513 }
514 }
515
516 scheduler_enter(Exiting);
517 unreachable();
518}
519
520/** Interrupts an existing thread so that it may exit as soon as possible.
521 *
522 * Threads that are blocked waiting for a synchronization primitive
523 * are woken up with a return code of EINTR if the
524 * blocking call was interruptable. See waitq_sleep_timeout().
525 *
526 * Interrupted threads automatically exit when returning back to user space.
527 *
528 * @param thread A valid thread object.
529 */
530void thread_interrupt(thread_t *thread)
531{
532 assert(thread != NULL);
533 thread->interrupted = true;
534 thread_wakeup(thread);
535}
536
537/** Prepare for putting the thread to sleep.
538 *
539 * @returns whether the thread is currently terminating. If THREAD_OK
540 * is returned, the thread is guaranteed to be woken up instantly if the thread
541 * is terminated at any time between this function's return and
542 * thread_wait_finish(). If THREAD_TERMINATING is returned, the thread can still
543 * go to sleep, but doing so will delay termination.
544 */
545thread_termination_state_t thread_wait_start(void)
546{
547 assert(THREAD != NULL);
548
549 /*
550 * This is an exchange rather than a store so that we can use the acquire
551 * semantics, which is needed to ensure that code after this operation sees
552 * memory ops made before thread_wakeup() in other thread, if that wakeup
553 * was reset by this operation.
554 *
555 * In particular, we need this to ensure we can't miss the thread being
556 * terminated concurrently with a synchronization primitive preparing to
557 * sleep.
558 */
559 (void) atomic_exchange_explicit(&THREAD->sleep_state, SLEEP_INITIAL,
560 memory_order_acquire);
561
562 return THREAD->interrupted ? THREAD_TERMINATING : THREAD_OK;
563}
564
565static void thread_wait_timeout_callback(void *arg)
566{
567 thread_wakeup(arg);
568}
569
570/**
571 * Suspends this thread's execution until thread_wakeup() is called on it,
572 * or deadline is reached.
573 *
574 * The way this would normally be used is that the current thread call
575 * thread_wait_start(), and if interruption has not been signaled, stores
576 * a reference to itself in a synchronized structure (such as waitq).
577 * After that, it releases any spinlocks it might hold and calls this function.
578 *
579 * The thread doing the wakeup will acquire the thread's reference from said
580 * synchronized structure and calls thread_wakeup() on it.
581 *
582 * Notably, there can be more than one thread performing wakeup.
583 * The number of performed calls to thread_wakeup(), or their relative
584 * ordering with thread_wait_finish(), does not matter. However, calls to
585 * thread_wakeup() are expected to be synchronized with thread_wait_start()
586 * with which they are associated, otherwise wakeups may be missed.
587 * However, the operation of thread_wakeup() is defined at any time,
588 * synchronization notwithstanding (in the sense of C un/defined behavior),
589 * and is in fact used to interrupt waiting threads by external events.
590 * The waiting thread must operate correctly in face of spurious wakeups,
591 * and clean up its reference in the synchronization structure if necessary.
592 *
593 * Returns THREAD_WAIT_TIMEOUT if timeout fired, which is a necessary condition
594 * for it to have been waken up by the timeout, but the caller must assume
595 * that proper wakeups, timeouts and interrupts may occur concurrently, so
596 * the fact timeout has been registered does not necessarily mean the thread
597 * has not been woken up or interrupted.
598 */
599thread_wait_result_t thread_wait_finish(deadline_t deadline)
600{
601 assert(THREAD != NULL);
602
603 timeout_t timeout;
604
605 /* Extra check to avoid going to scheduler if we don't need to. */
606 if (atomic_load_explicit(&THREAD->sleep_state, memory_order_acquire) !=
607 SLEEP_INITIAL)
608 return THREAD_WAIT_SUCCESS;
609
610 if (deadline != DEADLINE_NEVER) {
611 timeout_initialize(&timeout);
612 timeout_register_deadline(&timeout, deadline,
613 thread_wait_timeout_callback, THREAD);
614 }
615
616 scheduler_enter(Sleeping);
617
618 if (deadline != DEADLINE_NEVER && !timeout_unregister(&timeout)) {
619 return THREAD_WAIT_TIMEOUT;
620 } else {
621 return THREAD_WAIT_SUCCESS;
622 }
623}
624
625void thread_wakeup(thread_t *thread)
626{
627 assert(thread != NULL);
628
629 int state = atomic_exchange_explicit(&thread->sleep_state, SLEEP_WOKE,
630 memory_order_acq_rel);
631
632 if (state == SLEEP_ASLEEP) {
633 /*
634 * Only one thread gets to do this.
635 * The reference consumed here is the reference implicitly passed to
636 * the waking thread by the sleeper in thread_wait_finish().
637 */
638 thread_ready(thread);
639 }
640}
641
642/** Prevent the current thread from being migrated to another processor. */
643void thread_migration_disable(void)
644{
645 assert(THREAD);
646
647 THREAD->nomigrate++;
648}
649
650/** Allow the current thread to be migrated to another processor. */
651void thread_migration_enable(void)
652{
653 assert(THREAD);
654 assert(THREAD->nomigrate > 0);
655
656 if (THREAD->nomigrate > 0)
657 THREAD->nomigrate--;
658}
659
660/** Thread sleep
661 *
662 * Suspend execution of the current thread.
663 *
664 * @param sec Number of seconds to sleep.
665 *
666 */
667void thread_sleep(uint32_t sec)
668{
669 /*
670 * Sleep in 1000 second steps to support
671 * full argument range
672 */
673 while (sec > 0) {
674 uint32_t period = (sec > 1000) ? 1000 : sec;
675
676 thread_usleep(period * 1000000);
677 sec -= period;
678 }
679}
680
681errno_t thread_join(thread_t *thread)
682{
683 return thread_join_timeout(thread, SYNCH_NO_TIMEOUT, SYNCH_FLAGS_NONE);
684}
685
686/** Wait for another thread to exit.
687 * This function does not destroy the thread. Reference counting handles that.
688 *
689 * @param thread Thread to join on exit.
690 * @param usec Timeout in microseconds.
691 * @param flags Mode of operation.
692 *
693 * @return An error code from errno.h or an error code from synch.h.
694 *
695 */
696errno_t thread_join_timeout(thread_t *thread, uint32_t usec, unsigned int flags)
697{
698 if (thread == THREAD)
699 return EINVAL;
700
701 irq_spinlock_lock(&thread->lock, true);
702 state_t state = thread->state;
703 irq_spinlock_unlock(&thread->lock, true);
704
705 if (state == Exiting) {
706 return EOK;
707 } else {
708 return _waitq_sleep_timeout(&thread->join_wq, usec, flags);
709 }
710}
711
712/** Thread usleep
713 *
714 * Suspend execution of the current thread.
715 *
716 * @param usec Number of microseconds to sleep.
717 *
718 */
719void thread_usleep(uint32_t usec)
720{
721 waitq_t wq;
722
723 waitq_initialize(&wq);
724
725 (void) waitq_sleep_timeout(&wq, usec);
726}
727
728/** Allow other threads to run. */
729void thread_yield(void)
730{
731 assert(THREAD != NULL);
732 scheduler_enter(Running);
733}
734
735static void thread_print(thread_t *thread, bool additional)
736{
737 uint64_t ucycles, kcycles;
738 char usuffix, ksuffix;
739 order_suffix(thread->ucycles, &ucycles, &usuffix);
740 order_suffix(thread->kcycles, &kcycles, &ksuffix);
741
742 char *name;
743 if (str_cmp(thread->name, "uinit") == 0)
744 name = thread->task->name;
745 else
746 name = thread->name;
747
748 if (additional)
749 printf("%-8" PRIu64 " %p %p %9" PRIu64 "%c %9" PRIu64 "%c ",
750 thread->tid, thread->thread_code, thread->kstack,
751 ucycles, usuffix, kcycles, ksuffix);
752 else
753 printf("%-8" PRIu64 " %-14s %p %-8s %p %-5" PRIu32 "\n",
754 thread->tid, name, thread, thread_states[thread->state],
755 thread->task, thread->task->container);
756
757 if (additional) {
758 if (thread->cpu)
759 printf("%-5u", thread->cpu->id);
760 else
761 printf("none ");
762
763 if (thread->state == Sleeping) {
764 printf(" %p", thread->sleep_queue);
765 }
766
767 printf("\n");
768 }
769}
770
771/** Print list of threads debug info
772 *
773 * @param additional Print additional information.
774 *
775 */
776void thread_print_list(bool additional)
777{
778 thread_t *thread;
779
780 /* Accessing system-wide threads list through thread_first()/thread_next(). */
781 irq_spinlock_lock(&threads_lock, true);
782
783 if (sizeof(void *) <= 4) {
784 if (additional)
785 printf("[id ] [code ] [stack ] [ucycles ] [kcycles ]"
786 " [cpu] [waitqueue]\n");
787 else
788 printf("[id ] [name ] [address ] [state ] [task ]"
789 " [ctn]\n");
790 } else {
791 if (additional) {
792 printf("[id ] [code ] [stack ] [ucycles ] [kcycles ]"
793 " [cpu] [waitqueue ]\n");
794 } else
795 printf("[id ] [name ] [address ] [state ]"
796 " [task ] [ctn]\n");
797 }
798
799 thread = thread_first();
800 while (thread != NULL) {
801 thread_print(thread, additional);
802 thread = thread_next(thread);
803 }
804
805 irq_spinlock_unlock(&threads_lock, true);
806}
807
808static bool thread_exists(thread_t *thread)
809{
810 odlink_t *odlink = odict_find_eq(&threads, thread, NULL);
811 return odlink != NULL;
812}
813
814/** Check whether the thread exists, and if so, return a reference to it.
815 */
816thread_t *thread_try_get(thread_t *thread)
817{
818 irq_spinlock_lock(&threads_lock, true);
819
820 if (thread_exists(thread)) {
821 /* Try to strengthen the reference. */
822 thread = thread_try_ref(thread);
823 } else {
824 thread = NULL;
825 }
826
827 irq_spinlock_unlock(&threads_lock, true);
828
829 return thread;
830}
831
832/** Update accounting of current thread.
833 *
834 * Note that thread_lock on THREAD must be already held and
835 * interrupts must be already disabled.
836 *
837 * @param user True to update user accounting, false for kernel.
838 *
839 */
840void thread_update_accounting(bool user)
841{
842 uint64_t time = get_cycle();
843
844 assert(interrupts_disabled());
845 assert(irq_spinlock_locked(&THREAD->lock));
846
847 if (user)
848 THREAD->ucycles += time - THREAD->last_cycle;
849 else
850 THREAD->kcycles += time - THREAD->last_cycle;
851
852 THREAD->last_cycle = time;
853}
854
855/** Find thread structure corresponding to thread ID.
856 *
857 * The threads_lock must be already held by the caller of this function and
858 * interrupts must be disabled.
859 *
860 * The returned reference is weak.
861 * If the caller needs to keep it, thread_try_ref() must be used to upgrade
862 * to a strong reference _before_ threads_lock is released.
863 *
864 * @param id Thread ID.
865 *
866 * @return Thread structure address or NULL if there is no such thread ID.
867 *
868 */
869thread_t *thread_find_by_id(thread_id_t thread_id)
870{
871 thread_t *thread;
872
873 assert(interrupts_disabled());
874 assert(irq_spinlock_locked(&threads_lock));
875
876 thread = thread_first();
877 while (thread != NULL) {
878 if (thread->tid == thread_id)
879 return thread;
880
881 thread = thread_next(thread);
882 }
883
884 return NULL;
885}
886
887/** Get count of threads.
888 *
889 * @return Number of threads in the system
890 */
891size_t thread_count(void)
892{
893 assert(interrupts_disabled());
894 assert(irq_spinlock_locked(&threads_lock));
895
896 return odict_count(&threads);
897}
898
899/** Get first thread.
900 *
901 * @return Pointer to first thread or @c NULL if there are none.
902 */
903thread_t *thread_first(void)
904{
905 odlink_t *odlink;
906
907 assert(interrupts_disabled());
908 assert(irq_spinlock_locked(&threads_lock));
909
910 odlink = odict_first(&threads);
911 if (odlink == NULL)
912 return NULL;
913
914 return odict_get_instance(odlink, thread_t, lthreads);
915}
916
917/** Get next thread.
918 *
919 * @param cur Current thread
920 * @return Pointer to next thread or @c NULL if there are no more threads.
921 */
922thread_t *thread_next(thread_t *cur)
923{
924 odlink_t *odlink;
925
926 assert(interrupts_disabled());
927 assert(irq_spinlock_locked(&threads_lock));
928
929 odlink = odict_next(&cur->lthreads, &threads);
930 if (odlink == NULL)
931 return NULL;
932
933 return odict_get_instance(odlink, thread_t, lthreads);
934}
935
936#ifdef CONFIG_UDEBUG
937
938void thread_stack_trace(thread_id_t thread_id)
939{
940 irq_spinlock_lock(&threads_lock, true);
941 thread_t *thread = thread_try_ref(thread_find_by_id(thread_id));
942 irq_spinlock_unlock(&threads_lock, true);
943
944 if (thread == NULL) {
945 printf("No such thread.\n");
946 return;
947 }
948
949 /*
950 * Schedule a stack trace to be printed
951 * just before the thread is scheduled next.
952 *
953 * If the thread is sleeping then try to interrupt
954 * the sleep. Any request for printing an uspace stack
955 * trace from within the kernel should be always
956 * considered a last resort debugging means, therefore
957 * forcing the thread's sleep to be interrupted
958 * is probably justifiable.
959 */
960
961 irq_spinlock_lock(&thread->lock, true);
962
963 bool sleeping = false;
964 istate_t *istate = thread->udebug.uspace_state;
965 if (istate != NULL) {
966 printf("Scheduling thread stack trace.\n");
967 thread->btrace = true;
968 if (thread->state == Sleeping)
969 sleeping = true;
970 } else
971 printf("Thread interrupt state not available.\n");
972
973 irq_spinlock_unlock(&thread->lock, true);
974
975 if (sleeping)
976 thread_wakeup(thread);
977
978 thread_put(thread);
979}
980
981#endif /* CONFIG_UDEBUG */
982
983/** Get key function for the @c threads ordered dictionary.
984 *
985 * @param odlink Link
986 * @return Pointer to thread structure cast as 'void *'
987 */
988static void *threads_getkey(odlink_t *odlink)
989{
990 thread_t *thread = odict_get_instance(odlink, thread_t, lthreads);
991 return (void *) thread;
992}
993
994/** Key comparison function for the @c threads ordered dictionary.
995 *
996 * @param a Pointer to thread A
997 * @param b Pointer to thread B
998 * @return -1, 0, 1 iff pointer to A is less than, equal to, greater than B
999 */
1000static int threads_cmp(void *a, void *b)
1001{
1002 if (a > b)
1003 return -1;
1004 else if (a == b)
1005 return 0;
1006 else
1007 return +1;
1008}
1009
1010/** Process syscall to create new thread.
1011 *
1012 */
1013sys_errno_t sys_thread_create(uspace_ptr_uspace_arg_t uspace_uarg, uspace_ptr_char uspace_name,
1014 size_t name_len, uspace_ptr_thread_id_t uspace_thread_id)
1015{
1016 if (name_len > THREAD_NAME_BUFLEN - 1)
1017 name_len = THREAD_NAME_BUFLEN - 1;
1018
1019 char namebuf[THREAD_NAME_BUFLEN];
1020 errno_t rc = copy_from_uspace(namebuf, uspace_name, name_len);
1021 if (rc != EOK)
1022 return (sys_errno_t) rc;
1023
1024 namebuf[name_len] = 0;
1025
1026 /*
1027 * In case of failure, kernel_uarg will be deallocated in this function.
1028 * In case of success, kernel_uarg will be freed in uinit().
1029 */
1030 uspace_arg_t *kernel_uarg =
1031 (uspace_arg_t *) malloc(sizeof(uspace_arg_t));
1032 if (!kernel_uarg)
1033 return (sys_errno_t) ENOMEM;
1034
1035 rc = copy_from_uspace(kernel_uarg, uspace_uarg, sizeof(uspace_arg_t));
1036 if (rc != EOK) {
1037 free(kernel_uarg);
1038 return (sys_errno_t) rc;
1039 }
1040
1041 thread_t *thread = thread_create(uinit, kernel_uarg, TASK,
1042 THREAD_FLAG_USPACE | THREAD_FLAG_NOATTACH, namebuf);
1043 if (thread) {
1044 if (uspace_thread_id) {
1045 rc = copy_to_uspace(uspace_thread_id, &thread->tid,
1046 sizeof(thread->tid));
1047 if (rc != EOK) {
1048 /*
1049 * We have encountered a failure, but the thread
1050 * has already been created. We need to undo its
1051 * creation now.
1052 */
1053
1054 /*
1055 * The new thread structure is initialized, but
1056 * is still not visible to the system.
1057 * We can safely deallocate it.
1058 */
1059 slab_free(thread_cache, thread);
1060 free(kernel_uarg);
1061
1062 return (sys_errno_t) rc;
1063 }
1064 }
1065
1066#ifdef CONFIG_UDEBUG
1067 /*
1068 * Generate udebug THREAD_B event and attach the thread.
1069 * This must be done atomically (with the debug locks held),
1070 * otherwise we would either miss some thread or receive
1071 * THREAD_B events for threads that already existed
1072 * and could be detected with THREAD_READ before.
1073 */
1074 udebug_thread_b_event_attach(thread, TASK);
1075#else
1076 thread_attach(thread, TASK);
1077#endif
1078 thread_ready(thread);
1079
1080 return 0;
1081 } else
1082 free(kernel_uarg);
1083
1084 return (sys_errno_t) ENOMEM;
1085}
1086
1087/** Process syscall to terminate thread.
1088 *
1089 */
1090sys_errno_t sys_thread_exit(int uspace_status)
1091{
1092 thread_exit();
1093}
1094
1095/** Syscall for getting TID.
1096 *
1097 * @param uspace_thread_id Userspace address of 8-byte buffer where to store
1098 * current thread ID.
1099 *
1100 * @return 0 on success or an error code from @ref errno.h.
1101 *
1102 */
1103sys_errno_t sys_thread_get_id(uspace_ptr_thread_id_t uspace_thread_id)
1104{
1105 /*
1106 * No need to acquire lock on THREAD because tid
1107 * remains constant for the lifespan of the thread.
1108 *
1109 */
1110 return (sys_errno_t) copy_to_uspace(uspace_thread_id, &THREAD->tid,
1111 sizeof(THREAD->tid));
1112}
1113
1114/** Syscall wrapper for sleeping. */
1115sys_errno_t sys_thread_usleep(uint32_t usec)
1116{
1117 thread_usleep(usec);
1118 return 0;
1119}
1120
1121sys_errno_t sys_thread_udelay(uint32_t usec)
1122{
1123 delay(usec);
1124 return 0;
1125}
1126
1127/** @}
1128 */
Note: See TracBrowser for help on using the repository browser.