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

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

Improve comment for thread_create().

  • Property mode set to 100644
File size: 17.6 KB
Line 
1/*
2 * Copyright (c) 2001-2004 Jakub Jermar
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 *
9 * - Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 * - The name of the author may not be used to endorse or promote products
15 * derived from this software without specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 */
28
29/** @addtogroup genericproc
30 * @{
31 */
32
33/**
34 * @file
35 * @brief Thread management functions.
36 */
37
38#include <proc/scheduler.h>
39#include <proc/thread.h>
40#include <proc/task.h>
41#include <proc/uarg.h>
42#include <mm/frame.h>
43#include <mm/page.h>
44#include <arch/asm.h>
45#include <arch/cycle.h>
46#include <arch.h>
47#include <synch/synch.h>
48#include <synch/spinlock.h>
49#include <synch/waitq.h>
50#include <synch/rwlock.h>
51#include <cpu.h>
52#include <func.h>
53#include <context.h>
54#include <adt/avl.h>
55#include <adt/list.h>
56#include <time/clock.h>
57#include <time/timeout.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 <memstr.h>
64#include <print.h>
65#include <mm/slab.h>
66#include <debug.h>
67#include <main/uinit.h>
68#include <syscall/copy.h>
69#include <errno.h>
70#include <console/klog.h>
71
72
73/** Thread states */
74char *thread_states[] = {
75 "Invalid",
76 "Running",
77 "Sleeping",
78 "Ready",
79 "Entering",
80 "Exiting",
81 "Lingering"
82};
83
84/** Lock protecting the threads_tree AVL tree.
85 *
86 * For locking rules, see declaration thereof.
87 */
88SPINLOCK_INITIALIZE(threads_lock);
89
90/** AVL tree of all threads.
91 *
92 * When a thread is found in the threads_tree AVL tree, it is guaranteed to
93 * exist as long as the threads_lock is held.
94 */
95avltree_t threads_tree;
96
97SPINLOCK_INITIALIZE(tidlock);
98thread_id_t last_tid = 0;
99
100static slab_cache_t *thread_slab;
101#ifdef ARCH_HAS_FPU
102slab_cache_t *fpu_context_slab;
103#endif
104
105/** Thread wrapper.
106 *
107 * This wrapper is provided to ensure that every thread makes a call to
108 * thread_exit() when its implementing function returns.
109 *
110 * interrupts_disable() is assumed.
111 *
112 */
113static void cushion(void)
114{
115 void (*f)(void *) = THREAD->thread_code;
116 void *arg = THREAD->thread_arg;
117 THREAD->last_cycle = get_cycle();
118
119 /* This is where each thread wakes up after its creation */
120 spinlock_unlock(&THREAD->lock);
121 interrupts_enable();
122
123 f(arg);
124
125 /* Accumulate accounting to the task */
126 ipl_t ipl = interrupts_disable();
127
128 spinlock_lock(&THREAD->lock);
129 if (!THREAD->uncounted) {
130 thread_update_accounting();
131 uint64_t cycles = THREAD->cycles;
132 THREAD->cycles = 0;
133 spinlock_unlock(&THREAD->lock);
134
135 spinlock_lock(&TASK->lock);
136 TASK->cycles += cycles;
137 spinlock_unlock(&TASK->lock);
138 } else
139 spinlock_unlock(&THREAD->lock);
140
141 interrupts_restore(ipl);
142
143 thread_exit();
144 /* not reached */
145}
146
147/** Initialization and allocation for thread_t structure */
148static int thr_constructor(void *obj, int kmflags)
149{
150 thread_t *t = (thread_t *) obj;
151
152 spinlock_initialize(&t->lock, "thread_t_lock");
153 link_initialize(&t->rq_link);
154 link_initialize(&t->wq_link);
155 link_initialize(&t->th_link);
156
157 /* call the architecture-specific part of the constructor */
158 thr_constructor_arch(t);
159
160#ifdef ARCH_HAS_FPU
161#ifdef CONFIG_FPU_LAZY
162 t->saved_fpu_context = NULL;
163#else
164 t->saved_fpu_context = slab_alloc(fpu_context_slab, kmflags);
165 if (!t->saved_fpu_context)
166 return -1;
167#endif
168#endif
169
170 t->kstack = (uint8_t *) frame_alloc(STACK_FRAMES, FRAME_KA | kmflags);
171 if (!t->kstack) {
172#ifdef ARCH_HAS_FPU
173 if (t->saved_fpu_context)
174 slab_free(fpu_context_slab, t->saved_fpu_context);
175#endif
176 return -1;
177 }
178
179 return 0;
180}
181
182/** Destruction of thread_t object */
183static int thr_destructor(void *obj)
184{
185 thread_t *t = (thread_t *) obj;
186
187 /* call the architecture-specific part of the destructor */
188 thr_destructor_arch(t);
189
190 frame_free(KA2PA(t->kstack));
191#ifdef ARCH_HAS_FPU
192 if (t->saved_fpu_context)
193 slab_free(fpu_context_slab, t->saved_fpu_context);
194#endif
195 return 1; /* One page freed */
196}
197
198/** Initialize threads
199 *
200 * Initialize kernel threads support.
201 *
202 */
203void thread_init(void)
204{
205 THREAD = NULL;
206 atomic_set(&nrdy,0);
207 thread_slab = slab_cache_create("thread_slab", sizeof(thread_t), 0,
208 thr_constructor, thr_destructor, 0);
209
210#ifdef ARCH_HAS_FPU
211 fpu_context_slab = slab_cache_create("fpu_slab", sizeof(fpu_context_t),
212 FPU_CONTEXT_ALIGN, NULL, NULL, 0);
213#endif
214
215 avltree_create(&threads_tree);
216}
217
218/** Make thread ready
219 *
220 * Switch thread t to the ready state.
221 *
222 * @param t Thread to make ready.
223 *
224 */
225void thread_ready(thread_t *t)
226{
227 cpu_t *cpu;
228 runq_t *r;
229 ipl_t ipl;
230 int i, avg;
231
232 ipl = interrupts_disable();
233
234 spinlock_lock(&t->lock);
235
236 ASSERT(!(t->state == Ready));
237
238 i = (t->priority < RQ_COUNT - 1) ? ++t->priority : t->priority;
239
240 cpu = CPU;
241 if (t->flags & THREAD_FLAG_WIRED) {
242 ASSERT(t->cpu != NULL);
243 cpu = t->cpu;
244 }
245 t->state = Ready;
246 spinlock_unlock(&t->lock);
247
248 /*
249 * Append t to respective ready queue on respective processor.
250 */
251 r = &cpu->rq[i];
252 spinlock_lock(&r->lock);
253 list_append(&t->rq_link, &r->rq_head);
254 r->n++;
255 spinlock_unlock(&r->lock);
256
257 atomic_inc(&nrdy);
258 avg = atomic_get(&nrdy) / config.cpu_active;
259 atomic_inc(&cpu->nrdy);
260
261 interrupts_restore(ipl);
262}
263
264/** Create new thread
265 *
266 * Create a new thread.
267 *
268 * @param func Thread's implementing function.
269 * @param arg Thread's implementing function argument.
270 * @param task Task to which the thread belongs. The caller must
271 * guarantee that the task won't cease to exist during the
272 * call. The task's lock may not be held.
273 * @param flags Thread flags.
274 * @param name Symbolic name.
275 * @param uncounted Thread's accounting doesn't affect accumulated task
276 * accounting.
277 *
278 * @return New thread's structure on success, NULL on failure.
279 *
280 */
281thread_t *thread_create(void (* func)(void *), void *arg, task_t *task,
282 int flags, char *name, bool uncounted)
283{
284 thread_t *t;
285 ipl_t ipl;
286
287 t = (thread_t *) slab_alloc(thread_slab, 0);
288 if (!t)
289 return NULL;
290
291 /* Not needed, but good for debugging */
292 memsetb((uintptr_t) t->kstack, THREAD_STACK_SIZE * 1 << STACK_FRAMES,
293 0);
294
295 ipl = interrupts_disable();
296 spinlock_lock(&tidlock);
297 t->tid = ++last_tid;
298 spinlock_unlock(&tidlock);
299 interrupts_restore(ipl);
300
301 context_save(&t->saved_context);
302 context_set(&t->saved_context, FADDR(cushion), (uintptr_t) t->kstack,
303 THREAD_STACK_SIZE);
304
305 the_initialize((the_t *) t->kstack);
306
307 ipl = interrupts_disable();
308 t->saved_context.ipl = interrupts_read();
309 interrupts_restore(ipl);
310
311 memcpy(t->name, name, THREAD_NAME_BUFLEN);
312
313 t->thread_code = func;
314 t->thread_arg = arg;
315 t->ticks = -1;
316 t->cycles = 0;
317 t->uncounted = uncounted;
318 t->priority = -1; /* start in rq[0] */
319 t->cpu = NULL;
320 t->flags = flags;
321 t->state = Entering;
322 t->call_me = NULL;
323 t->call_me_with = NULL;
324
325 timeout_initialize(&t->sleep_timeout);
326 t->sleep_interruptible = false;
327 t->sleep_queue = NULL;
328 t->timeout_pending = 0;
329
330 t->in_copy_from_uspace = false;
331 t->in_copy_to_uspace = false;
332
333 t->interrupted = false;
334 t->detached = false;
335 waitq_initialize(&t->join_wq);
336
337 t->rwlock_holder_type = RWLOCK_NONE;
338
339 t->task = task;
340
341 t->fpu_context_exists = 0;
342 t->fpu_context_engaged = 0;
343
344 avltree_node_initialize(&t->threads_tree_node);
345 t->threads_tree_node.key = (uintptr_t) t;
346
347 /* might depend on previous initialization */
348 thread_create_arch(t);
349
350 if (!(flags & THREAD_FLAG_NOATTACH))
351 thread_attach(t, task);
352
353 return t;
354}
355
356/** Destroy thread memory structure
357 *
358 * Detach thread from all queues, cpus etc. and destroy it.
359 *
360 * Assume thread->lock is held!!
361 */
362void thread_destroy(thread_t *t)
363{
364 ASSERT(t->state == Exiting || t->state == Lingering);
365 ASSERT(t->task);
366 ASSERT(t->cpu);
367
368 spinlock_lock(&t->cpu->lock);
369 if (t->cpu->fpu_owner == t)
370 t->cpu->fpu_owner = NULL;
371 spinlock_unlock(&t->cpu->lock);
372
373 spinlock_unlock(&t->lock);
374
375 spinlock_lock(&threads_lock);
376 avltree_delete(&threads_tree, &t->threads_tree_node);
377 spinlock_unlock(&threads_lock);
378
379 /*
380 * Detach from the containing task.
381 */
382 spinlock_lock(&t->task->lock);
383 list_remove(&t->th_link);
384 spinlock_unlock(&t->task->lock);
385
386 /*
387 * t is guaranteed to be the very last thread of its task.
388 * It is safe to destroy the task.
389 */
390 if (atomic_predec(&t->task->refcount) == 0)
391 task_destroy(t->task);
392
393 slab_free(thread_slab, t);
394}
395
396/** Make the thread visible to the system.
397 *
398 * Attach the thread structure to the current task and make it visible in the
399 * threads_tree.
400 *
401 * @param t Thread to be attached to the task.
402 * @param task Task to which the thread is to be attached.
403 */
404void thread_attach(thread_t *t, task_t *task)
405{
406 ipl_t ipl;
407
408 /*
409 * Attach to the current task.
410 */
411 ipl = interrupts_disable();
412 spinlock_lock(&task->lock);
413 atomic_inc(&task->refcount);
414 atomic_inc(&task->lifecount);
415 list_append(&t->th_link, &task->th_head);
416 spinlock_unlock(&task->lock);
417
418 /*
419 * Register this thread in the system-wide list.
420 */
421 spinlock_lock(&threads_lock);
422 avltree_insert(&threads_tree, &t->threads_tree_node);
423 spinlock_unlock(&threads_lock);
424
425 interrupts_restore(ipl);
426}
427
428/** Terminate thread.
429 *
430 * End current thread execution and switch it to the exiting state. All pending
431 * timeouts are executed.
432 */
433void thread_exit(void)
434{
435 ipl_t ipl;
436
437 if (atomic_predec(&TASK->lifecount) == 0) {
438 /*
439 * We are the last thread in the task that still has not exited.
440 * With the exception of the moment the task was created, new
441 * threads can only be created by threads of the same task.
442 * We are safe to perform cleanup.
443 */
444 if (THREAD->flags & THREAD_FLAG_USPACE) {
445 ipc_cleanup();
446 futex_cleanup();
447 klog_printf("Cleanup of task %llu completed.",
448 TASK->taskid);
449 }
450 }
451
452restart:
453 ipl = interrupts_disable();
454 spinlock_lock(&THREAD->lock);
455 if (THREAD->timeout_pending) {
456 /* busy waiting for timeouts in progress */
457 spinlock_unlock(&THREAD->lock);
458 interrupts_restore(ipl);
459 goto restart;
460 }
461
462 THREAD->state = Exiting;
463 spinlock_unlock(&THREAD->lock);
464 scheduler();
465
466 /* Not reached */
467 while (1)
468 ;
469}
470
471
472/** Thread sleep
473 *
474 * Suspend execution of the current thread.
475 *
476 * @param sec Number of seconds to sleep.
477 *
478 */
479void thread_sleep(uint32_t sec)
480{
481 thread_usleep(sec * 1000000);
482}
483
484/** Wait for another thread to exit.
485 *
486 * @param t Thread to join on exit.
487 * @param usec Timeout in microseconds.
488 * @param flags Mode of operation.
489 *
490 * @return An error code from errno.h or an error code from synch.h.
491 */
492int thread_join_timeout(thread_t *t, uint32_t usec, int flags)
493{
494 ipl_t ipl;
495 int rc;
496
497 if (t == THREAD)
498 return EINVAL;
499
500 /*
501 * Since thread join can only be called once on an undetached thread,
502 * the thread pointer is guaranteed to be still valid.
503 */
504
505 ipl = interrupts_disable();
506 spinlock_lock(&t->lock);
507 ASSERT(!t->detached);
508 spinlock_unlock(&t->lock);
509 interrupts_restore(ipl);
510
511 rc = waitq_sleep_timeout(&t->join_wq, usec, flags);
512
513 return rc;
514}
515
516/** Detach thread.
517 *
518 * Mark the thread as detached, if the thread is already in the Lingering
519 * state, deallocate its resources.
520 *
521 * @param t Thread to be detached.
522 */
523void thread_detach(thread_t *t)
524{
525 ipl_t ipl;
526
527 /*
528 * Since the thread is expected not to be already detached,
529 * pointer to it must be still valid.
530 */
531 ipl = interrupts_disable();
532 spinlock_lock(&t->lock);
533 ASSERT(!t->detached);
534 if (t->state == Lingering) {
535 thread_destroy(t); /* unlocks &t->lock */
536 interrupts_restore(ipl);
537 return;
538 } else {
539 t->detached = true;
540 }
541 spinlock_unlock(&t->lock);
542 interrupts_restore(ipl);
543}
544
545/** Thread usleep
546 *
547 * Suspend execution of the current thread.
548 *
549 * @param usec Number of microseconds to sleep.
550 *
551 */
552void thread_usleep(uint32_t usec)
553{
554 waitq_t wq;
555
556 waitq_initialize(&wq);
557
558 (void) waitq_sleep_timeout(&wq, usec, SYNCH_FLAGS_NON_BLOCKING);
559}
560
561/** Register thread out-of-context invocation
562 *
563 * Register a function and its argument to be executed
564 * on next context switch to the current thread.
565 *
566 * @param call_me Out-of-context function.
567 * @param call_me_with Out-of-context function argument.
568 *
569 */
570void thread_register_call_me(void (* call_me)(void *), void *call_me_with)
571{
572 ipl_t ipl;
573
574 ipl = interrupts_disable();
575 spinlock_lock(&THREAD->lock);
576 THREAD->call_me = call_me;
577 THREAD->call_me_with = call_me_with;
578 spinlock_unlock(&THREAD->lock);
579 interrupts_restore(ipl);
580}
581
582static bool thread_walker(avltree_node_t *node, void *arg)
583{
584 thread_t *t;
585
586 t = avltree_get_instance(node, thread_t, threads_tree_node);
587
588 uint64_t cycles;
589 char suffix;
590 order(t->cycles, &cycles, &suffix);
591
592 if (sizeof(void *) == 4)
593 printf("%-6llu %-10s %#10zx %-8s %#10zx %-3ld %#10zx %#10zx %9llu%c ",
594 t->tid, t->name, t, thread_states[t->state], t->task,
595 t->task->context, t->thread_code, t->kstack, cycles, suffix);
596 else
597 printf("%-6llu %-10s %#18zx %-8s %#18zx %-3ld %#18zx %#18zx %9llu%c ",
598 t->tid, t->name, t, thread_states[t->state], t->task,
599 t->task->context, t->thread_code, t->kstack, cycles, suffix);
600
601 if (t->cpu)
602 printf("%-4zd", t->cpu->id);
603 else
604 printf("none");
605
606 if (t->state == Sleeping) {
607 if (sizeof(uintptr_t) == 4)
608 printf(" %#10zx", t->sleep_queue);
609 else
610 printf(" %#18zx", t->sleep_queue);
611 }
612
613 printf("\n");
614
615 return true;
616}
617
618/** Print list of threads debug info */
619void thread_print_list(void)
620{
621 ipl_t ipl;
622
623 /* Messing with thread structures, avoid deadlock */
624 ipl = interrupts_disable();
625 spinlock_lock(&threads_lock);
626
627 if (sizeof(uintptr_t) == 4) {
628 printf("tid name address state task "
629 "ctx code stack cycles cpu "
630 "waitqueue\n");
631 printf("------ ---------- ---------- -------- ---------- "
632 "--- ---------- ---------- ---------- ---- "
633 "----------\n");
634 } else {
635 printf("tid name address state task "
636 "ctx code stack cycles cpu "
637 "waitqueue\n");
638 printf("------ ---------- ------------------ -------- ------------------ "
639 "--- ------------------ ------------------ ---------- ---- "
640 "------------------\n");
641 }
642
643 avltree_walk(&threads_tree, thread_walker, NULL);
644
645 spinlock_unlock(&threads_lock);
646 interrupts_restore(ipl);
647}
648
649/** Check whether thread exists.
650 *
651 * Note that threads_lock must be already held and
652 * interrupts must be already disabled.
653 *
654 * @param t Pointer to thread.
655 *
656 * @return True if thread t is known to the system, false otherwise.
657 */
658bool thread_exists(thread_t *t)
659{
660 avltree_node_t *node;
661
662 node = avltree_search(&threads_tree, (avltree_key_t) ((uintptr_t) t));
663
664 return node != NULL;
665}
666
667
668/** Update accounting of current thread.
669 *
670 * Note that thread_lock on THREAD must be already held and
671 * interrupts must be already disabled.
672 *
673 */
674void thread_update_accounting(void)
675{
676 uint64_t time = get_cycle();
677 THREAD->cycles += time - THREAD->last_cycle;
678 THREAD->last_cycle = time;
679}
680
681/** Process syscall to create new thread.
682 *
683 */
684unative_t sys_thread_create(uspace_arg_t *uspace_uarg, char *uspace_name,
685 thread_id_t *uspace_thread_id)
686{
687 thread_t *t;
688 char namebuf[THREAD_NAME_BUFLEN];
689 uspace_arg_t *kernel_uarg;
690 int rc;
691
692 rc = copy_from_uspace(namebuf, uspace_name, THREAD_NAME_BUFLEN);
693 if (rc != 0)
694 return (unative_t) rc;
695
696 /*
697 * In case of failure, kernel_uarg will be deallocated in this function.
698 * In case of success, kernel_uarg will be freed in uinit().
699 */
700 kernel_uarg = (uspace_arg_t *) malloc(sizeof(uspace_arg_t), 0);
701
702 rc = copy_from_uspace(kernel_uarg, uspace_uarg, sizeof(uspace_arg_t));
703 if (rc != 0) {
704 free(kernel_uarg);
705 return (unative_t) rc;
706 }
707
708 t = thread_create(uinit, kernel_uarg, TASK,
709 THREAD_FLAG_USPACE | THREAD_FLAG_NOATTACH, namebuf, false);
710 if (t) {
711 if (uspace_thread_id != NULL) {
712 int rc;
713
714 rc = copy_to_uspace(uspace_thread_id, &t->tid,
715 sizeof(t->tid));
716 if (rc != 0) {
717 /*
718 * We have encountered a failure, but the thread
719 * has already been created. We need to undo its
720 * creation now.
721 */
722
723 /*
724 * The new thread structure is initialized, but
725 * is still not visible to the system.
726 * We can safely deallocate it.
727 */
728 slab_free(thread_slab, t);
729 free(kernel_uarg);
730
731 return (unative_t) rc;
732 }
733 }
734 thread_attach(t, TASK);
735 thread_ready(t);
736
737 return 0;
738 } else
739 free(kernel_uarg);
740
741 return (unative_t) ENOMEM;
742}
743
744/** Process syscall to terminate thread.
745 *
746 */
747unative_t sys_thread_exit(int uspace_status)
748{
749 thread_exit();
750 /* Unreachable */
751 return 0;
752}
753
754/** Syscall for getting TID.
755 *
756 * @param uspace_thread_id Userspace address of 8-byte buffer where to store
757 * current thread ID.
758 *
759 * @return 0 on success or an error code from @ref errno.h.
760 */
761unative_t sys_thread_get_id(thread_id_t *uspace_thread_id)
762{
763 /*
764 * No need to acquire lock on THREAD because tid
765 * remains constant for the lifespan of the thread.
766 */
767 return (unative_t) copy_to_uspace(uspace_thread_id, &THREAD->tid,
768 sizeof(THREAD->tid));
769}
770
771/** @}
772 */
Note: See TracBrowser for help on using the repository browser.