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

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

Move context switch preparation to a new separate function

This puts everything that's needed before activating a new
thread into a single place, and removes one lock/unlock pair.

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