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

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

Remove unnecessary function

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