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

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

Simplify timeout handling

Since timeout_unregister() now waits for the handler to complete,
we can get rid of some of the bookkeeping in waitq and thread code.
We can also turn timeout_t into a local variable instead of
keeping it around in thread_t.

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