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

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

Make thread_t reference counted

This simplifies interaction between various locks and thread
lifespan, which simplifies things. For example, threads_lock can
now simply be a mutex protecting the global it was made for, and
nothing more.

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