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

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

Remove unnecessary thread_t::wired

There's already thread_t::nomigrate doing the same thing

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