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

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since aae365bc was aae365bc, checked in by Jakub Jermar <jakub@…>, 7 years ago

Remove RCU and CHT support

  • Property mode set to 100644
File size: 26.6 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 <cpu.h>
51#include <str.h>
52#include <context.h>
53#include <adt/list.h>
54#include <adt/odict.h>
55#include <time/clock.h>
56#include <time/timeout.h>
57#include <time/delay.h>
58#include <config.h>
59#include <arch/interrupt.h>
60#include <smp/ipi.h>
61#include <arch/faddr.h>
62#include <atomic.h>
63#include <mem.h>
64#include <stdio.h>
65#include <mm/slab.h>
66#include <main/uinit.h>
67#include <syscall/copy.h>
68#include <errno.h>
69#include <debug.h>
70
71/** Thread states */
72const char *thread_states[] = {
73 "Invalid",
74 "Running",
75 "Sleeping",
76 "Ready",
77 "Entering",
78 "Exiting",
79 "Lingering"
80};
81
82/** Lock protecting the @c threads ordered dictionary .
83 *
84 * For locking rules, see declaration thereof.
85 */
86IRQ_SPINLOCK_INITIALIZE(threads_lock);
87
88/** Ordered dictionary of all threads by their address (i.e. pointer to
89 * the thread_t structure).
90 *
91 * When a thread is found in the @c threads ordered dictionary, it is
92 * guaranteed to exist as long as the @c threads_lock is held.
93 *
94 * Members are of type thread_t.
95 */
96odict_t threads;
97
98IRQ_SPINLOCK_STATIC_INITIALIZE(tidlock);
99static thread_id_t last_tid = 0;
100
101static slab_cache_t *thread_cache;
102
103#ifdef CONFIG_FPU
104slab_cache_t *fpu_context_cache;
105#endif
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#ifdef CONFIG_FPU
167#ifdef CONFIG_FPU_LAZY
168 thread->saved_fpu_context = NULL;
169#else /* CONFIG_FPU_LAZY */
170 thread->saved_fpu_context = slab_alloc(fpu_context_cache, kmflags);
171 if (!thread->saved_fpu_context)
172 return ENOMEM;
173#endif /* CONFIG_FPU_LAZY */
174#endif /* CONFIG_FPU */
175
176 /*
177 * Allocate the kernel stack from the low-memory to prevent an infinite
178 * nesting of TLB-misses when accessing the stack from the part of the
179 * TLB-miss handler written in C.
180 *
181 * Note that low-memory is safe to be used for the stack as it will be
182 * covered by the kernel identity mapping, which guarantees not to
183 * nest TLB-misses infinitely (either via some hardware mechanism or
184 * by the construciton of the assembly-language part of the TLB-miss
185 * handler).
186 *
187 * This restriction can be lifted once each architecture provides
188 * a similar guarantee, for example by locking the kernel stack
189 * in the TLB whenever it is allocated from the high-memory and the
190 * thread is being scheduled to run.
191 */
192 kmflags |= FRAME_LOWMEM;
193 kmflags &= ~FRAME_HIGHMEM;
194
195 // XXX: All kernel stacks must be aligned to STACK_SIZE,
196 // see get_stack_base().
197
198 uintptr_t stack_phys =
199 frame_alloc(STACK_FRAMES, kmflags, STACK_SIZE - 1);
200 if (!stack_phys) {
201#ifdef CONFIG_FPU
202 if (thread->saved_fpu_context)
203 slab_free(fpu_context_cache, thread->saved_fpu_context);
204#endif
205 return ENOMEM;
206 }
207
208 thread->kstack = (uint8_t *) PA2KA(stack_phys);
209
210#ifdef CONFIG_UDEBUG
211 mutex_initialize(&thread->udebug.lock, MUTEX_PASSIVE);
212#endif
213
214 return EOK;
215}
216
217/** Destruction of thread_t object */
218static size_t thr_destructor(void *obj)
219{
220 thread_t *thread = (thread_t *) obj;
221
222 /* call the architecture-specific part of the destructor */
223 thr_destructor_arch(thread);
224
225 frame_free(KA2PA(thread->kstack), STACK_FRAMES);
226
227#ifdef CONFIG_FPU
228 if (thread->saved_fpu_context)
229 slab_free(fpu_context_cache, thread->saved_fpu_context);
230#endif
231
232 return STACK_FRAMES; /* number of frames freed */
233}
234
235/** Initialize threads
236 *
237 * Initialize kernel threads support.
238 *
239 */
240void thread_init(void)
241{
242 THREAD = NULL;
243
244 atomic_store(&nrdy, 0);
245 thread_cache = slab_cache_create("thread_t", sizeof(thread_t), 0,
246 thr_constructor, thr_destructor, 0);
247
248#ifdef CONFIG_FPU
249 fpu_context_cache = slab_cache_create("fpu_context_t",
250 sizeof(fpu_context_t), FPU_CONTEXT_ALIGN, NULL, NULL, 0);
251#endif
252
253 odict_initialize(&threads, threads_getkey, threads_cmp);
254}
255
256/** Wire thread to the given CPU
257 *
258 * @param cpu CPU to wire the thread to.
259 *
260 */
261void thread_wire(thread_t *thread, cpu_t *cpu)
262{
263 irq_spinlock_lock(&thread->lock, true);
264 thread->cpu = cpu;
265 thread->wired = true;
266 irq_spinlock_unlock(&thread->lock, true);
267}
268
269/** Invoked right before thread_ready() readies the thread. thread is locked. */
270static void before_thread_is_ready(thread_t *thread)
271{
272 assert(irq_spinlock_locked(&thread->lock));
273}
274
275/** Make thread ready
276 *
277 * Switch thread to the ready state.
278 *
279 * @param thread Thread to make ready.
280 *
281 */
282void thread_ready(thread_t *thread)
283{
284 irq_spinlock_lock(&thread->lock, true);
285
286 assert(thread->state != Ready);
287
288 before_thread_is_ready(thread);
289
290 int i = (thread->priority < RQ_COUNT - 1) ?
291 ++thread->priority : thread->priority;
292
293 cpu_t *cpu;
294 if (thread->wired || thread->nomigrate || thread->fpu_context_engaged) {
295 /* Cannot ready to another CPU */
296 assert(thread->cpu != NULL);
297 cpu = thread->cpu;
298 } else if (thread->stolen) {
299 /* Ready to the stealing CPU */
300 cpu = CPU;
301 } else if (thread->cpu) {
302 /* Prefer the CPU on which the thread ran last */
303 assert(thread->cpu != NULL);
304 cpu = thread->cpu;
305 } else {
306 cpu = CPU;
307 }
308
309 thread->state = Ready;
310
311 irq_spinlock_pass(&thread->lock, &(cpu->rq[i].lock));
312
313 /*
314 * Append thread to respective ready queue
315 * on respective processor.
316 */
317
318 list_append(&thread->rq_link, &cpu->rq[i].rq);
319 cpu->rq[i].n++;
320 irq_spinlock_unlock(&(cpu->rq[i].lock), true);
321
322 atomic_inc(&nrdy);
323 atomic_inc(&cpu->nrdy);
324}
325
326/** Create new thread
327 *
328 * Create a new thread.
329 *
330 * @param func Thread's implementing function.
331 * @param arg Thread's implementing function argument.
332 * @param task Task to which the thread belongs. The caller must
333 * guarantee that the task won't cease to exist during the
334 * call. The task's lock may not be held.
335 * @param flags Thread flags.
336 * @param name Symbolic name (a copy is made).
337 *
338 * @return New thread's structure on success, NULL on failure.
339 *
340 */
341thread_t *thread_create(void (*func)(void *), void *arg, task_t *task,
342 thread_flags_t flags, const char *name)
343{
344 thread_t *thread = (thread_t *) slab_alloc(thread_cache, 0);
345 if (!thread)
346 return NULL;
347
348 /* Not needed, but good for debugging */
349 memsetb(thread->kstack, STACK_SIZE, 0);
350
351 irq_spinlock_lock(&tidlock, true);
352 thread->tid = ++last_tid;
353 irq_spinlock_unlock(&tidlock, true);
354
355 memset(&thread->saved_context, 0, sizeof(thread->saved_context));
356 context_set(&thread->saved_context, FADDR(cushion),
357 (uintptr_t) thread->kstack, STACK_SIZE);
358
359 current_initialize((current_t *) thread->kstack);
360
361 ipl_t ipl = interrupts_disable();
362 thread->saved_context.ipl = interrupts_read();
363 interrupts_restore(ipl);
364
365 str_cpy(thread->name, THREAD_NAME_BUFLEN, name);
366
367 thread->thread_code = func;
368 thread->thread_arg = arg;
369 thread->ticks = -1;
370 thread->ucycles = 0;
371 thread->kcycles = 0;
372 thread->uncounted =
373 ((flags & THREAD_FLAG_UNCOUNTED) == THREAD_FLAG_UNCOUNTED);
374 thread->priority = -1; /* Start in rq[0] */
375 thread->cpu = NULL;
376 thread->wired = false;
377 thread->stolen = false;
378 thread->uspace =
379 ((flags & THREAD_FLAG_USPACE) == THREAD_FLAG_USPACE);
380
381 thread->nomigrate = 0;
382 thread->state = Entering;
383
384 timeout_initialize(&thread->sleep_timeout);
385 thread->sleep_interruptible = false;
386 thread->sleep_composable = false;
387 thread->sleep_queue = NULL;
388 thread->timeout_pending = false;
389
390 thread->in_copy_from_uspace = false;
391 thread->in_copy_to_uspace = false;
392
393 thread->interrupted = false;
394 thread->detached = false;
395 waitq_initialize(&thread->join_wq);
396
397 thread->task = task;
398
399 thread->fpu_context_exists = false;
400 thread->fpu_context_engaged = false;
401
402 odlink_initialize(&thread->lthreads);
403
404#ifdef CONFIG_UDEBUG
405 /* Initialize debugging stuff */
406 thread->btrace = false;
407 udebug_thread_initialize(&thread->udebug);
408#endif
409
410 /* Might depend on previous initialization */
411 thread_create_arch(thread);
412
413 if ((flags & THREAD_FLAG_NOATTACH) != THREAD_FLAG_NOATTACH)
414 thread_attach(thread, task);
415
416 return thread;
417}
418
419/** Destroy thread memory structure
420 *
421 * Detach thread from all queues, cpus etc. and destroy it.
422 *
423 * @param thread Thread to be destroyed.
424 * @param irq_res Indicate whether it should unlock thread->lock
425 * in interrupts-restore mode.
426 *
427 */
428void thread_destroy(thread_t *thread, bool irq_res)
429{
430 assert(irq_spinlock_locked(&thread->lock));
431 assert((thread->state == Exiting) || (thread->state == Lingering));
432 assert(thread->task);
433 assert(thread->cpu);
434
435 irq_spinlock_lock(&thread->cpu->lock, false);
436 if (thread->cpu->fpu_owner == thread)
437 thread->cpu->fpu_owner = NULL;
438 irq_spinlock_unlock(&thread->cpu->lock, false);
439
440 irq_spinlock_pass(&thread->lock, &threads_lock);
441
442 odict_remove(&thread->lthreads);
443
444 irq_spinlock_pass(&threads_lock, &thread->task->lock);
445
446 /*
447 * Detach from the containing task.
448 */
449 list_remove(&thread->th_link);
450 irq_spinlock_unlock(&thread->task->lock, irq_res);
451
452 /*
453 * Drop the reference to the containing task.
454 */
455 task_release(thread->task);
456 slab_free(thread_cache, thread);
457}
458
459/** Make the thread visible to the system.
460 *
461 * Attach the thread structure to the current task and make it visible in the
462 * threads_tree.
463 *
464 * @param t Thread to be attached to the task.
465 * @param task Task to which the thread is to be attached.
466 *
467 */
468void thread_attach(thread_t *thread, task_t *task)
469{
470 /*
471 * Attach to the specified task.
472 */
473 irq_spinlock_lock(&task->lock, true);
474
475 /* Hold a reference to the task. */
476 task_hold(task);
477
478 /* Must not count kbox thread into lifecount */
479 if (thread->uspace)
480 atomic_inc(&task->lifecount);
481
482 list_append(&thread->th_link, &task->threads);
483
484 irq_spinlock_pass(&task->lock, &threads_lock);
485
486 /*
487 * Register this thread in the system-wide dictionary.
488 */
489 odict_insert(&thread->lthreads, &threads, NULL);
490 irq_spinlock_unlock(&threads_lock, true);
491}
492
493/** Terminate thread.
494 *
495 * End current thread execution and switch it to the exiting state.
496 * All pending timeouts are executed.
497 *
498 */
499void thread_exit(void)
500{
501 if (THREAD->uspace) {
502#ifdef CONFIG_UDEBUG
503 /* Generate udebug THREAD_E event */
504 udebug_thread_e_event();
505
506 /*
507 * This thread will not execute any code or system calls from
508 * now on.
509 */
510 udebug_stoppable_begin();
511#endif
512 if (atomic_predec(&TASK->lifecount) == 0) {
513 /*
514 * We are the last userspace thread in the task that
515 * still has not exited. With the exception of the
516 * moment the task was created, new userspace threads
517 * can only be created by threads of the same task.
518 * We are safe to perform cleanup.
519 *
520 */
521 ipc_cleanup();
522 futex_task_cleanup();
523 LOG("Cleanup of task %" PRIu64 " completed.", TASK->taskid);
524 }
525 }
526
527restart:
528 irq_spinlock_lock(&THREAD->lock, true);
529 if (THREAD->timeout_pending) {
530 /* Busy waiting for timeouts in progress */
531 irq_spinlock_unlock(&THREAD->lock, true);
532 goto restart;
533 }
534
535 THREAD->state = Exiting;
536 irq_spinlock_unlock(&THREAD->lock, true);
537
538 scheduler();
539
540 /* Not reached */
541 while (true)
542 ;
543}
544
545/** Interrupts an existing thread so that it may exit as soon as possible.
546 *
547 * Threads that are blocked waiting for a synchronization primitive
548 * are woken up with a return code of EINTR if the
549 * blocking call was interruptable. See waitq_sleep_timeout().
550 *
551 * The caller must guarantee the thread object is valid during the entire
552 * function, eg by holding the threads_lock lock.
553 *
554 * Interrupted threads automatically exit when returning back to user space.
555 *
556 * @param thread A valid thread object. The caller must guarantee it
557 * will remain valid until thread_interrupt() exits.
558 */
559void thread_interrupt(thread_t *thread)
560{
561 assert(thread != NULL);
562
563 irq_spinlock_lock(&thread->lock, true);
564
565 thread->interrupted = true;
566 bool sleeping = (thread->state == Sleeping);
567
568 irq_spinlock_unlock(&thread->lock, true);
569
570 if (sleeping)
571 waitq_interrupt_sleep(thread);
572}
573
574/** Returns true if the thread was interrupted.
575 *
576 * @param thread A valid thread object. User must guarantee it will
577 * be alive during the entire call.
578 * @return true if the thread was already interrupted via thread_interrupt().
579 */
580bool thread_interrupted(thread_t *thread)
581{
582 assert(thread != NULL);
583
584 bool interrupted;
585
586 irq_spinlock_lock(&thread->lock, true);
587 interrupted = thread->interrupted;
588 irq_spinlock_unlock(&thread->lock, true);
589
590 return interrupted;
591}
592
593/** Prevent the current thread from being migrated to another processor. */
594void thread_migration_disable(void)
595{
596 assert(THREAD);
597
598 THREAD->nomigrate++;
599}
600
601/** Allow the current thread to be migrated to another processor. */
602void thread_migration_enable(void)
603{
604 assert(THREAD);
605 assert(THREAD->nomigrate > 0);
606
607 if (THREAD->nomigrate > 0)
608 THREAD->nomigrate--;
609}
610
611/** Thread sleep
612 *
613 * Suspend execution of the current thread.
614 *
615 * @param sec Number of seconds to sleep.
616 *
617 */
618void thread_sleep(uint32_t sec)
619{
620 /*
621 * Sleep in 1000 second steps to support
622 * full argument range
623 */
624 while (sec > 0) {
625 uint32_t period = (sec > 1000) ? 1000 : sec;
626
627 thread_usleep(period * 1000000);
628 sec -= period;
629 }
630}
631
632/** Wait for another thread to exit.
633 *
634 * @param thread Thread to join on exit.
635 * @param usec Timeout in microseconds.
636 * @param flags Mode of operation.
637 *
638 * @return An error code from errno.h or an error code from synch.h.
639 *
640 */
641errno_t thread_join_timeout(thread_t *thread, uint32_t usec, unsigned int flags)
642{
643 if (thread == THREAD)
644 return EINVAL;
645
646 /*
647 * Since thread join can only be called once on an undetached thread,
648 * the thread pointer is guaranteed to be still valid.
649 */
650
651 irq_spinlock_lock(&thread->lock, true);
652 assert(!thread->detached);
653 irq_spinlock_unlock(&thread->lock, true);
654
655 return waitq_sleep_timeout(&thread->join_wq, usec, flags, NULL);
656}
657
658/** Detach thread.
659 *
660 * Mark the thread as detached. If the thread is already
661 * in the Lingering state, deallocate its resources.
662 *
663 * @param thread Thread to be detached.
664 *
665 */
666void thread_detach(thread_t *thread)
667{
668 /*
669 * Since the thread is expected not to be already detached,
670 * pointer to it must be still valid.
671 */
672 irq_spinlock_lock(&thread->lock, true);
673 assert(!thread->detached);
674
675 if (thread->state == Lingering) {
676 /*
677 * Unlock &thread->lock and restore
678 * interrupts in thread_destroy().
679 */
680 thread_destroy(thread, true);
681 return;
682 } else {
683 thread->detached = true;
684 }
685
686 irq_spinlock_unlock(&thread->lock, true);
687}
688
689/** Thread usleep
690 *
691 * Suspend execution of the current thread.
692 *
693 * @param usec Number of microseconds to sleep.
694 *
695 */
696void thread_usleep(uint32_t usec)
697{
698 waitq_t wq;
699
700 waitq_initialize(&wq);
701
702 (void) waitq_sleep_timeout(&wq, usec, SYNCH_FLAGS_NON_BLOCKING, NULL);
703}
704
705static void thread_print(thread_t *thread, bool additional)
706{
707 uint64_t ucycles, kcycles;
708 char usuffix, ksuffix;
709 order_suffix(thread->ucycles, &ucycles, &usuffix);
710 order_suffix(thread->kcycles, &kcycles, &ksuffix);
711
712 char *name;
713 if (str_cmp(thread->name, "uinit") == 0)
714 name = thread->task->name;
715 else
716 name = thread->name;
717
718#ifdef __32_BITS__
719 if (additional)
720 printf("%-8" PRIu64 " %10p %10p %9" PRIu64 "%c %9" PRIu64 "%c ",
721 thread->tid, thread->thread_code, thread->kstack,
722 ucycles, usuffix, kcycles, ksuffix);
723 else
724 printf("%-8" PRIu64 " %-14s %10p %-8s %10p %-5" PRIu32 "\n",
725 thread->tid, name, thread, thread_states[thread->state],
726 thread->task, thread->task->container);
727#endif
728
729#ifdef __64_BITS__
730 if (additional)
731 printf("%-8" PRIu64 " %18p %18p\n"
732 " %9" PRIu64 "%c %9" PRIu64 "%c ",
733 thread->tid, thread->thread_code, thread->kstack,
734 ucycles, usuffix, kcycles, ksuffix);
735 else
736 printf("%-8" PRIu64 " %-14s %18p %-8s %18p %-5" PRIu32 "\n",
737 thread->tid, name, thread, thread_states[thread->state],
738 thread->task, thread->task->container);
739#endif
740
741 if (additional) {
742 if (thread->cpu)
743 printf("%-5u", thread->cpu->id);
744 else
745 printf("none ");
746
747 if (thread->state == Sleeping) {
748#ifdef __32_BITS__
749 printf(" %10p", thread->sleep_queue);
750#endif
751
752#ifdef __64_BITS__
753 printf(" %18p", thread->sleep_queue);
754#endif
755 }
756
757 printf("\n");
758 }
759}
760
761/** Print list of threads debug info
762 *
763 * @param additional Print additional information.
764 *
765 */
766void thread_print_list(bool additional)
767{
768 thread_t *thread;
769
770 /* Messing with thread structures, avoid deadlock */
771 irq_spinlock_lock(&threads_lock, true);
772
773#ifdef __32_BITS__
774 if (additional)
775 printf("[id ] [code ] [stack ] [ucycles ] [kcycles ]"
776 " [cpu] [waitqueue]\n");
777 else
778 printf("[id ] [name ] [address ] [state ] [task ]"
779 " [ctn]\n");
780#endif
781
782#ifdef __64_BITS__
783 if (additional) {
784 printf("[id ] [code ] [stack ]\n"
785 " [ucycles ] [kcycles ] [cpu] [waitqueue ]\n");
786 } else
787 printf("[id ] [name ] [address ] [state ]"
788 " [task ] [ctn]\n");
789#endif
790
791 thread = thread_first();
792 while (thread != NULL) {
793 thread_print(thread, additional);
794 thread = thread_next(thread);
795 }
796
797 irq_spinlock_unlock(&threads_lock, true);
798}
799
800/** Check whether thread exists.
801 *
802 * Note that threads_lock must be already held and
803 * interrupts must be already disabled.
804 *
805 * @param thread Pointer to thread.
806 *
807 * @return True if thread t is known to the system, false otherwise.
808 *
809 */
810bool thread_exists(thread_t *thread)
811{
812 assert(interrupts_disabled());
813 assert(irq_spinlock_locked(&threads_lock));
814
815 odlink_t *odlink = odict_find_eq(&threads, thread, NULL);
816 return odlink != NULL;
817}
818
819/** Update accounting of current thread.
820 *
821 * Note that thread_lock on THREAD must be already held and
822 * interrupts must be already disabled.
823 *
824 * @param user True to update user accounting, false for kernel.
825 *
826 */
827void thread_update_accounting(bool user)
828{
829 uint64_t time = get_cycle();
830
831 assert(interrupts_disabled());
832 assert(irq_spinlock_locked(&THREAD->lock));
833
834 if (user)
835 THREAD->ucycles += time - THREAD->last_cycle;
836 else
837 THREAD->kcycles += time - THREAD->last_cycle;
838
839 THREAD->last_cycle = time;
840}
841
842/** Find thread structure corresponding to thread ID.
843 *
844 * The threads_lock must be already held by the caller of this function and
845 * interrupts must be disabled.
846 *
847 * @param id Thread ID.
848 *
849 * @return Thread structure address or NULL if there is no such thread ID.
850 *
851 */
852thread_t *thread_find_by_id(thread_id_t thread_id)
853{
854 thread_t *thread;
855
856 assert(interrupts_disabled());
857 assert(irq_spinlock_locked(&threads_lock));
858
859 thread = thread_first();
860 while (thread != NULL) {
861 if (thread->tid == thread_id)
862 return thread;
863
864 thread = thread_next(thread);
865 }
866
867 return NULL;
868}
869
870/** Get count of threads.
871 *
872 * @return Number of threads in the system
873 */
874size_t thread_count(void)
875{
876 assert(interrupts_disabled());
877 assert(irq_spinlock_locked(&threads_lock));
878
879 return odict_count(&threads);
880}
881
882/** Get first thread.
883 *
884 * @return Pointer to first thread or @c NULL if there are none.
885 */
886thread_t *thread_first(void)
887{
888 odlink_t *odlink;
889
890 assert(interrupts_disabled());
891 assert(irq_spinlock_locked(&threads_lock));
892
893 odlink = odict_first(&threads);
894 if (odlink == NULL)
895 return NULL;
896
897 return odict_get_instance(odlink, thread_t, lthreads);
898}
899
900/** Get next thread.
901 *
902 * @param cur Current thread
903 * @return Pointer to next thread or @c NULL if there are no more threads.
904 */
905thread_t *thread_next(thread_t *cur)
906{
907 odlink_t *odlink;
908
909 assert(interrupts_disabled());
910 assert(irq_spinlock_locked(&threads_lock));
911
912 odlink = odict_next(&cur->lthreads, &threads);
913 if (odlink == NULL)
914 return NULL;
915
916 return odict_get_instance(odlink, thread_t, lthreads);
917}
918
919#ifdef CONFIG_UDEBUG
920
921void thread_stack_trace(thread_id_t thread_id)
922{
923 irq_spinlock_lock(&threads_lock, true);
924
925 thread_t *thread = thread_find_by_id(thread_id);
926 if (thread == NULL) {
927 printf("No such thread.\n");
928 irq_spinlock_unlock(&threads_lock, true);
929 return;
930 }
931
932 irq_spinlock_lock(&thread->lock, false);
933
934 /*
935 * Schedule a stack trace to be printed
936 * just before the thread is scheduled next.
937 *
938 * If the thread is sleeping then try to interrupt
939 * the sleep. Any request for printing an uspace stack
940 * trace from within the kernel should be always
941 * considered a last resort debugging means, therefore
942 * forcing the thread's sleep to be interrupted
943 * is probably justifiable.
944 */
945
946 bool sleeping = false;
947 istate_t *istate = thread->udebug.uspace_state;
948 if (istate != NULL) {
949 printf("Scheduling thread stack trace.\n");
950 thread->btrace = true;
951 if (thread->state == Sleeping)
952 sleeping = true;
953 } else
954 printf("Thread interrupt state not available.\n");
955
956 irq_spinlock_unlock(&thread->lock, false);
957
958 if (sleeping)
959 waitq_interrupt_sleep(thread);
960
961 irq_spinlock_unlock(&threads_lock, true);
962}
963
964#endif /* CONFIG_UDEBUG */
965
966/** Get key function for the @c threads ordered dictionary.
967 *
968 * @param odlink Link
969 * @return Pointer to thread structure cast as 'void *'
970 */
971static void *threads_getkey(odlink_t *odlink)
972{
973 thread_t *thread = odict_get_instance(odlink, thread_t, lthreads);
974 return (void *) thread;
975}
976
977/** Key comparison function for the @c threads ordered dictionary.
978 *
979 * @param a Pointer to thread A
980 * @param b Pointer to thread B
981 * @return -1, 0, 1 iff pointer to A is less than, equal to, greater than B
982 */
983static int threads_cmp(void *a, void *b)
984{
985 if (a > b)
986 return -1;
987 else if (a == b)
988 return 0;
989 else
990 return +1;
991}
992
993/** Process syscall to create new thread.
994 *
995 */
996sys_errno_t sys_thread_create(uspace_arg_t *uspace_uarg, char *uspace_name,
997 size_t name_len, thread_id_t *uspace_thread_id)
998{
999 if (name_len > THREAD_NAME_BUFLEN - 1)
1000 name_len = THREAD_NAME_BUFLEN - 1;
1001
1002 char namebuf[THREAD_NAME_BUFLEN];
1003 errno_t rc = copy_from_uspace(namebuf, uspace_name, name_len);
1004 if (rc != EOK)
1005 return (sys_errno_t) rc;
1006
1007 namebuf[name_len] = 0;
1008
1009 /*
1010 * In case of failure, kernel_uarg will be deallocated in this function.
1011 * In case of success, kernel_uarg will be freed in uinit().
1012 */
1013 uspace_arg_t *kernel_uarg =
1014 (uspace_arg_t *) malloc(sizeof(uspace_arg_t));
1015 if (!kernel_uarg)
1016 return (sys_errno_t) ENOMEM;
1017
1018 rc = copy_from_uspace(kernel_uarg, uspace_uarg, sizeof(uspace_arg_t));
1019 if (rc != EOK) {
1020 free(kernel_uarg);
1021 return (sys_errno_t) rc;
1022 }
1023
1024 thread_t *thread = thread_create(uinit, kernel_uarg, TASK,
1025 THREAD_FLAG_USPACE | THREAD_FLAG_NOATTACH, namebuf);
1026 if (thread) {
1027 if (uspace_thread_id != NULL) {
1028 rc = copy_to_uspace(uspace_thread_id, &thread->tid,
1029 sizeof(thread->tid));
1030 if (rc != EOK) {
1031 /*
1032 * We have encountered a failure, but the thread
1033 * has already been created. We need to undo its
1034 * creation now.
1035 */
1036
1037 /*
1038 * The new thread structure is initialized, but
1039 * is still not visible to the system.
1040 * We can safely deallocate it.
1041 */
1042 slab_free(thread_cache, thread);
1043 free(kernel_uarg);
1044
1045 return (sys_errno_t) rc;
1046 }
1047 }
1048
1049#ifdef CONFIG_UDEBUG
1050 /*
1051 * Generate udebug THREAD_B event and attach the thread.
1052 * This must be done atomically (with the debug locks held),
1053 * otherwise we would either miss some thread or receive
1054 * THREAD_B events for threads that already existed
1055 * and could be detected with THREAD_READ before.
1056 */
1057 udebug_thread_b_event_attach(thread, TASK);
1058#else
1059 thread_attach(thread, TASK);
1060#endif
1061 thread_ready(thread);
1062
1063 return 0;
1064 } else
1065 free(kernel_uarg);
1066
1067 return (sys_errno_t) ENOMEM;
1068}
1069
1070/** Process syscall to terminate thread.
1071 *
1072 */
1073sys_errno_t sys_thread_exit(int uspace_status)
1074{
1075 thread_exit();
1076}
1077
1078/** Syscall for getting TID.
1079 *
1080 * @param uspace_thread_id Userspace address of 8-byte buffer where to store
1081 * current thread ID.
1082 *
1083 * @return 0 on success or an error code from @ref errno.h.
1084 *
1085 */
1086sys_errno_t sys_thread_get_id(thread_id_t *uspace_thread_id)
1087{
1088 /*
1089 * No need to acquire lock on THREAD because tid
1090 * remains constant for the lifespan of the thread.
1091 *
1092 */
1093 return (sys_errno_t) copy_to_uspace(uspace_thread_id, &THREAD->tid,
1094 sizeof(THREAD->tid));
1095}
1096
1097/** Syscall wrapper for sleeping. */
1098sys_errno_t sys_thread_usleep(uint32_t usec)
1099{
1100 thread_usleep(usec);
1101 return 0;
1102}
1103
1104sys_errno_t sys_thread_udelay(uint32_t usec)
1105{
1106 delay(usec);
1107 return 0;
1108}
1109
1110/** @}
1111 */
Note: See TracBrowser for help on using the repository browser.