Misc interrupts/LWKT 1/2: interlock the idle thread. Put execution of
[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.11 2003/06/29 07:37:06 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(_lwkt, OID_AUTO, untimely_switch, CTLFLAG_RW, &untimely_switch, 0, "");
59 static quad_t switch_count = 0;
60 SYSCTL_QUAD(_lwkt, OID_AUTO, switch_count, CTLFLAG_RW, &switch_count, 0, "");
61 static quad_t preempt_hit = 0;
62 SYSCTL_QUAD(_lwkt, OID_AUTO, preempt_hit, CTLFLAG_RW, &preempt_hit, 0, "");
63 static quad_t preempt_miss = 0;
64 SYSCTL_QUAD(_lwkt, OID_AUTO, preempt_miss, CTLFLAG_RW, &preempt_miss, 0, "");
65
66 /*
67  * These helper procedures handle the runq, they can only be called from
68  * within a critical section.
69  */
70 static __inline
71 void
72 _lwkt_dequeue(thread_t td)
73 {
74     if (td->td_flags & TDF_RUNQ) {
75         int nq = td->td_pri & TDPRI_MASK;
76         struct globaldata *gd = mycpu;
77
78         td->td_flags &= ~TDF_RUNQ;
79         TAILQ_REMOVE(&gd->gd_tdrunq[nq], td, td_threadq);
80         /* runqmask is passively cleaned up by the switcher */
81     }
82 }
83
84 static __inline
85 void
86 _lwkt_enqueue(thread_t td)
87 {
88     if ((td->td_flags & TDF_RUNQ) == 0) {
89         int nq = td->td_pri & TDPRI_MASK;
90         struct globaldata *gd = mycpu;
91
92         td->td_flags |= TDF_RUNQ;
93         TAILQ_INSERT_TAIL(&gd->gd_tdrunq[nq], td, td_threadq);
94         gd->gd_runqmask |= 1 << nq;
95     }
96 }
97
98 /*
99  * LWKTs operate on a per-cpu basis
100  *
101  * YYY implement strict priorities & round-robin at the same priority
102  */
103 void
104 lwkt_gdinit(struct globaldata *gd)
105 {
106     int i;
107
108     for (i = 0; i < sizeof(gd->gd_tdrunq)/sizeof(gd->gd_tdrunq[0]); ++i)
109         TAILQ_INIT(&gd->gd_tdrunq[i]);
110     gd->gd_runqmask = 0;
111 }
112
113 /*
114  * Initialize a thread wait structure prior to first use.
115  *
116  * NOTE!  called from low level boot code, we cannot do anything fancy!
117  */
118 void
119 lwkt_init_wait(lwkt_wait_t w)
120 {
121     TAILQ_INIT(&w->wa_waitq);
122 }
123
124 /*
125  * Create a new thread.  The thread must be associated with a process context
126  * or LWKT start address before it can be scheduled.
127  *
128  * If you intend to create a thread without a process context this function
129  * does everything except load the startup and switcher function.
130  */
131 thread_t
132 lwkt_alloc_thread(struct thread *td)
133 {
134     void *stack;
135     int flags = 0;
136
137     crit_enter();
138     if (td == NULL) {
139         if (mycpu->gd_tdfreecount > 0) {
140             --mycpu->gd_tdfreecount;
141             td = TAILQ_FIRST(&mycpu->gd_tdfreeq);
142             KASSERT(td != NULL && (td->td_flags & TDF_EXITED),
143                 ("lwkt_alloc_thread: unexpected NULL or corrupted td"));
144             TAILQ_REMOVE(&mycpu->gd_tdfreeq, td, td_threadq);
145             crit_exit();
146             stack = td->td_kstack;
147             flags = td->td_flags & (TDF_ALLOCATED_STACK|TDF_ALLOCATED_THREAD);
148         } else {
149             crit_exit();
150             td = zalloc(thread_zone);
151             td->td_kstack = NULL;
152             flags |= TDF_ALLOCATED_THREAD;
153         }
154     }
155     if ((stack = td->td_kstack) == NULL) {
156         stack = (void *)kmem_alloc(kernel_map, UPAGES * PAGE_SIZE);
157         flags |= TDF_ALLOCATED_STACK;
158     }
159     lwkt_init_thread(td, stack, flags);
160     return(td);
161 }
162
163 /*
164  * Initialize a preexisting thread structure.  This function is used by
165  * lwkt_alloc_thread() and also used to initialize the per-cpu idlethread.
166  *
167  * NOTE!  called from low level boot code, we cannot do anything fancy!
168  */
169 void
170 lwkt_init_thread(thread_t td, void *stack, int flags)
171 {
172     bzero(td, sizeof(struct thread));
173     td->td_kstack = stack;
174     td->td_flags |= flags;
175     pmap_init_thread(td);
176 }
177
178 void
179 lwkt_free_thread(struct thread *td)
180 {
181     KASSERT(td->td_flags & TDF_EXITED,
182         ("lwkt_free_thread: did not exit! %p", td));
183
184     crit_enter();
185     if (mycpu->gd_tdfreecount < CACHE_NTHREADS &&
186         (td->td_flags & TDF_ALLOCATED_THREAD)
187     ) {
188         ++mycpu->gd_tdfreecount;
189         TAILQ_INSERT_HEAD(&mycpu->gd_tdfreeq, td, td_threadq);
190         crit_exit();
191     } else {
192         crit_exit();
193         if (td->td_kstack && (td->td_flags & TDF_ALLOCATED_STACK)) {
194             kmem_free(kernel_map,
195                     (vm_offset_t)td->td_kstack, UPAGES * PAGE_SIZE);
196             td->td_kstack = NULL;
197         }
198         if (td->td_flags & TDF_ALLOCATED_THREAD)
199             zfree(thread_zone, td);
200     }
201 }
202
203
204 /*
205  * Switch to the next runnable lwkt.  If no LWKTs are runnable then 
206  * switch to the idlethread.  Switching must occur within a critical
207  * section to avoid races with the scheduling queue.
208  *
209  * We always have full control over our cpu's run queue.  Other cpus
210  * that wish to manipulate our queue must use the cpu_*msg() calls to
211  * talk to our cpu, so a critical section is all that is needed and
212  * the result is very, very fast thread switching.
213  *
214  * We always 'own' our own thread and the threads on our run queue,l
215  * due to TDF_RUNNING or TDF_RUNQ being set.  We can safely clear
216  * TDF_RUNNING while in a critical section.
217  *
218  * The td_switch() function must be called while in the critical section.
219  * This function saves as much state as is appropriate for the type of
220  * thread.
221  *
222  * (self contained on a per cpu basis)
223  */
224 void
225 lwkt_switch(void)
226 {
227     struct globaldata *gd;
228     thread_t td = curthread;
229     thread_t ntd;
230
231     if (mycpu->gd_intr_nesting_level && td->td_preempted == NULL)
232         panic("lwkt_switch: cannot switch from within an interrupt\n");
233
234     crit_enter();
235     ++switch_count;
236     if ((ntd = td->td_preempted) != NULL) {
237         /*
238          * We had preempted another thread on this cpu, resume the preempted
239          * thread.
240          */
241         td->td_preempted = NULL;
242         td->td_pri -= TDPRI_CRIT;
243         ntd->td_flags &= ~TDF_PREEMPTED;
244     } else {
245         /*
246          * Priority queue / round-robin at each priority.  Note that user
247          * processes run at a fixed, low priority and the user process
248          * scheduler deals with interactions between user processes
249          * by scheduling and descheduling them from the LWKT queue as
250          * necessary.
251          */
252         gd = mycpu;
253
254 again:
255         if (gd->gd_runqmask) {
256             int nq = bsrl(gd->gd_runqmask);
257             if ((ntd = TAILQ_FIRST(&gd->gd_tdrunq[nq])) == NULL) {
258                 gd->gd_runqmask &= ~(1 << nq);
259                 goto again;
260             }
261             TAILQ_REMOVE(&gd->gd_tdrunq[nq], ntd, td_threadq);
262             TAILQ_INSERT_TAIL(&gd->gd_tdrunq[nq], ntd, td_threadq);
263         } else {
264             ntd = gd->gd_idletd;
265         }
266     }
267     if (td != ntd)
268         td->td_switch(ntd);
269     crit_exit();
270 }
271
272 /*
273  * The target thread preempts the current thread.  The target thread
274  * structure must be stable and preempt-safe (e.g. an interrupt thread).
275  * When the target thread blocks the current thread will be resumed.
276  *
277  * XXX the target runs in a critical section so it does not open the original
278  * thread up to additional interrupts that the original thread believes it
279  * is blocking.
280  *
281  * Normal kernel threads should not preempt other normal kernel threads
282  * as it breaks the assumptions kernel threads are allowed to make.  Note
283  * that preemption does not mess around with the current thread's RUNQ
284  * state.
285  *
286  * This call is typically made from an interrupt handler like sched_ithd()
287  * which will only run if the current thread is not in a critical section,
288  * so we optimize the priority check a bit.
289  */
290 void
291 lwkt_preempt(struct thread *ntd, int id)
292 {
293     struct thread *td = curthread;
294
295     crit_enter();       /* YYY token */
296     if (ntd->td_preempted == NULL && 
297         (ntd->td_pri & TDPRI_MASK) > (td->td_pri & TDPRI_MASK)
298     ) {
299         ++preempt_hit;
300         ntd->td_preempted = td;
301         td->td_flags |= TDF_PREEMPTED;
302         ntd->td_pri += TDPRI_CRIT;
303         while (td->td_flags & TDF_PREEMPTED)
304             ntd->td_switch(ntd);
305     } else {
306         ++preempt_miss;
307     }
308     crit_exit_noyield();
309 }
310
311 /*
312  * Yield our thread while higher priority threads are pending.  This is
313  * typically called when we leave a critical section but it can be safely
314  * called while we are in a critical section.
315  *
316  * This function will not generally yield to equal priority threads but it
317  * can occur as a side effect.  Note that lwkt_switch() is called from
318  * inside the critical section to pervent its own crit_exit() from reentering
319  * lwkt_yield_quick().
320  *
321  * gd_reqpri indicates that *something* changed, e.g. an interrupt or softint
322  * came along but was blocked and made pending.
323  *
324  * (self contained on a per cpu basis)
325  */
326 void
327 lwkt_yield_quick(void)
328 {
329     thread_t td = curthread;
330
331     if ((td->td_pri & TDPRI_MASK) < mycpu->gd_reqpri) {
332         mycpu->gd_reqpri = 0;
333         splz();
334     }
335
336     /*
337      * YYY enabling will cause wakeup() to task-switch, which really
338      * confused the old 4.x code.  This is a good way to simulate
339      * preemption and MP without actually doing preemption or MP, because a
340      * lot of code assumes that wakeup() does not block.
341      */
342     if (untimely_switch && mycpu->gd_intr_nesting_level == 0) {
343         crit_enter();
344         /*
345          * YYY temporary hacks until we disassociate the userland scheduler
346          * from the LWKT scheduler.
347          */
348         if (td->td_flags & TDF_RUNQ) {
349             lwkt_switch();              /* will not reenter yield function */
350         } else {
351             lwkt_schedule_self();       /* make sure we are scheduled */
352             lwkt_switch();              /* will not reenter yield function */
353             lwkt_deschedule_self();     /* make sure we are descheduled */
354         }
355         crit_exit_noyield();
356     }
357 }
358
359 /*
360  * This implements a normal yield which, unlike _quick, will yield to equal
361  * priority threads as well.  Note that gd_reqpri tests will be handled by
362  * the crit_exit() call in lwkt_switch().
363  *
364  * (self contained on a per cpu basis)
365  */
366 void
367 lwkt_yield(void)
368 {
369     lwkt_schedule_self();
370     lwkt_switch();
371 }
372
373 /*
374  * Schedule a thread to run.  As the current thread we can always safely
375  * schedule ourselves, and a shortcut procedure is provided for that
376  * function.
377  *
378  * (non-blocking, self contained on a per cpu basis)
379  */
380 void
381 lwkt_schedule_self(void)
382 {
383     thread_t td = curthread;
384
385     crit_enter();
386     KASSERT(td->td_wait == NULL, ("lwkt_schedule_self(): td_wait not NULL!"));
387     _lwkt_enqueue(td);
388     crit_exit();
389 }
390
391 /*
392  * Generic schedule.  Possibly schedule threads belonging to other cpus and
393  * deal with threads that might be blocked on a wait queue.
394  *
395  * This function will queue requests asynchronously when possible, but may
396  * block if no request structures are available.  Upon return the caller
397  * should note that the scheduling request may not yet have been processed
398  * by the target cpu.
399  *
400  * YYY this is one of the best places to implement any load balancing code.
401  * Load balancing can be accomplished by requesting other sorts of actions
402  * for the thread in question.
403  */
404 void
405 lwkt_schedule(thread_t td)
406 {
407     crit_enter();
408     if (td == curthread) {
409         _lwkt_enqueue(td);
410     } else {
411         lwkt_wait_t w;
412
413         /*
414          * If the thread is on a wait list we have to send our scheduling
415          * request to the owner of the wait structure.  Otherwise we send
416          * the scheduling request to the cpu owning the thread.  Races
417          * are ok, the target will forward the message as necessary (the
418          * message may chase the thread around before it finally gets
419          * acted upon).
420          *
421          * (remember, wait structures use stable storage)
422          */
423         if ((w = td->td_wait) != NULL) {
424             if (lwkt_havetoken(&w->wa_token)) {
425                 TAILQ_REMOVE(&w->wa_waitq, td, td_threadq);
426                 --w->wa_count;
427                 td->td_wait = NULL;
428                 if (td->td_cpu == mycpu->gd_cpuid) {
429                     _lwkt_enqueue(td);
430                 } else {
431                     panic("lwkt_schedule: cpu mismatch1");
432 #if 0
433                     lwkt_cpu_msg_union_t msg = lwkt_getcpumsg();
434                     initScheduleReqMsg_Wait(&msg.mu_SchedReq, td, w);
435                     cpu_sendnormsg(&msg.mu_Msg);
436 #endif
437                 }
438             } else {
439                 panic("lwkt_schedule: cpu mismatch2");
440 #if 0
441                 lwkt_cpu_msg_union_t msg = lwkt_getcpumsg();
442                 initScheduleReqMsg_Wait(&msg.mu_SchedReq, td, w);
443                 cpu_sendnormsg(&msg.mu_Msg);
444 #endif
445             }
446         } else {
447             /*
448              * If the wait structure is NULL and we own the thread, there
449              * is no race (since we are in a critical section).  If we
450              * do not own the thread there might be a race but the
451              * target cpu will deal with it.
452              */
453             if (td->td_cpu == mycpu->gd_cpuid) {
454                 _lwkt_enqueue(td);
455             } else {
456                 panic("lwkt_schedule: cpu mismatch3");
457 #if 0
458                 lwkt_cpu_msg_union_t msg = lwkt_getcpumsg();
459                 initScheduleReqMsg_Thread(&msg.mu_SchedReq, td);
460                 cpu_sendnormsg(&msg.mu_Msg);
461 #endif
462             }
463         }
464     }
465     crit_exit();
466 }
467
468 /*
469  * Deschedule a thread.
470  *
471  * (non-blocking, self contained on a per cpu basis)
472  */
473 void
474 lwkt_deschedule_self(void)
475 {
476     thread_t td = curthread;
477
478     crit_enter();
479     KASSERT(td->td_wait == NULL, ("lwkt_schedule_self(): td_wait not NULL!"));
480     _lwkt_dequeue(td);
481     crit_exit();
482 }
483
484 /*
485  * Generic deschedule.  Descheduling threads other then your own should be
486  * done only in carefully controlled circumstances.  Descheduling is 
487  * asynchronous.  
488  *
489  * This function may block if the cpu has run out of messages.
490  */
491 void
492 lwkt_deschedule(thread_t td)
493 {
494     crit_enter();
495     if (td == curthread) {
496         _lwkt_dequeue(td);
497     } else {
498         if (td->td_cpu == mycpu->gd_cpuid) {
499             _lwkt_dequeue(td);
500         } else {
501             panic("lwkt_deschedule: cpu mismatch");
502 #if 0
503             lwkt_cpu_msg_union_t msg = lwkt_getcpumsg();
504             initDescheduleReqMsg_Thread(&msg.mu_DeschedReq, td);
505             cpu_sendnormsg(&msg.mu_Msg);
506 #endif
507         }
508     }
509     crit_exit();
510 }
511
512 /*
513  * Set the target thread's priority.  This routine does not automatically
514  * switch to a higher priority thread, LWKT threads are not designed for
515  * continuous priority changes.  Yield if you want to switch.
516  *
517  * We have to retain the critical section count which uses the high bits
518  * of the td_pri field.
519  */
520 void
521 lwkt_setpri(thread_t td, int pri)
522 {
523     KKASSERT(pri >= 0 && pri <= TDPRI_MAX);
524     crit_enter();
525     if (td->td_flags & TDF_RUNQ) {
526         _lwkt_dequeue(td);
527         td->td_pri = (td->td_pri & ~TDPRI_MASK) + pri;
528         _lwkt_enqueue(td);
529     } else {
530         td->td_pri = (td->td_pri & ~TDPRI_MASK) + pri;
531     }
532     crit_exit();
533 }
534
535 struct proc *
536 lwkt_preempted_proc(void)
537 {
538     struct thread *td = curthread;
539     while (td->td_preempted)
540         td = td->td_preempted;
541     return(td->td_proc);
542 }
543
544
545 /*
546  * This function deschedules the current thread and blocks on the specified
547  * wait queue.  We obtain ownership of the wait queue in order to block
548  * on it.  A generation number is used to interlock the wait queue in case
549  * it gets signalled while we are blocked waiting on the token.
550  *
551  * Note: alternatively we could dequeue our thread and then message the
552  * target cpu owning the wait queue.  YYY implement as sysctl.
553  *
554  * Note: wait queue signals normally ping-pong the cpu as an optimization.
555  */
556 void
557 lwkt_block(lwkt_wait_t w, const char *wmesg, int *gen)
558 {
559     thread_t td = curthread;
560
561     lwkt_gettoken(&w->wa_token);
562     if (w->wa_gen == *gen) {
563         _lwkt_dequeue(td);
564         TAILQ_INSERT_TAIL(&w->wa_waitq, td, td_threadq);
565         ++w->wa_count;
566         td->td_wait = w;
567         td->td_wmesg = wmesg;
568         lwkt_switch();
569     }
570     /* token might be lost, doesn't matter for gen update */
571     *gen = w->wa_gen;
572     lwkt_reltoken(&w->wa_token);
573 }
574
575 /*
576  * Signal a wait queue.  We gain ownership of the wait queue in order to
577  * signal it.  Once a thread is removed from the wait queue we have to
578  * deal with the cpu owning the thread.
579  *
580  * Note: alternatively we could message the target cpu owning the wait
581  * queue.  YYY implement as sysctl.
582  */
583 void
584 lwkt_signal(lwkt_wait_t w)
585 {
586     thread_t td;
587     int count;
588
589     lwkt_gettoken(&w->wa_token);
590     ++w->wa_gen;
591     count = w->wa_count;
592     while ((td = TAILQ_FIRST(&w->wa_waitq)) != NULL && count) {
593         --count;
594         --w->wa_count;
595         TAILQ_REMOVE(&w->wa_waitq, td, td_threadq);
596         td->td_wait = NULL;
597         td->td_wmesg = NULL;
598         if (td->td_cpu == mycpu->gd_cpuid) {
599             _lwkt_enqueue(td);
600         } else {
601 #if 0
602             lwkt_cpu_msg_union_t msg = lwkt_getcpumsg();
603             initScheduleReqMsg_Thread(&msg.mu_SchedReq, td);
604             cpu_sendnormsg(&msg.mu_Msg);
605 #endif
606             panic("lwkt_signal: cpu mismatch");
607         }
608         lwkt_regettoken(&w->wa_token);
609     }
610     lwkt_reltoken(&w->wa_token);
611 }
612
613 /*
614  * Aquire ownership of a token
615  *
616  * Aquire ownership of a token.  The token may have spl and/or critical
617  * section side effects, depending on its purpose.  These side effects
618  * guarentee that you will maintain ownership of the token as long as you
619  * do not block.  If you block you may lose access to the token (but you
620  * must still release it even if you lose your access to it).
621  *
622  * Note that the spl and critical section characteristics of a token
623  * may not be changed once the token has been initialized.
624  */
625 void
626 lwkt_gettoken(lwkt_token_t tok)
627 {
628     /*
629      * Prevent preemption so the token can't be taken away from us once
630      * we gain ownership of it.  Use a synchronous request which might
631      * block.  The request will be forwarded as necessary playing catchup
632      * to the token.
633      */
634     crit_enter();
635 #if 0
636     while (tok->t_cpu != mycpu->gd_cpuid) {
637         lwkt_cpu_msg_union msg;
638         initTokenReqMsg(&msg.mu_TokenReq);
639         cpu_domsg(&msg);
640     }
641 #endif
642     /*
643      * leave us in a critical section on return.  This will be undone
644      * by lwkt_reltoken()
645      */
646 }
647
648 /*
649  * Release your ownership of a token.  Releases must occur in reverse
650  * order to aquisitions, eventually so priorities can be unwound properly
651  * like SPLs.  At the moment the actual implemention doesn't care.
652  *
653  * We can safely hand a token that we own to another cpu without notifying
654  * it, but once we do we can't get it back without requesting it (unless
655  * the other cpu hands it back to us before we check).
656  *
657  * We might have lost the token, so check that.
658  */
659 void
660 lwkt_reltoken(lwkt_token_t tok)
661 {
662     if (tok->t_cpu == mycpu->gd_cpuid) {
663         tok->t_cpu = tok->t_reqcpu;
664     }
665     crit_exit();
666 }
667
668 /*
669  * Reaquire a token that might have been lost.  Returns 1 if we blocked
670  * while reaquiring the token (meaning that you might have lost other
671  * tokens you held when you made this call), return 0 if we did not block.
672  */
673 int
674 lwkt_regettoken(lwkt_token_t tok)
675 {
676 #if 0
677     if (tok->t_cpu != mycpu->gd_cpuid) {
678         while (tok->t_cpu != mycpu->gd_cpuid) {
679             lwkt_cpu_msg_union msg;
680             initTokenReqMsg(&msg.mu_TokenReq);
681             cpu_domsg(&msg);
682         }
683         return(1);
684     }
685 #endif
686     return(0);
687 }
688
689 /*
690  * Create a kernel process/thread/whatever.  It shares it's address space
691  * with proc0 - ie: kernel only.
692  *
693  * XXX should be renamed to lwkt_create()
694  */
695 int
696 lwkt_create(void (*func)(void *), void *arg,
697     struct thread **tdp, struct thread *template, int tdflags,
698     const char *fmt, ...)
699 {
700     struct thread *td;
701     va_list ap;
702
703     td = *tdp = lwkt_alloc_thread(template);
704     cpu_set_thread_handler(td, kthread_exit, func, arg);
705     td->td_flags |= TDF_VERBOSE | tdflags;
706
707     /*
708      * Set up arg0 for 'ps' etc
709      */
710     va_start(ap, fmt);
711     vsnprintf(td->td_comm, sizeof(td->td_comm), fmt, ap);
712     va_end(ap);
713
714     /*
715      * Schedule the thread to run
716      */
717     if ((td->td_flags & TDF_STOPREQ) == 0)
718         lwkt_schedule(td);
719     else
720         td->td_flags &= ~TDF_STOPREQ;
721     return 0;
722 }
723
724 /*
725  * Destroy an LWKT thread.   Warning!  This function is not called when
726  * a process exits, cpu_proc_exit() directly calls cpu_thread_exit() and
727  * uses a different reaping mechanism.
728  */
729 void
730 lwkt_exit(void)
731 {
732     thread_t td = curthread;
733
734     if (td->td_flags & TDF_VERBOSE)
735         printf("kthread %p %s has exited\n", td, td->td_comm);
736     crit_enter();
737     lwkt_deschedule_self();
738     ++mycpu->gd_tdfreecount;
739     TAILQ_INSERT_TAIL(&mycpu->gd_tdfreeq, td, td_threadq);
740     cpu_thread_exit();
741 }
742
743 /*
744  * Create a kernel process/thread/whatever.  It shares it's address space
745  * with proc0 - ie: kernel only.  5.x compatible.
746  */
747 int
748 kthread_create(void (*func)(void *), void *arg,
749     struct thread **tdp, const char *fmt, ...)
750 {
751     struct thread *td;
752     va_list ap;
753
754     td = *tdp = lwkt_alloc_thread(NULL);
755     cpu_set_thread_handler(td, kthread_exit, func, arg);
756     td->td_flags |= TDF_VERBOSE;
757
758     /*
759      * Set up arg0 for 'ps' etc
760      */
761     va_start(ap, fmt);
762     vsnprintf(td->td_comm, sizeof(td->td_comm), fmt, ap);
763     va_end(ap);
764
765     /*
766      * Schedule the thread to run
767      */
768     lwkt_schedule(td);
769     return 0;
770 }
771
772 /*
773  * Destroy an LWKT thread.   Warning!  This function is not called when
774  * a process exits, cpu_proc_exit() directly calls cpu_thread_exit() and
775  * uses a different reaping mechanism.
776  *
777  * XXX duplicates lwkt_exit()
778  */
779 void
780 kthread_exit(void)
781 {
782     lwkt_exit();
783 }
784