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

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

Add functions context_create(), context_replace() and context_swap()

and use them where appropriate, removing context_save() in the process.
Much like in userspace, context_swap() maintains natural control flow
as opposed to context_save()'s return-twice mechanic.

Beyond that, in the future, context_replace() and context_swap()
can be implemented more efficiently than the context_save()/
context_restore() pair. As of now, the original implementation is
retained.

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