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

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

Fix the problem with sys_thread_create() by splitting the create and attach functionality of
thread_create(). Now it is possible to specify a flag that will cause thread_create() to only allocate and
initialize the thread structure. A call to thread_attach() will make the thread visible to the system.
This arrangement makes it easier to undo creation of a thread in case of a failure in sys_thread_create().

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