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

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

Check cpu_t::fpu_owner directly instead of thread_t::fpu_context_engaged

This results in net reduction in locking.

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