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

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

Reorganize locking in thread_destroy()

  • Property mode set to 100644
File size: 25.0 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 obj Thread to be destroyed.
401 *
402 */
403static void thread_destroy(void *obj)
404{
405 thread_t *thread = (thread_t *) obj;
406
407 assert_link_not_used(&thread->rq_link);
408 assert_link_not_used(&thread->wq_link);
409
410 assert(thread->task);
411
412 ipl_t ipl = interrupts_disable();
413
414 /* Remove thread from task's list. */
415 irq_spinlock_lock(&thread->task->lock, false);
416 list_remove(&thread->th_link);
417 irq_spinlock_unlock(&thread->task->lock, false);
418
419 /* Remove thread from global list. */
420 irq_spinlock_lock(&threads_lock, false);
421 odict_remove(&thread->lthreads);
422 irq_spinlock_unlock(&threads_lock, false);
423
424 /* Clear cpu->fpu_owner if set to this thread. */
425 irq_spinlock_lock(&thread->lock, false);
426
427 assert((thread->state == Exiting) || (thread->state == Lingering));
428 assert(thread->cpu);
429
430 irq_spinlock_lock(&thread->cpu->lock, false);
431 if (thread->cpu->fpu_owner == thread)
432 thread->cpu->fpu_owner = NULL;
433 irq_spinlock_unlock(&thread->cpu->lock, false);
434
435 irq_spinlock_unlock(&thread->lock, false);
436
437 interrupts_restore(ipl);
438
439 /*
440 * Drop the reference to the containing task.
441 */
442 task_release(thread->task);
443 thread->task = NULL;
444
445 slab_free(thread_cache, thread);
446}
447
448void thread_put(thread_t *thread)
449{
450 if (refcount_down(&thread->refcount)) {
451 thread_destroy(thread);
452 }
453}
454
455/** Make the thread visible to the system.
456 *
457 * Attach the thread structure to the current task and make it visible in the
458 * threads_tree.
459 *
460 * @param t Thread to be attached to the task.
461 * @param task Task to which the thread is to be attached.
462 *
463 */
464void thread_attach(thread_t *thread, task_t *task)
465{
466 ipl_t ipl = interrupts_disable();
467
468 /*
469 * Attach to the specified task.
470 */
471 irq_spinlock_lock(&task->lock, false);
472
473 /* Hold a reference to the task. */
474 task_hold(task);
475
476 /* Must not count kbox thread into lifecount */
477 if (thread->uspace)
478 atomic_inc(&task->lifecount);
479
480 list_append(&thread->th_link, &task->threads);
481
482 irq_spinlock_unlock(&task->lock, false);
483
484 /*
485 * Register this thread in the system-wide dictionary.
486 */
487 irq_spinlock_lock(&threads_lock, false);
488 odict_insert(&thread->lthreads, &threads, NULL);
489 irq_spinlock_unlock(&threads_lock, false);
490
491 interrupts_restore(ipl);
492}
493
494/** Terminate thread.
495 *
496 * End current thread execution and switch it to the exiting state.
497 * All pending timeouts are executed.
498 *
499 */
500void thread_exit(void)
501{
502 if (THREAD->uspace) {
503#ifdef CONFIG_UDEBUG
504 /* Generate udebug THREAD_E event */
505 udebug_thread_e_event();
506
507 /*
508 * This thread will not execute any code or system calls from
509 * now on.
510 */
511 udebug_stoppable_begin();
512#endif
513 if (atomic_predec(&TASK->lifecount) == 0) {
514 /*
515 * We are the last userspace thread in the task that
516 * still has not exited. With the exception of the
517 * moment the task was created, new userspace threads
518 * can only be created by threads of the same task.
519 * We are safe to perform cleanup.
520 *
521 */
522 ipc_cleanup();
523 sys_waitq_task_cleanup();
524 LOG("Cleanup of task %" PRIu64 " completed.", TASK->taskid);
525 }
526 }
527
528 irq_spinlock_lock(&THREAD->lock, true);
529 THREAD->state = Exiting;
530 irq_spinlock_unlock(&THREAD->lock, true);
531
532 scheduler();
533
534 panic("should never be reached");
535}
536
537/** Interrupts an existing thread so that it may exit as soon as possible.
538 *
539 * Threads that are blocked waiting for a synchronization primitive
540 * are woken up with a return code of EINTR if the
541 * blocking call was interruptable. See waitq_sleep_timeout().
542 *
543 * Interrupted threads automatically exit when returning back to user space.
544 *
545 * @param thread A valid thread object.
546 */
547void thread_interrupt(thread_t *thread, bool irq_dis)
548{
549 assert(thread != NULL);
550
551 irq_spinlock_lock(&thread->lock, irq_dis);
552
553 thread->interrupted = true;
554 bool sleeping = (thread->state == Sleeping);
555
556 irq_spinlock_unlock(&thread->lock, irq_dis);
557
558 if (sleeping)
559 waitq_interrupt_sleep(thread);
560
561 thread_put(thread);
562}
563
564/** Prevent the current thread from being migrated to another processor. */
565void thread_migration_disable(void)
566{
567 assert(THREAD);
568
569 THREAD->nomigrate++;
570}
571
572/** Allow the current thread to be migrated to another processor. */
573void thread_migration_enable(void)
574{
575 assert(THREAD);
576 assert(THREAD->nomigrate > 0);
577
578 if (THREAD->nomigrate > 0)
579 THREAD->nomigrate--;
580}
581
582/** Thread sleep
583 *
584 * Suspend execution of the current thread.
585 *
586 * @param sec Number of seconds to sleep.
587 *
588 */
589void thread_sleep(uint32_t sec)
590{
591 /*
592 * Sleep in 1000 second steps to support
593 * full argument range
594 */
595 while (sec > 0) {
596 uint32_t period = (sec > 1000) ? 1000 : sec;
597
598 thread_usleep(period * 1000000);
599 sec -= period;
600 }
601}
602
603errno_t thread_join(thread_t *thread)
604{
605 return thread_join_timeout(thread, SYNCH_NO_TIMEOUT, SYNCH_FLAGS_NONE);
606}
607
608/** Wait for another thread to exit.
609 * This function does not destroy the thread. Reference counting handles that.
610 *
611 * @param thread Thread to join on exit.
612 * @param usec Timeout in microseconds.
613 * @param flags Mode of operation.
614 *
615 * @return An error code from errno.h or an error code from synch.h.
616 *
617 */
618errno_t thread_join_timeout(thread_t *thread, uint32_t usec, unsigned int flags)
619{
620 if (thread == THREAD)
621 return EINVAL;
622
623 irq_spinlock_lock(&thread->lock, true);
624 state_t state = thread->state;
625 irq_spinlock_unlock(&thread->lock, true);
626
627 if (state == Exiting) {
628 return EOK;
629 } else {
630 return waitq_sleep_timeout(&thread->join_wq, usec,
631 SYNCH_FLAGS_NON_BLOCKING, NULL);
632 }
633}
634
635/** Thread usleep
636 *
637 * Suspend execution of the current thread.
638 *
639 * @param usec Number of microseconds to sleep.
640 *
641 */
642void thread_usleep(uint32_t usec)
643{
644 waitq_t wq;
645
646 waitq_initialize(&wq);
647
648 (void) waitq_sleep_timeout(&wq, usec, SYNCH_FLAGS_NON_BLOCKING, NULL);
649}
650
651static void thread_print(thread_t *thread, bool additional)
652{
653 uint64_t ucycles, kcycles;
654 char usuffix, ksuffix;
655 order_suffix(thread->ucycles, &ucycles, &usuffix);
656 order_suffix(thread->kcycles, &kcycles, &ksuffix);
657
658 char *name;
659 if (str_cmp(thread->name, "uinit") == 0)
660 name = thread->task->name;
661 else
662 name = thread->name;
663
664 if (additional)
665 printf("%-8" PRIu64 " %p %p %9" PRIu64 "%c %9" PRIu64 "%c ",
666 thread->tid, thread->thread_code, thread->kstack,
667 ucycles, usuffix, kcycles, ksuffix);
668 else
669 printf("%-8" PRIu64 " %-14s %p %-8s %p %-5" PRIu32 "\n",
670 thread->tid, name, thread, thread_states[thread->state],
671 thread->task, thread->task->container);
672
673 if (additional) {
674 if (thread->cpu)
675 printf("%-5u", thread->cpu->id);
676 else
677 printf("none ");
678
679 if (thread->state == Sleeping) {
680 printf(" %p", thread->sleep_queue);
681 }
682
683 printf("\n");
684 }
685}
686
687/** Print list of threads debug info
688 *
689 * @param additional Print additional information.
690 *
691 */
692void thread_print_list(bool additional)
693{
694 thread_t *thread;
695
696 /* Accessing system-wide threads list through thread_first()/thread_next(). */
697 irq_spinlock_lock(&threads_lock, true);
698
699 if (sizeof(void *) <= 4) {
700 if (additional)
701 printf("[id ] [code ] [stack ] [ucycles ] [kcycles ]"
702 " [cpu] [waitqueue]\n");
703 else
704 printf("[id ] [name ] [address ] [state ] [task ]"
705 " [ctn]\n");
706 } else {
707 if (additional) {
708 printf("[id ] [code ] [stack ] [ucycles ] [kcycles ]"
709 " [cpu] [waitqueue ]\n");
710 } else
711 printf("[id ] [name ] [address ] [state ]"
712 " [task ] [ctn]\n");
713 }
714
715 thread = thread_first();
716 while (thread != NULL) {
717 thread_print(thread, additional);
718 thread = thread_next(thread);
719 }
720
721 irq_spinlock_unlock(&threads_lock, true);
722}
723
724static bool thread_exists(thread_t *thread)
725{
726 odlink_t *odlink = odict_find_eq(&threads, thread, NULL);
727 return odlink != NULL;
728}
729
730/** Check whether the thread exists, and if so, return a reference to it.
731 */
732thread_t *thread_try_get(thread_t *thread)
733{
734 irq_spinlock_lock(&threads_lock, true);
735
736 if (thread_exists(thread)) {
737 /* Try to strengthen the reference. */
738 thread = thread_try_ref(thread);
739 } else {
740 thread = NULL;
741 }
742
743 irq_spinlock_unlock(&threads_lock, true);
744
745 return thread;
746}
747
748/** Update accounting of current thread.
749 *
750 * Note that thread_lock on THREAD must be already held and
751 * interrupts must be already disabled.
752 *
753 * @param user True to update user accounting, false for kernel.
754 *
755 */
756void thread_update_accounting(bool user)
757{
758 uint64_t time = get_cycle();
759
760 assert(interrupts_disabled());
761 assert(irq_spinlock_locked(&THREAD->lock));
762
763 if (user)
764 THREAD->ucycles += time - THREAD->last_cycle;
765 else
766 THREAD->kcycles += time - THREAD->last_cycle;
767
768 THREAD->last_cycle = time;
769}
770
771/** Find thread structure corresponding to thread ID.
772 *
773 * The threads_lock must be already held by the caller of this function and
774 * interrupts must be disabled.
775 *
776 * The returned reference is weak.
777 * If the caller needs to keep it, thread_try_ref() must be used to upgrade
778 * to a strong reference _before_ threads_lock is released.
779 *
780 * @param id Thread ID.
781 *
782 * @return Thread structure address or NULL if there is no such thread ID.
783 *
784 */
785thread_t *thread_find_by_id(thread_id_t thread_id)
786{
787 thread_t *thread;
788
789 assert(interrupts_disabled());
790 assert(irq_spinlock_locked(&threads_lock));
791
792 thread = thread_first();
793 while (thread != NULL) {
794 if (thread->tid == thread_id)
795 return thread;
796
797 thread = thread_next(thread);
798 }
799
800 return NULL;
801}
802
803/** Get count of threads.
804 *
805 * @return Number of threads in the system
806 */
807size_t thread_count(void)
808{
809 assert(interrupts_disabled());
810 assert(irq_spinlock_locked(&threads_lock));
811
812 return odict_count(&threads);
813}
814
815/** Get first thread.
816 *
817 * @return Pointer to first thread or @c NULL if there are none.
818 */
819thread_t *thread_first(void)
820{
821 odlink_t *odlink;
822
823 assert(interrupts_disabled());
824 assert(irq_spinlock_locked(&threads_lock));
825
826 odlink = odict_first(&threads);
827 if (odlink == NULL)
828 return NULL;
829
830 return odict_get_instance(odlink, thread_t, lthreads);
831}
832
833/** Get next thread.
834 *
835 * @param cur Current thread
836 * @return Pointer to next thread or @c NULL if there are no more threads.
837 */
838thread_t *thread_next(thread_t *cur)
839{
840 odlink_t *odlink;
841
842 assert(interrupts_disabled());
843 assert(irq_spinlock_locked(&threads_lock));
844
845 odlink = odict_next(&cur->lthreads, &threads);
846 if (odlink == NULL)
847 return NULL;
848
849 return odict_get_instance(odlink, thread_t, lthreads);
850}
851
852#ifdef CONFIG_UDEBUG
853
854void thread_stack_trace(thread_id_t thread_id)
855{
856 irq_spinlock_lock(&threads_lock, true);
857 thread_t *thread = thread_try_ref(thread_find_by_id(thread_id));
858 irq_spinlock_unlock(&threads_lock, true);
859
860 if (thread == NULL) {
861 printf("No such thread.\n");
862 return;
863 }
864
865 /*
866 * Schedule a stack trace to be printed
867 * just before the thread is scheduled next.
868 *
869 * If the thread is sleeping then try to interrupt
870 * the sleep. Any request for printing an uspace stack
871 * trace from within the kernel should be always
872 * considered a last resort debugging means, therefore
873 * forcing the thread's sleep to be interrupted
874 * is probably justifiable.
875 */
876
877 irq_spinlock_lock(&thread->lock, true);
878
879 bool sleeping = false;
880 istate_t *istate = thread->udebug.uspace_state;
881 if (istate != NULL) {
882 printf("Scheduling thread stack trace.\n");
883 thread->btrace = true;
884 if (thread->state == Sleeping)
885 sleeping = true;
886 } else
887 printf("Thread interrupt state not available.\n");
888
889 irq_spinlock_unlock(&thread->lock, true);
890
891 if (sleeping)
892 waitq_interrupt_sleep(thread);
893
894 thread_put(thread);
895}
896
897#endif /* CONFIG_UDEBUG */
898
899/** Get key function for the @c threads ordered dictionary.
900 *
901 * @param odlink Link
902 * @return Pointer to thread structure cast as 'void *'
903 */
904static void *threads_getkey(odlink_t *odlink)
905{
906 thread_t *thread = odict_get_instance(odlink, thread_t, lthreads);
907 return (void *) thread;
908}
909
910/** Key comparison function for the @c threads ordered dictionary.
911 *
912 * @param a Pointer to thread A
913 * @param b Pointer to thread B
914 * @return -1, 0, 1 iff pointer to A is less than, equal to, greater than B
915 */
916static int threads_cmp(void *a, void *b)
917{
918 if (a > b)
919 return -1;
920 else if (a == b)
921 return 0;
922 else
923 return +1;
924}
925
926/** Process syscall to create new thread.
927 *
928 */
929sys_errno_t sys_thread_create(uspace_ptr_uspace_arg_t uspace_uarg, uspace_ptr_char uspace_name,
930 size_t name_len, uspace_ptr_thread_id_t uspace_thread_id)
931{
932 if (name_len > THREAD_NAME_BUFLEN - 1)
933 name_len = THREAD_NAME_BUFLEN - 1;
934
935 char namebuf[THREAD_NAME_BUFLEN];
936 errno_t rc = copy_from_uspace(namebuf, uspace_name, name_len);
937 if (rc != EOK)
938 return (sys_errno_t) rc;
939
940 namebuf[name_len] = 0;
941
942 /*
943 * In case of failure, kernel_uarg will be deallocated in this function.
944 * In case of success, kernel_uarg will be freed in uinit().
945 */
946 uspace_arg_t *kernel_uarg =
947 (uspace_arg_t *) malloc(sizeof(uspace_arg_t));
948 if (!kernel_uarg)
949 return (sys_errno_t) ENOMEM;
950
951 rc = copy_from_uspace(kernel_uarg, uspace_uarg, sizeof(uspace_arg_t));
952 if (rc != EOK) {
953 free(kernel_uarg);
954 return (sys_errno_t) rc;
955 }
956
957 thread_t *thread = thread_create(uinit, kernel_uarg, TASK,
958 THREAD_FLAG_USPACE | THREAD_FLAG_NOATTACH, namebuf);
959 if (thread) {
960 if (uspace_thread_id) {
961 rc = copy_to_uspace(uspace_thread_id, &thread->tid,
962 sizeof(thread->tid));
963 if (rc != EOK) {
964 /*
965 * We have encountered a failure, but the thread
966 * has already been created. We need to undo its
967 * creation now.
968 */
969
970 /*
971 * The new thread structure is initialized, but
972 * is still not visible to the system.
973 * We can safely deallocate it.
974 */
975 slab_free(thread_cache, thread);
976 free(kernel_uarg);
977
978 return (sys_errno_t) rc;
979 }
980 }
981
982#ifdef CONFIG_UDEBUG
983 /*
984 * Generate udebug THREAD_B event and attach the thread.
985 * This must be done atomically (with the debug locks held),
986 * otherwise we would either miss some thread or receive
987 * THREAD_B events for threads that already existed
988 * and could be detected with THREAD_READ before.
989 */
990 udebug_thread_b_event_attach(thread, TASK);
991#else
992 thread_attach(thread, TASK);
993#endif
994 thread_ready(thread);
995
996 return 0;
997 } else
998 free(kernel_uarg);
999
1000 return (sys_errno_t) ENOMEM;
1001}
1002
1003/** Process syscall to terminate thread.
1004 *
1005 */
1006sys_errno_t sys_thread_exit(int uspace_status)
1007{
1008 thread_exit();
1009}
1010
1011/** Syscall for getting TID.
1012 *
1013 * @param uspace_thread_id Userspace address of 8-byte buffer where to store
1014 * current thread ID.
1015 *
1016 * @return 0 on success or an error code from @ref errno.h.
1017 *
1018 */
1019sys_errno_t sys_thread_get_id(uspace_ptr_thread_id_t uspace_thread_id)
1020{
1021 /*
1022 * No need to acquire lock on THREAD because tid
1023 * remains constant for the lifespan of the thread.
1024 *
1025 */
1026 return (sys_errno_t) copy_to_uspace(uspace_thread_id, &THREAD->tid,
1027 sizeof(THREAD->tid));
1028}
1029
1030/** Syscall wrapper for sleeping. */
1031sys_errno_t sys_thread_usleep(uint32_t usec)
1032{
1033 thread_usleep(usec);
1034 return 0;
1035}
1036
1037sys_errno_t sys_thread_udelay(uint32_t usec)
1038{
1039 delay(usec);
1040 return 0;
1041}
1042
1043/** @}
1044 */
Note: See TracBrowser for help on using the repository browser.