ba645e7b053dd8f77f86a978656c523f3faea896
[dragonfly.git] / sys / kern / lwkt_thread.c
1 /*
2  * Copyright (c) 2003 Matthew Dillon <dillon@backplane.com>
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  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  *      Each cpu in a system has its own self-contained light weight kernel
27  *      thread scheduler, which means that generally speaking we only need
28  *      to use a critical section to prevent hicups.
29  *
30  * $DragonFly: src/sys/kern/lwkt_thread.c,v 1.9 2003/06/29 03:28:44 dillon Exp $
31  */
32
33 #include <sys/param.h>
34 #include <sys/systm.h>
35 #include <sys/kernel.h>
36 #include <sys/proc.h>
37 #include <sys/rtprio.h>
38 #include <sys/queue.h>
39 #include <sys/thread2.h>
40 #include <sys/sysctl.h>
41 #include <sys/kthread.h>
42 #include <machine/cpu.h>
43 #include <sys/lock.h>
44
45 #include <vm/vm.h>
46 #include <vm/vm_param.h>
47 #include <vm/vm_kern.h>
48 #include <vm/vm_object.h>
49 #include <vm/vm_page.h>
50 #include <vm/vm_map.h>
51 #include <vm/vm_pager.h>
52 #include <vm/vm_extern.h>
53 #include <vm/vm_zone.h>
54
55 #include <machine/stdarg.h>
56
57 static int untimely_switch = 0;
58 SYSCTL_INT(_debug, OID_AUTO, untimely_switch, CTLFLAG_RW, &untimely_switch, 0, "");
59
60
61 static __inline
62 void
63 _lwkt_dequeue(thread_t td)
64 {
65     if (td->td_flags & TDF_RUNQ) {
66         td->td_flags &= ~TDF_RUNQ;
67         TAILQ_REMOVE(&mycpu->gd_tdrunq, td, td_threadq);
68     }
69 }
70
71 static __inline
72 void
73 _lwkt_enqueue(thread_t td)
74 {
75     if ((td->td_flags & TDF_RUNQ) == 0) {
76         td->td_flags |= TDF_RUNQ;
77         TAILQ_INSERT_TAIL(&mycpu->gd_tdrunq, td, td_threadq);
78     }
79 }
80
81 /*
82  * LWKTs operate on a per-cpu basis
83  *
84  * YYY implement strict priorities & round-robin at the same priority
85  */
86 void
87 lwkt_gdinit(struct globaldata *gd)
88 {
89     TAILQ_INIT(&gd->gd_tdrunq);
90 }
91
92 /*
93  * Initialize a thread wait structure prior to first use.
94  *
95  * NOTE!  called from low level boot code, we cannot do anything fancy!
96  */
97 void
98 lwkt_init_wait(lwkt_wait_t w)
99 {
100     TAILQ_INIT(&w->wa_waitq);
101 }
102
103 /*
104  * Create a new thread.  The thread must be associated with a process context
105  * or LWKT start address before it can be scheduled.
106  *
107  * If you intend to create a thread without a process context this function
108  * does everything except load the startup and switcher function.
109  */
110 thread_t
111 lwkt_alloc_thread(struct thread *td)
112 {
113     void *stack;
114     int flags = 0;
115
116     crit_enter();
117     if (td == NULL) {
118         if (mycpu->gd_tdfreecount > 0) {
119             --mycpu->gd_tdfreecount;
120             td = TAILQ_FIRST(&mycpu->gd_tdfreeq);
121             KASSERT(td != NULL && (td->td_flags & TDF_EXITED),
122                 ("lwkt_alloc_thread: unexpected NULL or corrupted td"));
123             TAILQ_REMOVE(&mycpu->gd_tdfreeq, td, td_threadq);
124             crit_exit();
125             stack = td->td_kstack;
126             flags = td->td_flags & (TDF_ALLOCATED_STACK|TDF_ALLOCATED_THREAD);
127         } else {
128             crit_exit();
129             td = zalloc(thread_zone);
130             td->td_kstack = NULL;
131             flags |= TDF_ALLOCATED_THREAD;
132         }
133     }
134     if ((stack = td->td_kstack) == NULL) {
135         stack = (void *)kmem_alloc(kernel_map, UPAGES * PAGE_SIZE);
136         flags |= TDF_ALLOCATED_STACK;
137     }
138     lwkt_init_thread(td, stack, flags);
139     return(td);
140 }
141
142 /*
143  * Initialize a preexisting thread structure.  This function is used by
144  * lwkt_alloc_thread() and also used to initialize the per-cpu idlethread.
145  *
146  * NOTE!  called from low level boot code, we cannot do anything fancy!
147  */
148 void
149 lwkt_init_thread(thread_t td, void *stack, int flags)
150 {
151     bzero(td, sizeof(struct thread));
152     td->td_kstack = stack;
153     td->td_flags |= flags;
154     pmap_init_thread(td);
155 }
156
157 void
158 lwkt_free_thread(struct thread *td)
159 {
160     KASSERT(td->td_flags & TDF_EXITED,
161         ("lwkt_free_thread: did not exit! %p", td));
162
163     crit_enter();
164     if (mycpu->gd_tdfreecount < CACHE_NTHREADS &&
165         (td->td_flags & TDF_ALLOCATED_THREAD)
166     ) {
167         ++mycpu->gd_tdfreecount;
168         TAILQ_INSERT_HEAD(&mycpu->gd_tdfreeq, td, td_threadq);
169         crit_exit();
170     } else {
171         crit_exit();
172         if (td->td_kstack && (td->td_flags & TDF_ALLOCATED_STACK)) {
173             kmem_free(kernel_map,
174                     (vm_offset_t)td->td_kstack, UPAGES * PAGE_SIZE);
175             td->td_kstack = NULL;
176         }
177         if (td->td_flags & TDF_ALLOCATED_THREAD)
178             zfree(thread_zone, td);
179     }
180 }
181
182
183 /*
184  * Switch to the next runnable lwkt.  If no LWKTs are runnable then 
185  * switch to the idlethread.  Switching must occur within a critical
186  * section to avoid races with the scheduling queue.
187  *
188  * We always have full control over our cpu's run queue.  Other cpus
189  * that wish to manipulate our queue must use the cpu_*msg() calls to
190  * talk to our cpu, so a critical section is all that is needed and
191  * the result is very, very fast thread switching.
192  *
193  * We always 'own' our own thread and the threads on our run queue,l
194  * due to TDF_RUNNING or TDF_RUNQ being set.  We can safely clear
195  * TDF_RUNNING while in a critical section.
196  *
197  * The td_switch() function must be called while in the critical section.
198  * This function saves as much state as is appropriate for the type of
199  * thread.
200  *
201  * (self contained on a per cpu basis)
202  */
203 void
204 lwkt_switch(void)
205 {
206     thread_t td = curthread;
207     thread_t ntd;
208
209     if (mycpu->gd_intr_nesting_level)
210         panic("lwkt_switch: cannot switch from within an interrupt\n");
211
212     crit_enter();
213     if ((ntd = td->td_preempted) != NULL) {
214         /*
215          * We had preempted another thread on this cpu, resume the preempted
216          * thread.
217          */
218         td->td_preempted = NULL;
219         ntd->td_flags &= ~TDF_PREEMPTED;
220     } else if ((ntd = TAILQ_FIRST(&mycpu->gd_tdrunq)) != NULL) {
221         TAILQ_REMOVE(&mycpu->gd_tdrunq, ntd, td_threadq);
222         TAILQ_INSERT_TAIL(&mycpu->gd_tdrunq, ntd, td_threadq);
223     } else {
224         ntd = mycpu->gd_idletd;
225     }
226     if (td != ntd)
227         td->td_switch(ntd);
228     crit_exit();
229 }
230
231 /*
232  * Yield our thread while higher priority threads are pending.  This is
233  * typically called when we leave a critical section but it can be safely
234  * called while we are in a critical section.
235  *
236  * This function will not generally yield to equal priority threads but it
237  * can occur as a side effect.  Note that lwkt_switch() is called from
238  * inside the critical section to pervent its own crit_exit() from reentering
239  * lwkt_yield_quick().
240  *
241  * gd_reqpri indicates that *something* changed, e.g. an interrupt or softint
242  * came along but was blocked and made pending.
243  *
244  * (self contained on a per cpu basis)
245  */
246 void
247 lwkt_yield_quick(void)
248 {
249     thread_t td = curthread;
250
251     if ((td->td_pri & TDPRI_MASK) < mycpu->gd_reqpri) {
252         mycpu->gd_reqpri = 0;
253         splz();
254     }
255
256     /*
257      * YYY enabling will cause wakeup() to task-switch, which really
258      * confused the old 4.x code.  This is a good way to simulate
259      * preemption and MP without actually doing preemption or MP, because a
260      * lot of code assumes that wakeup() does not block.
261      */
262     if (untimely_switch && mycpu->gd_intr_nesting_level == 0) {
263         crit_enter();
264         /*
265          * YYY temporary hacks until we disassociate the userland scheduler
266          * from the LWKT scheduler.
267          */
268         if (td->td_flags & TDF_RUNQ) {
269             lwkt_switch();              /* will not reenter yield function */
270         } else {
271             lwkt_schedule_self();       /* make sure we are scheduled */
272             lwkt_switch();              /* will not reenter yield function */
273             lwkt_deschedule_self();     /* make sure we are descheduled */
274         }
275         crit_exit_noyield();
276     }
277 }
278
279 /*
280  * This implements a normal yield which, unlike _quick, will yield to equal
281  * priority threads as well.  Note that gd_reqpri tests will be handled by
282  * the crit_exit() call in lwkt_switch().
283  *
284  * (self contained on a per cpu basis)
285  */
286 void
287 lwkt_yield(void)
288 {
289     lwkt_schedule_self();
290     lwkt_switch();
291 }
292
293 /*
294  * Schedule a thread to run.  As the current thread we can always safely
295  * schedule ourselves, and a shortcut procedure is provided for that
296  * function.
297  *
298  * (non-blocking, self contained on a per cpu basis)
299  */
300 void
301 lwkt_schedule_self(void)
302 {
303     thread_t td = curthread;
304
305     crit_enter();
306     KASSERT(td->td_wait == NULL, ("lwkt_schedule_self(): td_wait not NULL!"));
307     _lwkt_enqueue(td);
308     crit_exit();
309 }
310
311 /*
312  * Generic schedule.  Possibly schedule threads belonging to other cpus and
313  * deal with threads that might be blocked on a wait queue.
314  *
315  * This function will queue requests asynchronously when possible, but may
316  * block if no request structures are available.  Upon return the caller
317  * should note that the scheduling request may not yet have been processed
318  * by the target cpu.
319  *
320  * YYY this is one of the best places to implement any load balancing code.
321  * Load balancing can be accomplished by requesting other sorts of actions
322  * for the thread in question.
323  */
324 void
325 lwkt_schedule(thread_t td)
326 {
327     crit_enter();
328     if (td == curthread) {
329         _lwkt_enqueue(td);
330     } else {
331         lwkt_wait_t w;
332
333         /*
334          * If the thread is on a wait list we have to send our scheduling
335          * request to the owner of the wait structure.  Otherwise we send
336          * the scheduling request to the cpu owning the thread.  Races
337          * are ok, the target will forward the message as necessary (the
338          * message may chase the thread around before it finally gets
339          * acted upon).
340          *
341          * (remember, wait structures use stable storage)
342          */
343         if ((w = td->td_wait) != NULL) {
344             if (lwkt_havetoken(&w->wa_token)) {
345                 TAILQ_REMOVE(&w->wa_waitq, td, td_threadq);
346                 --w->wa_count;
347                 td->td_wait = NULL;
348                 if (td->td_cpu == mycpu->gd_cpuid) {
349                     _lwkt_enqueue(td);
350                 } else {
351                     panic("lwkt_schedule: cpu mismatch1");
352 #if 0
353                     lwkt_cpu_msg_union_t msg = lwkt_getcpumsg();
354                     initScheduleReqMsg_Wait(&msg.mu_SchedReq, td, w);
355                     cpu_sendnormsg(&msg.mu_Msg);
356 #endif
357                 }
358             } else {
359                 panic("lwkt_schedule: cpu mismatch2");
360 #if 0
361                 lwkt_cpu_msg_union_t msg = lwkt_getcpumsg();
362                 initScheduleReqMsg_Wait(&msg.mu_SchedReq, td, w);
363                 cpu_sendnormsg(&msg.mu_Msg);
364 #endif
365             }
366         } else {
367             /*
368              * If the wait structure is NULL and we own the thread, there
369              * is no race (since we are in a critical section).  If we
370              * do not own the thread there might be a race but the
371              * target cpu will deal with it.
372              */
373             if (td->td_cpu == mycpu->gd_cpuid) {
374                 _lwkt_enqueue(td);
375             } else {
376                 panic("lwkt_schedule: cpu mismatch3");
377 #if 0
378                 lwkt_cpu_msg_union_t msg = lwkt_getcpumsg();
379                 initScheduleReqMsg_Thread(&msg.mu_SchedReq, td);
380                 cpu_sendnormsg(&msg.mu_Msg);
381 #endif
382             }
383         }
384     }
385     crit_exit();
386 }
387
388 /*
389  * Deschedule a thread.
390  *
391  * (non-blocking, self contained on a per cpu basis)
392  */
393 void
394 lwkt_deschedule_self(void)
395 {
396     thread_t td = curthread;
397
398     crit_enter();
399     KASSERT(td->td_wait == NULL, ("lwkt_schedule_self(): td_wait not NULL!"));
400     _lwkt_dequeue(td);
401     crit_exit();
402 }
403
404 /*
405  * Generic deschedule.  Descheduling threads other then your own should be
406  * done only in carefully controlled circumstances.  Descheduling is 
407  * asynchronous.  
408  *
409  * This function may block if the cpu has run out of messages.
410  */
411 void
412 lwkt_deschedule(thread_t td)
413 {
414     crit_enter();
415     if (td == curthread) {
416         _lwkt_dequeue(td);
417     } else {
418         if (td->td_cpu == mycpu->gd_cpuid) {
419             _lwkt_dequeue(td);
420         } else {
421             panic("lwkt_deschedule: cpu mismatch");
422 #if 0
423             lwkt_cpu_msg_union_t msg = lwkt_getcpumsg();
424             initDescheduleReqMsg_Thread(&msg.mu_DeschedReq, td);
425             cpu_sendnormsg(&msg.mu_Msg);
426 #endif
427         }
428     }
429     crit_exit();
430 }
431
432 /*
433  * This function deschedules the current thread and blocks on the specified
434  * wait queue.  We obtain ownership of the wait queue in order to block
435  * on it.  A generation number is used to interlock the wait queue in case
436  * it gets signalled while we are blocked waiting on the token.
437  *
438  * Note: alternatively we could dequeue our thread and then message the
439  * target cpu owning the wait queue.  YYY implement as sysctl.
440  *
441  * Note: wait queue signals normally ping-pong the cpu as an optimization.
442  */
443 void
444 lwkt_block(lwkt_wait_t w, const char *wmesg, int *gen)
445 {
446     thread_t td = curthread;
447
448     lwkt_gettoken(&w->wa_token);
449     if (w->wa_gen == *gen) {
450         _lwkt_dequeue(td);
451         TAILQ_INSERT_TAIL(&w->wa_waitq, td, td_threadq);
452         ++w->wa_count;
453         td->td_wait = w;
454         td->td_wmesg = wmesg;
455         lwkt_switch();
456     }
457     /* token might be lost, doesn't matter for gen update */
458     *gen = w->wa_gen;
459     lwkt_reltoken(&w->wa_token);
460 }
461
462 /*
463  * Signal a wait queue.  We gain ownership of the wait queue in order to
464  * signal it.  Once a thread is removed from the wait queue we have to
465  * deal with the cpu owning the thread.
466  *
467  * Note: alternatively we could message the target cpu owning the wait
468  * queue.  YYY implement as sysctl.
469  */
470 void
471 lwkt_signal(lwkt_wait_t w)
472 {
473     thread_t td;
474     int count;
475
476     lwkt_gettoken(&w->wa_token);
477     ++w->wa_gen;
478     count = w->wa_count;
479     while ((td = TAILQ_FIRST(&w->wa_waitq)) != NULL && count) {
480         --count;
481         --w->wa_count;
482         TAILQ_REMOVE(&w->wa_waitq, td, td_threadq);
483         td->td_wait = NULL;
484         td->td_wmesg = NULL;
485         if (td->td_cpu == mycpu->gd_cpuid) {
486             _lwkt_enqueue(td);
487         } else {
488 #if 0
489             lwkt_cpu_msg_union_t msg = lwkt_getcpumsg();
490             initScheduleReqMsg_Thread(&msg.mu_SchedReq, td);
491             cpu_sendnormsg(&msg.mu_Msg);
492 #endif
493             panic("lwkt_signal: cpu mismatch");
494         }
495         lwkt_regettoken(&w->wa_token);
496     }
497     lwkt_reltoken(&w->wa_token);
498 }
499
500 /*
501  * Aquire ownership of a token
502  *
503  * Aquire ownership of a token.  The token may have spl and/or critical
504  * section side effects, depending on its purpose.  These side effects
505  * guarentee that you will maintain ownership of the token as long as you
506  * do not block.  If you block you may lose access to the token (but you
507  * must still release it even if you lose your access to it).
508  *
509  * Note that the spl and critical section characteristics of a token
510  * may not be changed once the token has been initialized.
511  */
512 void
513 lwkt_gettoken(lwkt_token_t tok)
514 {
515     /*
516      * Prevent preemption so the token can't be taken away from us once
517      * we gain ownership of it.  Use a synchronous request which might
518      * block.  The request will be forwarded as necessary playing catchup
519      * to the token.
520      */
521     crit_enter();
522 #if 0
523     while (tok->t_cpu != mycpu->gd_cpuid) {
524         lwkt_cpu_msg_union msg;
525         initTokenReqMsg(&msg.mu_TokenReq);
526         cpu_domsg(&msg);
527     }
528 #endif
529     /*
530      * leave us in a critical section on return.  This will be undone
531      * by lwkt_reltoken()
532      */
533 }
534
535 /*
536  * Release your ownership of a token.  Releases must occur in reverse
537  * order to aquisitions, eventually so priorities can be unwound properly
538  * like SPLs.  At the moment the actual implemention doesn't care.
539  *
540  * We can safely hand a token that we own to another cpu without notifying
541  * it, but once we do we can't get it back without requesting it (unless
542  * the other cpu hands it back to us before we check).
543  *
544  * We might have lost the token, so check that.
545  */
546 void
547 lwkt_reltoken(lwkt_token_t tok)
548 {
549     if (tok->t_cpu == mycpu->gd_cpuid) {
550         tok->t_cpu = tok->t_reqcpu;
551     }
552     crit_exit();
553 }
554
555 /*
556  * Reaquire a token that might have been lost.  Returns 1 if we blocked
557  * while reaquiring the token (meaning that you might have lost other
558  * tokens you held when you made this call), return 0 if we did not block.
559  */
560 int
561 lwkt_regettoken(lwkt_token_t tok)
562 {
563 #if 0
564     if (tok->t_cpu != mycpu->gd_cpuid) {
565         while (tok->t_cpu != mycpu->gd_cpuid) {
566             lwkt_cpu_msg_union msg;
567             initTokenReqMsg(&msg.mu_TokenReq);
568             cpu_domsg(&msg);
569         }
570         return(1);
571     }
572 #endif
573     return(0);
574 }
575
576 /*
577  * Create a kernel process/thread/whatever.  It shares it's address space
578  * with proc0 - ie: kernel only.
579  *
580  * XXX should be renamed to lwkt_create()
581  */
582 int
583 lwkt_create(void (*func)(void *), void *arg,
584     struct thread **tdp, struct thread *template, int tdflags,
585     const char *fmt, ...)
586 {
587     struct thread *td;
588     va_list ap;
589
590     td = *tdp = lwkt_alloc_thread(template);
591     cpu_set_thread_handler(td, kthread_exit, func, arg);
592     td->td_flags |= TDF_VERBOSE | tdflags;
593
594     /*
595      * Set up arg0 for 'ps' etc
596      */
597     va_start(ap, fmt);
598     vsnprintf(td->td_comm, sizeof(td->td_comm), fmt, ap);
599     va_end(ap);
600
601     /*
602      * Schedule the thread to run
603      */
604     if ((td->td_flags & TDF_STOPREQ) == 0)
605         lwkt_schedule(td);
606     else
607         td->td_flags &= ~TDF_STOPREQ;
608     return 0;
609 }
610
611 /*
612  * Destroy an LWKT thread.   Warning!  This function is not called when
613  * a process exits, cpu_proc_exit() directly calls cpu_thread_exit() and
614  * uses a different reaping mechanism.
615  */
616 void
617 lwkt_exit(void)
618 {
619     thread_t td = curthread;
620
621     if (td->td_flags & TDF_VERBOSE)
622         printf("kthread %p %s has exited\n", td, td->td_comm);
623     crit_enter();
624     lwkt_deschedule_self();
625     ++mycpu->gd_tdfreecount;
626     TAILQ_INSERT_TAIL(&mycpu->gd_tdfreeq, td, td_threadq);
627     cpu_thread_exit();
628 }
629
630 /*
631  * Create a kernel process/thread/whatever.  It shares it's address space
632  * with proc0 - ie: kernel only.  5.x compatible.
633  */
634 int
635 kthread_create(void (*func)(void *), void *arg,
636     struct thread **tdp, const char *fmt, ...)
637 {
638     struct thread *td;
639     va_list ap;
640
641     td = *tdp = lwkt_alloc_thread(NULL);
642     cpu_set_thread_handler(td, kthread_exit, func, arg);
643     td->td_flags |= TDF_VERBOSE;
644
645     /*
646      * Set up arg0 for 'ps' etc
647      */
648     va_start(ap, fmt);
649     vsnprintf(td->td_comm, sizeof(td->td_comm), fmt, ap);
650     va_end(ap);
651
652     /*
653      * Schedule the thread to run
654      */
655     lwkt_schedule(td);
656     return 0;
657 }
658
659 /*
660  * Destroy an LWKT thread.   Warning!  This function is not called when
661  * a process exits, cpu_proc_exit() directly calls cpu_thread_exit() and
662  * uses a different reaping mechanism.
663  *
664  * XXX duplicates lwkt_exit()
665  */
666 void
667 kthread_exit(void)
668 {
669     lwkt_exit();
670 }
671