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

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

Reimplement waitq using thread_wait/wakeup

This adds a few functions to the thread API which can be
summarized as "stop running until woken up by others".
The ordering and context-switching concerns are thus yeeted
to this abstraction and waitq only deals with maintaining
the queues. Overall, this makes the control flow in waitq
much easier to navigate.

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