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

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

Make thread cycle statistics atomic

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