Subversion Repositories HelenOS-historic

Rev

Rev 1210 | Rev 1288 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | Download | RSS feed

  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. /**
  30.  * @file    thread.c
  31.  * @brief   Thread management functions.
  32.  */
  33.  
  34. #include <proc/scheduler.h>
  35. #include <proc/thread.h>
  36. #include <proc/task.h>
  37. #include <proc/uarg.h>
  38. #include <mm/frame.h>
  39. #include <mm/page.h>
  40. #include <arch/asm.h>
  41. #include <arch.h>
  42. #include <synch/synch.h>
  43. #include <synch/spinlock.h>
  44. #include <synch/waitq.h>
  45. #include <synch/rwlock.h>
  46. #include <cpu.h>
  47. #include <func.h>
  48. #include <context.h>
  49. #include <adt/btree.h>
  50. #include <adt/list.h>
  51. #include <typedefs.h>
  52. #include <time/clock.h>
  53. #include <config.h>
  54. #include <arch/interrupt.h>
  55. #include <smp/ipi.h>
  56. #include <arch/faddr.h>
  57. #include <atomic.h>
  58. #include <memstr.h>
  59. #include <print.h>
  60. #include <mm/slab.h>
  61. #include <debug.h>
  62. #include <main/uinit.h>
  63.  
  64. char *thread_states[] = {"Invalid", "Running", "Sleeping", "Ready", "Entering", "Exiting"}; /**< Thread states */
  65.  
  66. /** Lock protecting threads_head list. For locking rules, see declaration thereof. */
  67. SPINLOCK_INITIALIZE(threads_lock);
  68. btree_t threads_btree;          /**< B+tree of all threads. */
  69.  
  70. SPINLOCK_INITIALIZE(tidlock);
  71. __u32 last_tid = 0;
  72.  
  73. static slab_cache_t *thread_slab;
  74. #ifdef ARCH_HAS_FPU
  75. slab_cache_t *fpu_context_slab;
  76. #endif
  77.  
  78. /** Thread wrapper
  79.  *
  80.  * This wrapper is provided to ensure that every thread
  81.  * makes a call to thread_exit() when its implementing
  82.  * function returns.
  83.  *
  84.  * interrupts_disable() is assumed.
  85.  *
  86.  */
  87. static void cushion(void)
  88. {
  89.     void (*f)(void *) = THREAD->thread_code;
  90.     void *arg = THREAD->thread_arg;
  91.  
  92.     /* this is where each thread wakes up after its creation */
  93.     spinlock_unlock(&THREAD->lock);
  94.     interrupts_enable();
  95.  
  96.     f(arg);
  97.     thread_exit();
  98.     /* not reached */
  99. }
  100.  
  101. /** Initialization and allocation for thread_t structure */
  102. static int thr_constructor(void *obj, int kmflags)
  103. {
  104.     thread_t *t = (thread_t *)obj;
  105.     pfn_t pfn;
  106.     int status;
  107.  
  108.     spinlock_initialize(&t->lock, "thread_t_lock");
  109.     link_initialize(&t->rq_link);
  110.     link_initialize(&t->wq_link);
  111.     link_initialize(&t->th_link);
  112.    
  113. #ifdef ARCH_HAS_FPU
  114. #  ifdef CONFIG_FPU_LAZY
  115.     t->saved_fpu_context = NULL;
  116. #  else
  117.     t->saved_fpu_context = slab_alloc(fpu_context_slab,kmflags);
  118.     if (!t->saved_fpu_context)
  119.         return -1;
  120. #  endif
  121. #endif 
  122.  
  123.     pfn = frame_alloc_rc(STACK_FRAMES, FRAME_KA | kmflags,&status);
  124.     if (status) {
  125. #ifdef ARCH_HAS_FPU
  126.         if (t->saved_fpu_context)
  127.             slab_free(fpu_context_slab,t->saved_fpu_context);
  128. #endif
  129.         return -1;
  130.     }
  131.     t->kstack = (__u8 *)PA2KA(PFN2ADDR(pfn));
  132.  
  133.     return 0;
  134. }
  135.  
  136. /** Destruction of thread_t object */
  137. static int thr_destructor(void *obj)
  138. {
  139.     thread_t *t = (thread_t *)obj;
  140.  
  141.     frame_free(ADDR2PFN(KA2PA(t->kstack)));
  142. #ifdef ARCH_HAS_FPU
  143.     if (t->saved_fpu_context)
  144.         slab_free(fpu_context_slab,t->saved_fpu_context);
  145. #endif
  146.     return 1; /* One page freed */
  147. }
  148.  
  149. /** Initialize threads
  150.  *
  151.  * Initialize kernel threads support.
  152.  *
  153.  */
  154. void thread_init(void)
  155. {
  156.     THREAD = NULL;
  157.     atomic_set(&nrdy,0);
  158.     thread_slab = slab_cache_create("thread_slab",
  159.                     sizeof(thread_t),0,
  160.                     thr_constructor, thr_destructor, 0);
  161. #ifdef ARCH_HAS_FPU
  162.     fpu_context_slab = slab_cache_create("fpu_slab",
  163.                          sizeof(fpu_context_t),
  164.                          FPU_CONTEXT_ALIGN,
  165.                          NULL, NULL, 0);
  166. #endif
  167.  
  168.     btree_create(&threads_btree);
  169. }
  170.  
  171. /** Make thread ready
  172.  *
  173.  * Switch thread t to the ready state.
  174.  *
  175.  * @param t Thread to make ready.
  176.  *
  177.  */
  178. void thread_ready(thread_t *t)
  179. {
  180.     cpu_t *cpu;
  181.     runq_t *r;
  182.     ipl_t ipl;
  183.     int i, avg;
  184.  
  185.     ipl = interrupts_disable();
  186.  
  187.     spinlock_lock(&t->lock);
  188.  
  189.     ASSERT(! (t->state == Ready));
  190.  
  191.     i = (t->priority < RQ_COUNT -1) ? ++t->priority : t->priority;
  192.    
  193.     cpu = CPU;
  194.     if (t->flags & X_WIRED) {
  195.         cpu = t->cpu;
  196.     }
  197.     t->state = Ready;
  198.     spinlock_unlock(&t->lock);
  199.    
  200.     /*
  201.      * Append t to respective ready queue on respective processor.
  202.      */
  203.     r = &cpu->rq[i];
  204.     spinlock_lock(&r->lock);
  205.     list_append(&t->rq_link, &r->rq_head);
  206.     r->n++;
  207.     spinlock_unlock(&r->lock);
  208.  
  209.     atomic_inc(&nrdy);
  210.     avg = atomic_get(&nrdy) / config.cpu_active;
  211.     atomic_inc(&cpu->nrdy);
  212.  
  213.     interrupts_restore(ipl);
  214. }
  215.  
  216. /** Destroy thread memory structure
  217.  *
  218.  * Detach thread from all queues, cpus etc. and destroy it.
  219.  *
  220.  * Assume thread->lock is held!!
  221.  */
  222. void thread_destroy(thread_t *t)
  223. {
  224.     ASSERT(t->state == Exiting);
  225.     ASSERT(t->task);
  226.     ASSERT(t->cpu);
  227.  
  228.     spinlock_lock(&t->cpu->lock);
  229.     if(t->cpu->fpu_owner==t)
  230.         t->cpu->fpu_owner=NULL;
  231.     spinlock_unlock(&t->cpu->lock);
  232.  
  233.     /*
  234.      * Detach from the containing task.
  235.      */
  236.     spinlock_lock(&t->task->lock);
  237.     list_remove(&t->th_link);
  238.     spinlock_unlock(&t->task->lock);
  239.    
  240.     spinlock_unlock(&t->lock);
  241.    
  242.     spinlock_lock(&threads_lock);
  243.     btree_remove(&threads_btree, (btree_key_t) ((__address ) t), NULL);
  244.     spinlock_unlock(&threads_lock);
  245.    
  246.     slab_free(thread_slab, t);
  247. }
  248.  
  249. /** Create new thread
  250.  *
  251.  * Create a new thread.
  252.  *
  253.  * @param func  Thread's implementing function.
  254.  * @param arg   Thread's implementing function argument.
  255.  * @param task  Task to which the thread belongs.
  256.  * @param flags Thread flags.
  257.  * @param name  Symbolic name.
  258.  *
  259.  * @return New thread's structure on success, NULL on failure.
  260.  *
  261.  */
  262. thread_t *thread_create(void (* func)(void *), void *arg, task_t *task, int flags, char *name)
  263. {
  264.     thread_t *t;
  265.     ipl_t ipl;
  266.    
  267.     t = (thread_t *) slab_alloc(thread_slab, 0);
  268.     if (!t)
  269.         return NULL;
  270.  
  271.     thread_create_arch(t);
  272.    
  273.     /* Not needed, but good for debugging */
  274.     memsetb((__address)t->kstack, THREAD_STACK_SIZE * 1<<STACK_FRAMES, 0);
  275.    
  276.     ipl = interrupts_disable();
  277.     spinlock_lock(&tidlock);
  278.     t->tid = ++last_tid;
  279.     spinlock_unlock(&tidlock);
  280.     interrupts_restore(ipl);
  281.    
  282.     context_save(&t->saved_context);
  283.     context_set(&t->saved_context, FADDR(cushion), (__address) t->kstack, THREAD_STACK_SIZE);
  284.    
  285.     the_initialize((the_t *) t->kstack);
  286.    
  287.     ipl = interrupts_disable();
  288.     t->saved_context.ipl = interrupts_read();
  289.     interrupts_restore(ipl);
  290.    
  291.     memcpy(t->name, name, THREAD_NAME_BUFLEN);
  292.    
  293.     t->thread_code = func;
  294.     t->thread_arg = arg;
  295.     t->ticks = -1;
  296.     t->priority = -1;       /* start in rq[0] */
  297.     t->cpu = NULL;
  298.     t->flags = 0;
  299.     t->state = Entering;
  300.     t->call_me = NULL;
  301.     t->call_me_with = NULL;
  302.    
  303.     timeout_initialize(&t->sleep_timeout);
  304.     t->sleep_queue = NULL;
  305.     t->timeout_pending = 0;
  306.    
  307.     t->rwlock_holder_type = RWLOCK_NONE;
  308.        
  309.     t->task = task;
  310.    
  311.     t->fpu_context_exists = 0;
  312.     t->fpu_context_engaged = 0;
  313.    
  314.     /*
  315.      * Register this thread in the system-wide list.
  316.      */
  317.     ipl = interrupts_disable();
  318.     spinlock_lock(&threads_lock);
  319.     btree_insert(&threads_btree, (btree_key_t) ((__address) t), (void *) t, NULL);
  320.     spinlock_unlock(&threads_lock);
  321.    
  322.     /*
  323.      * Attach to the containing task.
  324.      */
  325.     spinlock_lock(&task->lock);
  326.     list_append(&t->th_link, &task->th_head);
  327.     spinlock_unlock(&task->lock);
  328.    
  329.     interrupts_restore(ipl);
  330.    
  331.     return t;
  332. }
  333.  
  334. /** Make thread exiting
  335.  *
  336.  * End current thread execution and switch it to the exiting
  337.  * state. All pending timeouts are executed.
  338.  *
  339.  */
  340. void thread_exit(void)
  341. {
  342.     ipl_t ipl;
  343.  
  344. restart:
  345.     ipl = interrupts_disable();
  346.     spinlock_lock(&THREAD->lock);
  347.     if (THREAD->timeout_pending) { /* busy waiting for timeouts in progress */
  348.         spinlock_unlock(&THREAD->lock);
  349.         interrupts_restore(ipl);
  350.         goto restart;
  351.     }
  352.     THREAD->state = Exiting;
  353.     spinlock_unlock(&THREAD->lock);
  354.     scheduler();
  355. }
  356.  
  357.  
  358. /** Thread sleep
  359.  *
  360.  * Suspend execution of the current thread.
  361.  *
  362.  * @param sec Number of seconds to sleep.
  363.  *
  364.  */
  365. void thread_sleep(__u32 sec)
  366. {
  367.     thread_usleep(sec*1000000);
  368. }
  369.  
  370. /** Thread usleep
  371.  *
  372.  * Suspend execution of the current thread.
  373.  *
  374.  * @param usec Number of microseconds to sleep.
  375.  *
  376.  */
  377. void thread_usleep(__u32 usec)
  378. {
  379.     waitq_t wq;
  380.                  
  381.     waitq_initialize(&wq);
  382.  
  383.     (void) waitq_sleep_timeout(&wq, usec, SYNCH_NON_BLOCKING);
  384. }
  385.  
  386. /** Register thread out-of-context invocation
  387.  *
  388.  * Register a function and its argument to be executed
  389.  * on next context switch to the current thread.
  390.  *
  391.  * @param call_me      Out-of-context function.
  392.  * @param call_me_with Out-of-context function argument.
  393.  *
  394.  */
  395. void thread_register_call_me(void (* call_me)(void *), void *call_me_with)
  396. {
  397.     ipl_t ipl;
  398.    
  399.     ipl = interrupts_disable();
  400.     spinlock_lock(&THREAD->lock);
  401.     THREAD->call_me = call_me;
  402.     THREAD->call_me_with = call_me_with;
  403.     spinlock_unlock(&THREAD->lock);
  404.     interrupts_restore(ipl);
  405. }
  406.  
  407. /** Print list of threads debug info */
  408. void thread_print_list(void)
  409. {
  410.     link_t *cur;
  411.     ipl_t ipl;
  412.    
  413.     /* Messing with thread structures, avoid deadlock */
  414.     ipl = interrupts_disable();
  415.     spinlock_lock(&threads_lock);
  416.  
  417.     for (cur = threads_btree.leaf_head.next; cur != &threads_btree.leaf_head; cur = cur->next) {
  418.         btree_node_t *node;
  419.         int i;
  420.  
  421.         node = list_get_instance(cur, btree_node_t, leaf_link);
  422.         for (i = 0; i < node->keys; i++) {
  423.             thread_t *t;
  424.        
  425.             t = (thread_t *) node->value[i];
  426.             printf("%s: address=%#zX, tid=%zd, state=%s, task=%#zX, code=%#zX, stack=%#zX, cpu=",
  427.                 t->name, t, t->tid, thread_states[t->state], t->task, t->thread_code, t->kstack);
  428.             if (t->cpu)
  429.                 printf("cpu%zd ", t->cpu->id);
  430.             else
  431.                 printf("none");
  432.             printf("\n");
  433.         }
  434.     }
  435.  
  436.     spinlock_unlock(&threads_lock);
  437.     interrupts_restore(ipl);
  438. }
  439.  
  440. /** Check whether thread exists.
  441.  *
  442.  * Note that threads_lock must be already held and
  443.  * interrupts must be already disabled.
  444.  *
  445.  * @param t Pointer to thread.
  446.  *
  447.  * @return True if thread t is known to the system, false otherwise.
  448.  */
  449. bool thread_exists(thread_t *t)
  450. {
  451.     btree_node_t *leaf;
  452.    
  453.     return btree_search(&threads_btree, (btree_key_t) ((__address) t), &leaf) != NULL;
  454. }
  455.  
  456. /** Process syscall to create new thread.
  457.  *
  458.  */
  459. __native sys_thread_create(uspace_arg_t *uspace_uarg, char *uspace_name)
  460. {
  461.     thread_t *t;
  462.     char namebuf[THREAD_NAME_BUFLEN];
  463.     uspace_arg_t *kernel_uarg;
  464.     __u32 tid;
  465.  
  466.     copy_from_uspace(namebuf, uspace_name, THREAD_NAME_BUFLEN);
  467.  
  468.     kernel_uarg = (uspace_arg_t *) malloc(sizeof(uspace_arg_t), 0);
  469.     copy_from_uspace(kernel_uarg, uspace_uarg, sizeof(uspace_arg_t));
  470.  
  471.     if ((t = thread_create(uinit, kernel_uarg, TASK, 0, namebuf))) {
  472.         tid = t->tid;
  473.         thread_ready(t);
  474.         return (__native) tid;
  475.     } else {
  476.         free(kernel_uarg);
  477.     }
  478.  
  479.     return (__native) -1;
  480. }
  481.  
  482. /** Process syscall to terminate thread.
  483.  *
  484.  */
  485. __native sys_thread_exit(int uspace_status)
  486. {
  487.     thread_exit();
  488.     /* Unreachable */
  489.     return 0;
  490. }
  491.