Add two KTR (kernel trace) options: KTR_GIANT_CONTENTION and
[dragonfly.git] / sys / kern / lwkt_thread.c
1 /*
2  * Copyright (c) 2003,2004 The DragonFly Project.  All rights reserved.
3  * 
4  * This code is derived from software contributed to The DragonFly Project
5  * by Matthew Dillon <dillon@backplane.com>
6  * 
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in
15  *    the documentation and/or other materials provided with the
16  *    distribution.
17  * 3. Neither the name of The DragonFly Project nor the names of its
18  *    contributors may be used to endorse or promote products derived
19  *    from this software without specific, prior written permission.
20  * 
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
25  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
27  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
31  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  * 
34  * $DragonFly: src/sys/kern/lwkt_thread.c,v 1.98 2006/05/29 07:29:14 dillon Exp $
35  */
36
37 /*
38  * Each cpu in a system has its own self-contained light weight kernel
39  * thread scheduler, which means that generally speaking we only need
40  * to use a critical section to avoid problems.  Foreign thread 
41  * scheduling is queued via (async) IPIs.
42  */
43
44 #ifdef _KERNEL
45
46 #include <sys/param.h>
47 #include <sys/systm.h>
48 #include <sys/kernel.h>
49 #include <sys/proc.h>
50 #include <sys/rtprio.h>
51 #include <sys/queue.h>
52 #include <sys/sysctl.h>
53 #include <sys/kthread.h>
54 #include <machine/cpu.h>
55 #include <sys/lock.h>
56 #include <sys/caps.h>
57 #include <sys/spinlock.h>
58 #include <sys/ktr.h>
59
60 #include <sys/thread2.h>
61 #include <sys/spinlock2.h>
62
63 #include <vm/vm.h>
64 #include <vm/vm_param.h>
65 #include <vm/vm_kern.h>
66 #include <vm/vm_object.h>
67 #include <vm/vm_page.h>
68 #include <vm/vm_map.h>
69 #include <vm/vm_pager.h>
70 #include <vm/vm_extern.h>
71 #include <vm/vm_zone.h>
72
73 #include <machine/stdarg.h>
74 #include <machine/ipl.h>
75 #include <machine/smp.h>
76
77 #else
78
79 #include <sys/stdint.h>
80 #include <libcaps/thread.h>
81 #include <sys/thread.h>
82 #include <sys/msgport.h>
83 #include <sys/errno.h>
84 #include <libcaps/globaldata.h>
85 #include <machine/cpufunc.h>
86 #include <sys/thread2.h>
87 #include <sys/msgport2.h>
88 #include <stdio.h>
89 #include <stdlib.h>
90 #include <string.h>
91 #include <machine/lock.h>
92 #include <machine/atomic.h>
93 #include <machine/cpu.h>
94
95 #endif
96
97 static int untimely_switch = 0;
98 #ifdef  INVARIANTS
99 static int panic_on_cscount = 0;
100 #endif
101 static __int64_t switch_count = 0;
102 static __int64_t preempt_hit = 0;
103 static __int64_t preempt_miss = 0;
104 static __int64_t preempt_weird = 0;
105 static __int64_t token_contention_count = 0;
106 static __int64_t mplock_contention_count = 0;
107
108 #ifdef _KERNEL
109
110 SYSCTL_INT(_lwkt, OID_AUTO, untimely_switch, CTLFLAG_RW, &untimely_switch, 0, "");
111 #ifdef  INVARIANTS
112 SYSCTL_INT(_lwkt, OID_AUTO, panic_on_cscount, CTLFLAG_RW, &panic_on_cscount, 0, "");
113 #endif
114 SYSCTL_QUAD(_lwkt, OID_AUTO, switch_count, CTLFLAG_RW, &switch_count, 0, "");
115 SYSCTL_QUAD(_lwkt, OID_AUTO, preempt_hit, CTLFLAG_RW, &preempt_hit, 0, "");
116 SYSCTL_QUAD(_lwkt, OID_AUTO, preempt_miss, CTLFLAG_RW, &preempt_miss, 0, "");
117 SYSCTL_QUAD(_lwkt, OID_AUTO, preempt_weird, CTLFLAG_RW, &preempt_weird, 0, "");
118 #ifdef  INVARIANTS
119 SYSCTL_QUAD(_lwkt, OID_AUTO, token_contention_count, CTLFLAG_RW,
120         &token_contention_count, 0, "spinning due to token contention");
121 SYSCTL_QUAD(_lwkt, OID_AUTO, mplock_contention_count, CTLFLAG_RW,
122         &mplock_contention_count, 0, "spinning due to MPLOCK contention");
123 #endif
124 #endif
125
126 /*
127  * Kernel Trace
128  */
129 #ifdef _KERNEL
130
131 #if !defined(KTR_GIANT_CONTENTION)
132 #define KTR_GIANT_CONTENTION    KTR_ALL
133 #endif
134
135 KTR_INFO_MASTER(giant);
136 KTR_INFO(KTR_GIANT_CONTENTION, giant, beg, 0, "thread=%p", sizeof(void *));
137 KTR_INFO(KTR_GIANT_CONTENTION, giant, end, 1, "thread=%p", sizeof(void *));
138
139 #define loggiant(name)  KTR_LOG(giant_ ## name, curthread)
140
141 #endif
142
143 /*
144  * These helper procedures handle the runq, they can only be called from
145  * within a critical section.
146  *
147  * WARNING!  Prior to SMP being brought up it is possible to enqueue and
148  * dequeue threads belonging to other cpus, so be sure to use td->td_gd
149  * instead of 'mycpu' when referencing the globaldata structure.   Once
150  * SMP live enqueuing and dequeueing only occurs on the current cpu.
151  */
152 static __inline
153 void
154 _lwkt_dequeue(thread_t td)
155 {
156     if (td->td_flags & TDF_RUNQ) {
157         int nq = td->td_pri & TDPRI_MASK;
158         struct globaldata *gd = td->td_gd;
159
160         td->td_flags &= ~TDF_RUNQ;
161         TAILQ_REMOVE(&gd->gd_tdrunq[nq], td, td_threadq);
162         /* runqmask is passively cleaned up by the switcher */
163     }
164 }
165
166 static __inline
167 void
168 _lwkt_enqueue(thread_t td)
169 {
170     if ((td->td_flags & (TDF_RUNQ|TDF_MIGRATING|TDF_TSLEEPQ|TDF_BLOCKQ)) == 0) {
171         int nq = td->td_pri & TDPRI_MASK;
172         struct globaldata *gd = td->td_gd;
173
174         td->td_flags |= TDF_RUNQ;
175         TAILQ_INSERT_TAIL(&gd->gd_tdrunq[nq], td, td_threadq);
176         gd->gd_runqmask |= 1 << nq;
177     }
178 }
179
180 /*
181  * Schedule a thread to run.  As the current thread we can always safely
182  * schedule ourselves, and a shortcut procedure is provided for that
183  * function.
184  *
185  * (non-blocking, self contained on a per cpu basis)
186  */
187 void
188 lwkt_schedule_self(thread_t td)
189 {
190     crit_enter_quick(td);
191     KASSERT(td->td_wait == NULL, ("lwkt_schedule_self(): td_wait not NULL!"));
192     KASSERT(td != &td->td_gd->gd_idlethread, ("lwkt_schedule_self(): scheduling gd_idlethread is illegal!"));
193     KKASSERT(td->td_proc == NULL || (td->td_proc->p_flag & P_ONRUNQ) == 0);
194     _lwkt_enqueue(td);
195     crit_exit_quick(td);
196 }
197
198 /*
199  * Deschedule a thread.
200  *
201  * (non-blocking, self contained on a per cpu basis)
202  */
203 void
204 lwkt_deschedule_self(thread_t td)
205 {
206     crit_enter_quick(td);
207     KASSERT(td->td_wait == NULL, ("lwkt_schedule_self(): td_wait not NULL!"));
208     _lwkt_dequeue(td);
209     crit_exit_quick(td);
210 }
211
212 #ifdef _KERNEL
213
214 /*
215  * LWKTs operate on a per-cpu basis
216  *
217  * WARNING!  Called from early boot, 'mycpu' may not work yet.
218  */
219 void
220 lwkt_gdinit(struct globaldata *gd)
221 {
222     int i;
223
224     for (i = 0; i < sizeof(gd->gd_tdrunq)/sizeof(gd->gd_tdrunq[0]); ++i)
225         TAILQ_INIT(&gd->gd_tdrunq[i]);
226     gd->gd_runqmask = 0;
227     TAILQ_INIT(&gd->gd_tdallq);
228 }
229
230 #endif /* _KERNEL */
231
232 /*
233  * Initialize a thread wait structure prior to first use.
234  *
235  * NOTE!  called from low level boot code, we cannot do anything fancy!
236  */
237 void
238 lwkt_wait_init(lwkt_wait_t w)
239 {
240     spin_init(&w->wa_spinlock);
241     TAILQ_INIT(&w->wa_waitq);
242     w->wa_gen = 0;
243     w->wa_count = 0;
244 }
245
246 /*
247  * Create a new thread.  The thread must be associated with a process context
248  * or LWKT start address before it can be scheduled.  If the target cpu is
249  * -1 the thread will be created on the current cpu.
250  *
251  * If you intend to create a thread without a process context this function
252  * does everything except load the startup and switcher function.
253  */
254 thread_t
255 lwkt_alloc_thread(struct thread *td, int stksize, int cpu, int flags)
256 {
257     void *stack;
258     globaldata_t gd = mycpu;
259
260     if (td == NULL) {
261         crit_enter_gd(gd);
262         if (gd->gd_tdfreecount > 0) {
263             --gd->gd_tdfreecount;
264             td = TAILQ_FIRST(&gd->gd_tdfreeq);
265             KASSERT(td != NULL && (td->td_flags & TDF_RUNNING) == 0,
266                 ("lwkt_alloc_thread: unexpected NULL or corrupted td"));
267             TAILQ_REMOVE(&gd->gd_tdfreeq, td, td_threadq);
268             crit_exit_gd(gd);
269             flags |= td->td_flags & (TDF_ALLOCATED_STACK|TDF_ALLOCATED_THREAD);
270         } else {
271             crit_exit_gd(gd);
272 #ifdef _KERNEL
273             td = zalloc(thread_zone);
274 #else
275             td = malloc(sizeof(struct thread));
276 #endif
277             td->td_kstack = NULL;
278             td->td_kstack_size = 0;
279             flags |= TDF_ALLOCATED_THREAD;
280         }
281     }
282     if ((stack = td->td_kstack) != NULL && td->td_kstack_size != stksize) {
283         if (flags & TDF_ALLOCATED_STACK) {
284 #ifdef _KERNEL
285             kmem_free(kernel_map, (vm_offset_t)stack, td->td_kstack_size);
286 #else
287             libcaps_free_stack(stack, td->td_kstack_size);
288 #endif
289             stack = NULL;
290         }
291     }
292     if (stack == NULL) {
293 #ifdef _KERNEL
294         stack = (void *)kmem_alloc(kernel_map, stksize);
295 #else
296         stack = libcaps_alloc_stack(stksize);
297 #endif
298         flags |= TDF_ALLOCATED_STACK;
299     }
300     if (cpu < 0)
301         lwkt_init_thread(td, stack, stksize, flags, mycpu);
302     else
303         lwkt_init_thread(td, stack, stksize, flags, globaldata_find(cpu));
304     return(td);
305 }
306
307 #ifdef _KERNEL
308
309 /*
310  * Initialize a preexisting thread structure.  This function is used by
311  * lwkt_alloc_thread() and also used to initialize the per-cpu idlethread.
312  *
313  * All threads start out in a critical section at a priority of
314  * TDPRI_KERN_DAEMON.  Higher level code will modify the priority as
315  * appropriate.  This function may send an IPI message when the 
316  * requested cpu is not the current cpu and consequently gd_tdallq may
317  * not be initialized synchronously from the point of view of the originating
318  * cpu.
319  *
320  * NOTE! we have to be careful in regards to creating threads for other cpus
321  * if SMP has not yet been activated.
322  */
323 #ifdef SMP
324
325 static void
326 lwkt_init_thread_remote(void *arg)
327 {
328     thread_t td = arg;
329
330     /*
331      * Protected by critical section held by IPI dispatch
332      */
333     TAILQ_INSERT_TAIL(&td->td_gd->gd_tdallq, td, td_allq);
334 }
335
336 #endif
337
338 void
339 lwkt_init_thread(thread_t td, void *stack, int stksize, int flags,
340                 struct globaldata *gd)
341 {
342     globaldata_t mygd = mycpu;
343
344     bzero(td, sizeof(struct thread));
345     td->td_kstack = stack;
346     td->td_kstack_size = stksize;
347     td->td_flags = flags;
348     td->td_gd = gd;
349     td->td_pri = TDPRI_KERN_DAEMON + TDPRI_CRIT;
350 #ifdef SMP
351     if ((flags & TDF_MPSAFE) == 0)
352         td->td_mpcount = 1;
353 #endif
354     lwkt_initport(&td->td_msgport, td);
355     pmap_init_thread(td);
356 #ifdef SMP
357     /*
358      * Normally initializing a thread for a remote cpu requires sending an
359      * IPI.  However, the idlethread is setup before the other cpus are
360      * activated so we have to treat it as a special case.  XXX manipulation
361      * of gd_tdallq requires the BGL.
362      */
363     if (gd == mygd || td == &gd->gd_idlethread) {
364         crit_enter_gd(mygd);
365         TAILQ_INSERT_TAIL(&gd->gd_tdallq, td, td_allq);
366         crit_exit_gd(mygd);
367     } else {
368         lwkt_send_ipiq(gd, lwkt_init_thread_remote, td);
369     }
370 #else
371     crit_enter_gd(mygd);
372     TAILQ_INSERT_TAIL(&gd->gd_tdallq, td, td_allq);
373     crit_exit_gd(mygd);
374 #endif
375 }
376
377 #endif /* _KERNEL */
378
379 void
380 lwkt_set_comm(thread_t td, const char *ctl, ...)
381 {
382     __va_list va;
383
384     __va_start(va, ctl);
385     vsnprintf(td->td_comm, sizeof(td->td_comm), ctl, va);
386     __va_end(va);
387 }
388
389 void
390 lwkt_hold(thread_t td)
391 {
392     ++td->td_refs;
393 }
394
395 void
396 lwkt_rele(thread_t td)
397 {
398     KKASSERT(td->td_refs > 0);
399     --td->td_refs;
400 }
401
402 #ifdef _KERNEL
403
404 void
405 lwkt_wait_free(thread_t td)
406 {
407     while (td->td_refs)
408         tsleep(td, 0, "tdreap", hz);
409 }
410
411 #endif
412
413 void
414 lwkt_free_thread(thread_t td)
415 {
416     struct globaldata *gd = mycpu;
417
418     KASSERT((td->td_flags & TDF_RUNNING) == 0,
419         ("lwkt_free_thread: did not exit! %p", td));
420
421     crit_enter_gd(gd);
422     TAILQ_REMOVE(&td->td_gd->gd_tdallq, td, td_allq); /* Protected by BGL */
423     if (gd->gd_tdfreecount < CACHE_NTHREADS &&
424         (td->td_flags & TDF_ALLOCATED_THREAD)
425     ) {
426         ++gd->gd_tdfreecount;
427         TAILQ_INSERT_HEAD(&gd->gd_tdfreeq, td, td_threadq);
428         crit_exit_gd(gd);
429     } else {
430         crit_exit_gd(gd);
431         if (td->td_kstack && (td->td_flags & TDF_ALLOCATED_STACK)) {
432 #ifdef _KERNEL
433             kmem_free(kernel_map, (vm_offset_t)td->td_kstack, td->td_kstack_size);
434 #else
435             libcaps_free_stack(td->td_kstack, td->td_kstack_size);
436 #endif
437             /* gd invalid */
438             td->td_kstack = NULL;
439             td->td_kstack_size = 0;
440         }
441         if (td->td_flags & TDF_ALLOCATED_THREAD) {
442 #ifdef _KERNEL
443             zfree(thread_zone, td);
444 #else
445             free(td);
446 #endif
447         }
448     }
449 }
450
451
452 /*
453  * Switch to the next runnable lwkt.  If no LWKTs are runnable then 
454  * switch to the idlethread.  Switching must occur within a critical
455  * section to avoid races with the scheduling queue.
456  *
457  * We always have full control over our cpu's run queue.  Other cpus
458  * that wish to manipulate our queue must use the cpu_*msg() calls to
459  * talk to our cpu, so a critical section is all that is needed and
460  * the result is very, very fast thread switching.
461  *
462  * The LWKT scheduler uses a fixed priority model and round-robins at
463  * each priority level.  User process scheduling is a totally
464  * different beast and LWKT priorities should not be confused with
465  * user process priorities.
466  *
467  * The MP lock may be out of sync with the thread's td_mpcount.  lwkt_switch()
468  * cleans it up.  Note that the td_switch() function cannot do anything that
469  * requires the MP lock since the MP lock will have already been setup for
470  * the target thread (not the current thread).  It's nice to have a scheduler
471  * that does not need the MP lock to work because it allows us to do some
472  * really cool high-performance MP lock optimizations.
473  *
474  * PREEMPTION NOTE: Preemption occurs via lwkt_preempt().  lwkt_switch()
475  * is not called by the current thread in the preemption case, only when
476  * the preempting thread blocks (in order to return to the original thread).
477  */
478 void
479 lwkt_switch(void)
480 {
481     globaldata_t gd = mycpu;
482     thread_t td = gd->gd_curthread;
483     thread_t ntd;
484 #ifdef SMP
485     int mpheld;
486 #endif
487
488     /*
489      * Switching from within a 'fast' (non thread switched) interrupt or IPI
490      * is illegal.  However, we may have to do it anyway if we hit a fatal
491      * kernel trap or we have paniced.
492      *
493      * If this case occurs save and restore the interrupt nesting level.
494      */
495     if (gd->gd_intr_nesting_level) {
496         int savegdnest;
497         int savegdtrap;
498
499         if (gd->gd_trap_nesting_level == 0 && panicstr == NULL) {
500             panic("lwkt_switch: cannot switch from within "
501                   "a fast interrupt, yet, td %p\n", td);
502         } else {
503             savegdnest = gd->gd_intr_nesting_level;
504             savegdtrap = gd->gd_trap_nesting_level;
505             gd->gd_intr_nesting_level = 0;
506             gd->gd_trap_nesting_level = 0;
507             if ((td->td_flags & TDF_PANICWARN) == 0) {
508                 td->td_flags |= TDF_PANICWARN;
509                 printf("Warning: thread switch from interrupt or IPI, "
510                         "thread %p (%s)\n", td, td->td_comm);
511 #ifdef DDB
512                 db_print_backtrace();
513 #endif
514             }
515             lwkt_switch();
516             gd->gd_intr_nesting_level = savegdnest;
517             gd->gd_trap_nesting_level = savegdtrap;
518             return;
519         }
520     }
521
522     /*
523      * Passive release (used to transition from user to kernel mode
524      * when we block or switch rather then when we enter the kernel).
525      * This function is NOT called if we are switching into a preemption
526      * or returning from a preemption.  Typically this causes us to lose
527      * our current process designation (if we have one) and become a true
528      * LWKT thread, and may also hand the current process designation to
529      * another process and schedule thread.
530      */
531     if (td->td_release)
532             td->td_release(td);
533
534     crit_enter_gd(gd);
535 #ifdef SMP
536     if (td->td_toks)
537             lwkt_relalltokens(td);
538 #endif
539
540     /*
541      * We had better not be holding any spin locks, but don't get into an
542      * endless panic loop.
543      */
544     KASSERT(gd->gd_spinlocks_rd == 0 || panicstr != NULL, 
545             ("lwkt_switch: still holding %d shared spinlocks!", 
546              gd->gd_spinlocks_rd));
547     KASSERT(gd->gd_spinlocks_wr == 0 || panicstr != NULL, 
548             ("lwkt_switch: still holding %d exclusive spinlocks!",
549              gd->gd_spinlocks_wr));
550
551
552 #ifdef SMP
553     /*
554      * td_mpcount cannot be used to determine if we currently hold the
555      * MP lock because get_mplock() will increment it prior to attempting
556      * to get the lock, and switch out if it can't.  Our ownership of 
557      * the actual lock will remain stable while we are in a critical section
558      * (but, of course, another cpu may own or release the lock so the
559      * actual value of mp_lock is not stable).
560      */
561     mpheld = MP_LOCK_HELD();
562 #ifdef  INVARIANTS
563     if (td->td_cscount) {
564         printf("Diagnostic: attempt to switch while mastering cpusync: %p\n",
565                 td);
566         if (panic_on_cscount)
567             panic("switching while mastering cpusync");
568     }
569 #endif
570 #endif
571     if ((ntd = td->td_preempted) != NULL) {
572         /*
573          * We had preempted another thread on this cpu, resume the preempted
574          * thread.  This occurs transparently, whether the preempted thread
575          * was scheduled or not (it may have been preempted after descheduling
576          * itself). 
577          *
578          * We have to setup the MP lock for the original thread after backing
579          * out the adjustment that was made to curthread when the original
580          * was preempted.
581          */
582         KKASSERT(ntd->td_flags & TDF_PREEMPT_LOCK);
583 #ifdef SMP
584         if (ntd->td_mpcount && mpheld == 0) {
585             panic("MPLOCK NOT HELD ON RETURN: %p %p %d %d",
586                td, ntd, td->td_mpcount, ntd->td_mpcount);
587         }
588         if (ntd->td_mpcount) {
589             td->td_mpcount -= ntd->td_mpcount;
590             KKASSERT(td->td_mpcount >= 0);
591         }
592 #endif
593         ntd->td_flags |= TDF_PREEMPT_DONE;
594
595         /*
596          * XXX.  The interrupt may have woken a thread up, we need to properly
597          * set the reschedule flag if the originally interrupted thread is at
598          * a lower priority.
599          */
600         if (gd->gd_runqmask > (2 << (ntd->td_pri & TDPRI_MASK)) - 1)
601             need_lwkt_resched();
602         /* YYY release mp lock on switchback if original doesn't need it */
603     } else {
604         /*
605          * Priority queue / round-robin at each priority.  Note that user
606          * processes run at a fixed, low priority and the user process
607          * scheduler deals with interactions between user processes
608          * by scheduling and descheduling them from the LWKT queue as
609          * necessary.
610          *
611          * We have to adjust the MP lock for the target thread.  If we 
612          * need the MP lock and cannot obtain it we try to locate a
613          * thread that does not need the MP lock.  If we cannot, we spin
614          * instead of HLT.
615          *
616          * A similar issue exists for the tokens held by the target thread.
617          * If we cannot obtain ownership of the tokens we cannot immediately
618          * schedule the thread.
619          */
620
621         /*
622          * If an LWKT reschedule was requested, well that is what we are
623          * doing now so clear it.
624          */
625         clear_lwkt_resched();
626 again:
627         if (gd->gd_runqmask) {
628             int nq = bsrl(gd->gd_runqmask);
629             if ((ntd = TAILQ_FIRST(&gd->gd_tdrunq[nq])) == NULL) {
630                 gd->gd_runqmask &= ~(1 << nq);
631                 goto again;
632             }
633 #ifdef SMP
634             /*
635              * THREAD SELECTION FOR AN SMP MACHINE BUILD
636              *
637              * If the target needs the MP lock and we couldn't get it,
638              * or if the target is holding tokens and we could not 
639              * gain ownership of the tokens, continue looking for a
640              * thread to schedule and spin instead of HLT if we can't.
641              *
642              * NOTE: the mpheld variable invalid after this conditional, it
643              * can change due to both cpu_try_mplock() returning success
644              * AND interactions in lwkt_getalltokens() due to the fact that
645              * we are trying to check the mpcount of a thread other then
646              * the current thread.  Because of this, if the current thread
647              * is not holding td_mpcount, an IPI indirectly run via
648              * lwkt_getalltokens() can obtain and release the MP lock and
649              * cause the core MP lock to be released. 
650              */
651             if ((ntd->td_mpcount && mpheld == 0 && !cpu_try_mplock()) ||
652                 (ntd->td_toks && lwkt_getalltokens(ntd) == 0)
653             ) {
654                 u_int32_t rqmask = gd->gd_runqmask;
655
656                 mpheld = MP_LOCK_HELD();
657                 ntd = NULL;
658                 while (rqmask) {
659                     TAILQ_FOREACH(ntd, &gd->gd_tdrunq[nq], td_threadq) {
660                         if (ntd->td_mpcount && !mpheld && !cpu_try_mplock()) {
661                             /* spinning due to MP lock being held */
662 #ifdef  INVARIANTS
663                             ++mplock_contention_count;
664 #endif
665                             /* mplock still not held, 'mpheld' still valid */
666                             continue;
667                         }
668
669                         /*
670                          * mpheld state invalid after getalltokens call returns
671                          * failure, but the variable is only needed for
672                          * the loop.
673                          */
674                         if (ntd->td_toks && !lwkt_getalltokens(ntd)) {
675                             /* spinning due to token contention */
676 #ifdef  INVARIANTS
677                             ++token_contention_count;
678 #endif
679                             mpheld = MP_LOCK_HELD();
680                             continue;
681                         }
682                         break;
683                     }
684                     if (ntd)
685                         break;
686                     rqmask &= ~(1 << nq);
687                     nq = bsrl(rqmask);
688                 }
689                 if (ntd == NULL) {
690                     ntd = &gd->gd_idlethread;
691                     ntd->td_flags |= TDF_IDLE_NOHLT;
692                     goto using_idle_thread;
693                 } else {
694                     ++gd->gd_cnt.v_swtch;
695                     TAILQ_REMOVE(&gd->gd_tdrunq[nq], ntd, td_threadq);
696                     TAILQ_INSERT_TAIL(&gd->gd_tdrunq[nq], ntd, td_threadq);
697                 }
698             } else {
699                 ++gd->gd_cnt.v_swtch;
700                 TAILQ_REMOVE(&gd->gd_tdrunq[nq], ntd, td_threadq);
701                 TAILQ_INSERT_TAIL(&gd->gd_tdrunq[nq], ntd, td_threadq);
702             }
703 #else
704             /*
705              * THREAD SELECTION FOR A UP MACHINE BUILD.  We don't have to
706              * worry about tokens or the BGL.
707              */
708             ++gd->gd_cnt.v_swtch;
709             TAILQ_REMOVE(&gd->gd_tdrunq[nq], ntd, td_threadq);
710             TAILQ_INSERT_TAIL(&gd->gd_tdrunq[nq], ntd, td_threadq);
711 #endif
712         } else {
713             /*
714              * We have nothing to run but only let the idle loop halt
715              * the cpu if there are no pending interrupts.
716              */
717             ntd = &gd->gd_idlethread;
718             if (gd->gd_reqflags & RQF_IDLECHECK_MASK)
719                 ntd->td_flags |= TDF_IDLE_NOHLT;
720 #ifdef SMP
721 using_idle_thread:
722             /*
723              * The idle thread should not be holding the MP lock unless we
724              * are trapping in the kernel or in a panic.  Since we select the
725              * idle thread unconditionally when no other thread is available,
726              * if the MP lock is desired during a panic or kernel trap, we
727              * have to loop in the scheduler until we get it.
728              */
729             if (ntd->td_mpcount) {
730                 mpheld = MP_LOCK_HELD();
731                 if (gd->gd_trap_nesting_level == 0 && panicstr == NULL)
732                     panic("Idle thread %p was holding the BGL!", ntd);
733                 else if (mpheld == 0)
734                     goto again;
735             }
736 #endif
737         }
738     }
739     KASSERT(ntd->td_pri >= TDPRI_CRIT,
740         ("priority problem in lwkt_switch %d %d", td->td_pri, ntd->td_pri));
741
742     /*
743      * Do the actual switch.  If the new target does not need the MP lock
744      * and we are holding it, release the MP lock.  If the new target requires
745      * the MP lock we have already acquired it for the target.
746      */
747 #ifdef SMP
748     if (ntd->td_mpcount == 0 ) {
749         if (MP_LOCK_HELD())
750             cpu_rel_mplock();
751     } else {
752         ASSERT_MP_LOCK_HELD(ntd);
753     }
754 #endif
755     if (td != ntd) {
756         ++switch_count;
757         td->td_switch(ntd);
758     }
759     /* NOTE: current cpu may have changed after switch */
760     crit_exit_quick(td);
761 }
762
763 /*
764  * Request that the target thread preempt the current thread.  Preemption
765  * only works under a specific set of conditions:
766  *
767  *      - We are not preempting ourselves
768  *      - The target thread is owned by the current cpu
769  *      - We are not currently being preempted
770  *      - The target is not currently being preempted
771  *      - We are able to satisfy the target's MP lock requirements (if any).
772  *
773  * THE CALLER OF LWKT_PREEMPT() MUST BE IN A CRITICAL SECTION.  Typically
774  * this is called via lwkt_schedule() through the td_preemptable callback.
775  * critpri is the managed critical priority that we should ignore in order
776  * to determine whether preemption is possible (aka usually just the crit
777  * priority of lwkt_schedule() itself).
778  *
779  * XXX at the moment we run the target thread in a critical section during
780  * the preemption in order to prevent the target from taking interrupts
781  * that *WE* can't.  Preemption is strictly limited to interrupt threads
782  * and interrupt-like threads, outside of a critical section, and the
783  * preempted source thread will be resumed the instant the target blocks
784  * whether or not the source is scheduled (i.e. preemption is supposed to
785  * be as transparent as possible).
786  *
787  * The target thread inherits our MP count (added to its own) for the
788  * duration of the preemption in order to preserve the atomicy of the
789  * MP lock during the preemption.  Therefore, any preempting targets must be
790  * careful in regards to MP assertions.  Note that the MP count may be
791  * out of sync with the physical mp_lock, but we do not have to preserve
792  * the original ownership of the lock if it was out of synch (that is, we
793  * can leave it synchronized on return).
794  */
795 void
796 lwkt_preempt(thread_t ntd, int critpri)
797 {
798     struct globaldata *gd = mycpu;
799     thread_t td;
800 #ifdef SMP
801     int mpheld;
802     int savecnt;
803 #endif
804
805     /*
806      * The caller has put us in a critical section.  We can only preempt
807      * if the caller of the caller was not in a critical section (basically
808      * a local interrupt), as determined by the 'critpri' parameter.  We
809      * also acn't preempt if the caller is holding any spinlocks (even if
810      * he isn't in a critical section).  This also handles the tokens test.
811      *
812      * YYY The target thread must be in a critical section (else it must
813      * inherit our critical section?  I dunno yet).
814      *
815      * Set need_lwkt_resched() unconditionally for now YYY.
816      */
817     KASSERT(ntd->td_pri >= TDPRI_CRIT, ("BADCRIT0 %d", ntd->td_pri));
818
819     td = gd->gd_curthread;
820     if ((ntd->td_pri & TDPRI_MASK) <= (td->td_pri & TDPRI_MASK)) {
821         ++preempt_miss;
822         return;
823     }
824     if ((td->td_pri & ~TDPRI_MASK) > critpri) {
825         ++preempt_miss;
826         need_lwkt_resched();
827         return;
828     }
829 #ifdef SMP
830     if (ntd->td_gd != gd) {
831         ++preempt_miss;
832         need_lwkt_resched();
833         return;
834     }
835 #endif
836     /*
837      * Take the easy way out and do not preempt if the target is holding
838      * any spinlocks.  We could test whether the thread(s) being
839      * preempted interlock against the target thread's tokens and whether
840      * we can get all the target thread's tokens, but this situation 
841      * should not occur very often so its easier to simply not preempt.
842      * Also, plain spinlocks are impossible to figure out at this point so 
843      * just don't preempt.
844      */
845     if (gd->gd_spinlocks_rd + gd->gd_spinlocks_wr != 0) {
846         ++preempt_miss;
847         need_lwkt_resched();
848         return;
849     }
850     if (td == ntd || ((td->td_flags | ntd->td_flags) & TDF_PREEMPT_LOCK)) {
851         ++preempt_weird;
852         need_lwkt_resched();
853         return;
854     }
855     if (ntd->td_preempted) {
856         ++preempt_hit;
857         need_lwkt_resched();
858         return;
859     }
860 #ifdef SMP
861     /*
862      * note: an interrupt might have occured just as we were transitioning
863      * to or from the MP lock.  In this case td_mpcount will be pre-disposed
864      * (non-zero) but not actually synchronized with the actual state of the
865      * lock.  We can use it to imply an MP lock requirement for the
866      * preemption but we cannot use it to test whether we hold the MP lock
867      * or not.
868      */
869     savecnt = td->td_mpcount;
870     mpheld = MP_LOCK_HELD();
871     ntd->td_mpcount += td->td_mpcount;
872     if (mpheld == 0 && ntd->td_mpcount && !cpu_try_mplock()) {
873         ntd->td_mpcount -= td->td_mpcount;
874         ++preempt_miss;
875         need_lwkt_resched();
876         return;
877     }
878 #endif
879
880     /*
881      * Since we are able to preempt the current thread, there is no need to
882      * call need_lwkt_resched().
883      */
884     ++preempt_hit;
885     ntd->td_preempted = td;
886     td->td_flags |= TDF_PREEMPT_LOCK;
887     td->td_switch(ntd);
888     KKASSERT(ntd->td_preempted && (td->td_flags & TDF_PREEMPT_DONE));
889 #ifdef SMP
890     KKASSERT(savecnt == td->td_mpcount);
891     mpheld = MP_LOCK_HELD();
892     if (mpheld && td->td_mpcount == 0)
893         cpu_rel_mplock();
894     else if (mpheld == 0 && td->td_mpcount)
895         panic("lwkt_preempt(): MP lock was not held through");
896 #endif
897     ntd->td_preempted = NULL;
898     td->td_flags &= ~(TDF_PREEMPT_LOCK|TDF_PREEMPT_DONE);
899 }
900
901 /*
902  * Yield our thread while higher priority threads are pending.  This is
903  * typically called when we leave a critical section but it can be safely
904  * called while we are in a critical section.
905  *
906  * This function will not generally yield to equal priority threads but it
907  * can occur as a side effect.  Note that lwkt_switch() is called from
908  * inside the critical section to prevent its own crit_exit() from reentering
909  * lwkt_yield_quick().
910  *
911  * gd_reqflags indicates that *something* changed, e.g. an interrupt or softint
912  * came along but was blocked and made pending.
913  *
914  * (self contained on a per cpu basis)
915  */
916 void
917 lwkt_yield_quick(void)
918 {
919     globaldata_t gd = mycpu;
920     thread_t td = gd->gd_curthread;
921
922     /*
923      * gd_reqflags is cleared in splz if the cpl is 0.  If we were to clear
924      * it with a non-zero cpl then we might not wind up calling splz after
925      * a task switch when the critical section is exited even though the
926      * new task could accept the interrupt.
927      *
928      * XXX from crit_exit() only called after last crit section is released.
929      * If called directly will run splz() even if in a critical section.
930      *
931      * td_nest_count prevent deep nesting via splz() or doreti().  Note that
932      * except for this special case, we MUST call splz() here to handle any
933      * pending ints, particularly after we switch, or we might accidently
934      * halt the cpu with interrupts pending.
935      */
936     if (gd->gd_reqflags && td->td_nest_count < 2)
937         splz();
938
939     /*
940      * YYY enabling will cause wakeup() to task-switch, which really
941      * confused the old 4.x code.  This is a good way to simulate
942      * preemption and MP without actually doing preemption or MP, because a
943      * lot of code assumes that wakeup() does not block.
944      */
945     if (untimely_switch && td->td_nest_count == 0 &&
946         gd->gd_intr_nesting_level == 0
947     ) {
948         crit_enter_quick(td);
949         /*
950          * YYY temporary hacks until we disassociate the userland scheduler
951          * from the LWKT scheduler.
952          */
953         if (td->td_flags & TDF_RUNQ) {
954             lwkt_switch();              /* will not reenter yield function */
955         } else {
956             lwkt_schedule_self(td);     /* make sure we are scheduled */
957             lwkt_switch();              /* will not reenter yield function */
958             lwkt_deschedule_self(td);   /* make sure we are descheduled */
959         }
960         crit_exit_noyield(td);
961     }
962 }
963
964 /*
965  * This implements a normal yield which, unlike _quick, will yield to equal
966  * priority threads as well.  Note that gd_reqflags tests will be handled by
967  * the crit_exit() call in lwkt_switch().
968  *
969  * (self contained on a per cpu basis)
970  */
971 void
972 lwkt_yield(void)
973 {
974     lwkt_schedule_self(curthread);
975     lwkt_switch();
976 }
977
978 /*
979  * Generic schedule.  Possibly schedule threads belonging to other cpus and
980  * deal with threads that might be blocked on a wait queue.
981  *
982  * We have a little helper inline function which does additional work after
983  * the thread has been enqueued, including dealing with preemption and
984  * setting need_lwkt_resched() (which prevents the kernel from returning
985  * to userland until it has processed higher priority threads).
986  *
987  * It is possible for this routine to be called after a failed _enqueue
988  * (due to the target thread migrating, sleeping, or otherwise blocked).
989  * We have to check that the thread is actually on the run queue!
990  */
991 static __inline
992 void
993 _lwkt_schedule_post(globaldata_t gd, thread_t ntd, int cpri)
994 {
995     if (ntd->td_flags & TDF_RUNQ) {
996         if (ntd->td_preemptable) {
997             ntd->td_preemptable(ntd, cpri);     /* YYY +token */
998         } else if ((ntd->td_flags & TDF_NORESCHED) == 0 &&
999             (ntd->td_pri & TDPRI_MASK) > (gd->gd_curthread->td_pri & TDPRI_MASK)
1000         ) {
1001             need_lwkt_resched();
1002         }
1003     }
1004 }
1005
1006 void
1007 lwkt_schedule(thread_t td)
1008 {
1009     globaldata_t mygd = mycpu;
1010
1011     KASSERT(td != &td->td_gd->gd_idlethread, ("lwkt_schedule(): scheduling gd_idlethread is illegal!"));
1012     crit_enter_gd(mygd);
1013     KKASSERT(td->td_proc == NULL || (td->td_proc->p_flag & P_ONRUNQ) == 0);
1014     if (td == mygd->gd_curthread) {
1015         _lwkt_enqueue(td);
1016     } else {
1017         lwkt_wait_t w;
1018
1019         /*
1020          * If the thread is on a wait list we have to send our scheduling
1021          * request to the owner of the wait structure.  Otherwise we send
1022          * the scheduling request to the cpu owning the thread.  Races
1023          * are ok, the target will forward the message as necessary (the
1024          * message may chase the thread around before it finally gets
1025          * acted upon).
1026          *
1027          * (remember, wait structures use stable storage)
1028          *
1029          * NOTE: we have to account for the number of critical sections
1030          * under our control when calling _lwkt_schedule_post() so it
1031          * can figure out whether preemption is allowed.
1032          *
1033          * NOTE: The wait structure algorithms are a mess and need to be
1034          * rewritten.
1035          *
1036          * NOTE: We cannot safely acquire or release a token, even 
1037          * non-blocking, because this routine may be called in the context
1038          * of a thread already holding the token and thus not provide any
1039          * interlock protection.  We cannot safely manipulate the td_toks
1040          * list for the same reason.  Instead we depend on our critical
1041          * section if the token is owned by our cpu.
1042          */
1043         if ((w = td->td_wait) != NULL) {
1044             spin_lock_wr(&w->wa_spinlock);
1045             TAILQ_REMOVE(&w->wa_waitq, td, td_threadq);
1046             --w->wa_count;
1047             td->td_wait = NULL;
1048             spin_unlock_wr(&w->wa_spinlock);
1049 #ifdef SMP
1050             if (td->td_gd == mygd) {
1051                 _lwkt_enqueue(td);
1052                 _lwkt_schedule_post(mygd, td, TDPRI_CRIT);
1053             } else {
1054                 lwkt_send_ipiq(td->td_gd, (ipifunc1_t)lwkt_schedule, td);
1055             }
1056 #else
1057             _lwkt_enqueue(td);
1058             _lwkt_schedule_post(mygd, td, TDPRI_CRIT);
1059 #endif
1060         } else {
1061             /*
1062              * If the wait structure is NULL and we own the thread, there
1063              * is no race (since we are in a critical section).  If we
1064              * do not own the thread there might be a race but the
1065              * target cpu will deal with it.
1066              */
1067 #ifdef SMP
1068             if (td->td_gd == mygd) {
1069                 _lwkt_enqueue(td);
1070                 _lwkt_schedule_post(mygd, td, TDPRI_CRIT);
1071             } else {
1072                 lwkt_send_ipiq(td->td_gd, (ipifunc1_t)lwkt_schedule, td);
1073             }
1074 #else
1075             _lwkt_enqueue(td);
1076             _lwkt_schedule_post(mygd, td, TDPRI_CRIT);
1077 #endif
1078         }
1079     }
1080     crit_exit_gd(mygd);
1081 }
1082
1083 #ifdef SMP
1084
1085 /*
1086  * Thread migration using a 'Pull' method.  The thread may or may not be
1087  * the current thread.  It MUST be descheduled and in a stable state.
1088  * lwkt_giveaway() must be called on the cpu owning the thread.
1089  *
1090  * At any point after lwkt_giveaway() is called, the target cpu may
1091  * 'pull' the thread by calling lwkt_acquire().
1092  *
1093  * MPSAFE - must be called under very specific conditions.
1094  */
1095 void
1096 lwkt_giveaway(thread_t td)
1097 {
1098         globaldata_t gd = mycpu;
1099
1100         crit_enter_gd(gd);
1101         KKASSERT(td->td_gd == gd);
1102         TAILQ_REMOVE(&gd->gd_tdallq, td, td_allq);
1103         td->td_flags |= TDF_MIGRATING;
1104         crit_exit_gd(gd);
1105 }
1106
1107 void
1108 lwkt_acquire(thread_t td)
1109 {
1110     globaldata_t gd;
1111     globaldata_t mygd;
1112
1113     KKASSERT(td->td_flags & TDF_MIGRATING);
1114     gd = td->td_gd;
1115     mygd = mycpu;
1116     if (gd != mycpu) {
1117         cpu_lfence();
1118         KKASSERT((td->td_flags & TDF_RUNQ) == 0);
1119         crit_enter_gd(mygd);
1120         while (td->td_flags & (TDF_RUNNING|TDF_PREEMPT_LOCK))
1121             cpu_lfence();
1122         td->td_gd = mygd;
1123         TAILQ_INSERT_TAIL(&mygd->gd_tdallq, td, td_allq);
1124         td->td_flags &= ~TDF_MIGRATING;
1125         crit_exit_gd(mygd);
1126     } else {
1127         crit_enter_gd(mygd);
1128         TAILQ_INSERT_TAIL(&mygd->gd_tdallq, td, td_allq);
1129         td->td_flags &= ~TDF_MIGRATING;
1130         crit_exit_gd(mygd);
1131     }
1132 }
1133
1134 #endif
1135
1136 /*
1137  * Generic deschedule.  Descheduling threads other then your own should be
1138  * done only in carefully controlled circumstances.  Descheduling is 
1139  * asynchronous.  
1140  *
1141  * This function may block if the cpu has run out of messages.
1142  */
1143 void
1144 lwkt_deschedule(thread_t td)
1145 {
1146     crit_enter();
1147 #ifdef SMP
1148     if (td == curthread) {
1149         _lwkt_dequeue(td);
1150     } else {
1151         if (td->td_gd == mycpu) {
1152             _lwkt_dequeue(td);
1153         } else {
1154             lwkt_send_ipiq(td->td_gd, (ipifunc1_t)lwkt_deschedule, td);
1155         }
1156     }
1157 #else
1158     _lwkt_dequeue(td);
1159 #endif
1160     crit_exit();
1161 }
1162
1163 /*
1164  * Set the target thread's priority.  This routine does not automatically
1165  * switch to a higher priority thread, LWKT threads are not designed for
1166  * continuous priority changes.  Yield if you want to switch.
1167  *
1168  * We have to retain the critical section count which uses the high bits
1169  * of the td_pri field.  The specified priority may also indicate zero or
1170  * more critical sections by adding TDPRI_CRIT*N.
1171  *
1172  * Note that we requeue the thread whether it winds up on a different runq
1173  * or not.  uio_yield() depends on this and the routine is not normally
1174  * called with the same priority otherwise.
1175  */
1176 void
1177 lwkt_setpri(thread_t td, int pri)
1178 {
1179     KKASSERT(pri >= 0);
1180     KKASSERT(td->td_gd == mycpu);
1181     crit_enter();
1182     if (td->td_flags & TDF_RUNQ) {
1183         _lwkt_dequeue(td);
1184         td->td_pri = (td->td_pri & ~TDPRI_MASK) + pri;
1185         _lwkt_enqueue(td);
1186     } else {
1187         td->td_pri = (td->td_pri & ~TDPRI_MASK) + pri;
1188     }
1189     crit_exit();
1190 }
1191
1192 void
1193 lwkt_setpri_self(int pri)
1194 {
1195     thread_t td = curthread;
1196
1197     KKASSERT(pri >= 0 && pri <= TDPRI_MAX);
1198     crit_enter();
1199     if (td->td_flags & TDF_RUNQ) {
1200         _lwkt_dequeue(td);
1201         td->td_pri = (td->td_pri & ~TDPRI_MASK) + pri;
1202         _lwkt_enqueue(td);
1203     } else {
1204         td->td_pri = (td->td_pri & ~TDPRI_MASK) + pri;
1205     }
1206     crit_exit();
1207 }
1208
1209 /*
1210  * Determine if there is a runnable thread at a higher priority then
1211  * the current thread.  lwkt_setpri() does not check this automatically.
1212  * Return 1 if there is, 0 if there isn't.
1213  *
1214  * Example: if bit 31 of runqmask is set and the current thread is priority
1215  * 30, then we wind up checking the mask: 0x80000000 against 0x7fffffff.  
1216  *
1217  * If nq reaches 31 the shift operation will overflow to 0 and we will wind
1218  * up comparing against 0xffffffff, a comparison that will always be false.
1219  */
1220 int
1221 lwkt_checkpri_self(void)
1222 {
1223     globaldata_t gd = mycpu;
1224     thread_t td = gd->gd_curthread;
1225     int nq = td->td_pri & TDPRI_MASK;
1226
1227     while (gd->gd_runqmask > (__uint32_t)(2 << nq) - 1) {
1228         if (TAILQ_FIRST(&gd->gd_tdrunq[nq + 1]))
1229             return(1);
1230         ++nq;
1231     }
1232     return(0);
1233 }
1234
1235 /*
1236  * Migrate the current thread to the specified cpu. 
1237  *
1238  * This is accomplished by descheduling ourselves from the current cpu,
1239  * moving our thread to the tdallq of the target cpu, IPI messaging the
1240  * target cpu, and switching out.  TDF_MIGRATING prevents scheduling
1241  * races while the thread is being migrated.
1242  */
1243 #ifdef SMP
1244 static void lwkt_setcpu_remote(void *arg);
1245 #endif
1246
1247 void
1248 lwkt_setcpu_self(globaldata_t rgd)
1249 {
1250 #ifdef SMP
1251     thread_t td = curthread;
1252
1253     if (td->td_gd != rgd) {
1254         crit_enter_quick(td);
1255         td->td_flags |= TDF_MIGRATING;
1256         lwkt_deschedule_self(td);
1257         TAILQ_REMOVE(&td->td_gd->gd_tdallq, td, td_allq);
1258         lwkt_send_ipiq(rgd, (ipifunc1_t)lwkt_setcpu_remote, td);
1259         lwkt_switch();
1260         /* we are now on the target cpu */
1261         TAILQ_INSERT_TAIL(&rgd->gd_tdallq, td, td_allq);
1262         crit_exit_quick(td);
1263     }
1264 #endif
1265 }
1266
1267 void
1268 lwkt_migratecpu(int cpuid)
1269 {
1270 #ifdef SMP
1271         globaldata_t rgd;
1272
1273         rgd = globaldata_find(cpuid);
1274         lwkt_setcpu_self(rgd);
1275 #endif
1276 }
1277
1278 /*
1279  * Remote IPI for cpu migration (called while in a critical section so we
1280  * do not have to enter another one).  The thread has already been moved to
1281  * our cpu's allq, but we must wait for the thread to be completely switched
1282  * out on the originating cpu before we schedule it on ours or the stack
1283  * state may be corrupt.  We clear TDF_MIGRATING after flushing the GD
1284  * change to main memory.
1285  *
1286  * XXX The use of TDF_MIGRATING might not be sufficient to avoid races
1287  * against wakeups.  It is best if this interface is used only when there
1288  * are no pending events that might try to schedule the thread.
1289  */
1290 #ifdef SMP
1291 static void
1292 lwkt_setcpu_remote(void *arg)
1293 {
1294     thread_t td = arg;
1295     globaldata_t gd = mycpu;
1296
1297     while (td->td_flags & (TDF_RUNNING|TDF_PREEMPT_LOCK))
1298         cpu_lfence();
1299     td->td_gd = gd;
1300     cpu_sfence();
1301     td->td_flags &= ~TDF_MIGRATING;
1302     KKASSERT(td->td_proc == NULL || (td->td_proc->p_flag & P_ONRUNQ) == 0);
1303     _lwkt_enqueue(td);
1304 }
1305 #endif
1306
1307 struct lwp *
1308 lwkt_preempted_proc(void)
1309 {
1310     thread_t td = curthread;
1311     while (td->td_preempted)
1312         td = td->td_preempted;
1313     return(td->td_lwp);
1314 }
1315
1316 /*
1317  * Block on the specified wait queue until signaled.  A generation number
1318  * must be supplied to interlock the wait queue.  The function will
1319  * return immediately if the generation number does not match the wait
1320  * structure's generation number.
1321  */
1322 void
1323 lwkt_block(lwkt_wait_t w, const char *wmesg, int *gen)
1324 {
1325     thread_t td = curthread;
1326
1327     spin_lock_wr(&w->wa_spinlock);
1328     if (w->wa_gen == *gen) {
1329         _lwkt_dequeue(td);
1330         td->td_flags |= TDF_BLOCKQ;
1331         TAILQ_INSERT_TAIL(&w->wa_waitq, td, td_threadq);
1332         ++w->wa_count;
1333         td->td_wait = w;
1334         td->td_wmesg = wmesg;
1335         spin_unlock_wr(&w->wa_spinlock);
1336         lwkt_switch();
1337         KKASSERT((td->td_flags & TDF_BLOCKQ) == 0);
1338         td->td_wmesg = NULL;
1339         *gen = w->wa_gen;
1340     } else {
1341         *gen = w->wa_gen;
1342         spin_unlock_wr(&w->wa_spinlock);
1343     }
1344 }
1345
1346 /*
1347  * Signal a wait queue.  We gain ownership of the wait queue in order to
1348  * signal it.  Once a thread is removed from the wait queue we have to
1349  * deal with the cpu owning the thread.
1350  *
1351  * Note: alternatively we could message the target cpu owning the wait
1352  * queue.  YYY implement as sysctl.
1353  */
1354 void
1355 lwkt_signal(lwkt_wait_t w, int count)
1356 {
1357     thread_t td;
1358
1359     spin_lock_wr(&w->wa_spinlock);
1360     ++w->wa_gen;
1361     if (count < 0)
1362         count = w->wa_count;
1363     while ((td = TAILQ_FIRST(&w->wa_waitq)) != NULL && count) {
1364         --count;
1365         --w->wa_count;
1366         KKASSERT(td->td_flags & TDF_BLOCKQ);
1367         TAILQ_REMOVE(&w->wa_waitq, td, td_threadq);
1368         td->td_flags &= ~TDF_BLOCKQ;
1369         td->td_wait = NULL;
1370         spin_unlock_wr(&w->wa_spinlock);
1371         KKASSERT(td->td_proc == NULL || (td->td_proc->p_flag & P_ONRUNQ) == 0);
1372 #ifdef SMP
1373         if (td->td_gd == mycpu) {
1374             _lwkt_enqueue(td);
1375         } else {
1376             lwkt_send_ipiq(td->td_gd, (ipifunc1_t)lwkt_schedule, td);
1377         }
1378 #else
1379         _lwkt_enqueue(td);
1380 #endif
1381         spin_lock_wr(&w->wa_spinlock);
1382     }
1383     spin_unlock_wr(&w->wa_spinlock);
1384 }
1385
1386 /*
1387  * Create a kernel process/thread/whatever.  It shares it's address space
1388  * with proc0 - ie: kernel only.
1389  *
1390  * NOTE!  By default new threads are created with the MP lock held.  A 
1391  * thread which does not require the MP lock should release it by calling
1392  * rel_mplock() at the start of the new thread.
1393  */
1394 int
1395 lwkt_create(void (*func)(void *), void *arg,
1396     struct thread **tdp, thread_t template, int tdflags, int cpu,
1397     const char *fmt, ...)
1398 {
1399     thread_t td;
1400     __va_list ap;
1401
1402     td = lwkt_alloc_thread(template, LWKT_THREAD_STACK, cpu,
1403                            tdflags | TDF_VERBOSE);
1404     if (tdp)
1405         *tdp = td;
1406     cpu_set_thread_handler(td, lwkt_exit, func, arg);
1407
1408     /*
1409      * Set up arg0 for 'ps' etc
1410      */
1411     __va_start(ap, fmt);
1412     vsnprintf(td->td_comm, sizeof(td->td_comm), fmt, ap);
1413     __va_end(ap);
1414
1415     /*
1416      * Schedule the thread to run
1417      */
1418     if ((td->td_flags & TDF_STOPREQ) == 0)
1419         lwkt_schedule(td);
1420     else
1421         td->td_flags &= ~TDF_STOPREQ;
1422     return 0;
1423 }
1424
1425 /*
1426  * kthread_* is specific to the kernel and is not needed by userland.
1427  */
1428 #ifdef _KERNEL
1429
1430 /*
1431  * Destroy an LWKT thread.   Warning!  This function is not called when
1432  * a process exits, cpu_proc_exit() directly calls cpu_thread_exit() and
1433  * uses a different reaping mechanism.
1434  */
1435 void
1436 lwkt_exit(void)
1437 {
1438     thread_t td = curthread;
1439     globaldata_t gd;
1440
1441     if (td->td_flags & TDF_VERBOSE)
1442         printf("kthread %p %s has exited\n", td, td->td_comm);
1443     caps_exit(td);
1444     crit_enter_quick(td);
1445     lwkt_deschedule_self(td);
1446     gd = mycpu;
1447     KKASSERT(gd == td->td_gd);
1448     TAILQ_REMOVE(&gd->gd_tdallq, td, td_allq);
1449     if (td->td_flags & TDF_ALLOCATED_THREAD) {
1450         ++gd->gd_tdfreecount;
1451         TAILQ_INSERT_TAIL(&gd->gd_tdfreeq, td, td_threadq);
1452     }
1453     cpu_thread_exit();
1454 }
1455
1456 #endif /* _KERNEL */
1457
1458 void
1459 crit_panic(void)
1460 {
1461     thread_t td = curthread;
1462     int lpri = td->td_pri;
1463
1464     td->td_pri = 0;
1465     panic("td_pri is/would-go negative! %p %d", td, lpri);
1466 }
1467
1468 #ifdef SMP
1469
1470 /*
1471  * Called from debugger/panic on cpus which have been stopped.  We must still
1472  * process the IPIQ while stopped, even if we were stopped while in a critical
1473  * section (XXX).
1474  *
1475  * If we are dumping also try to process any pending interrupts.  This may
1476  * or may not work depending on the state of the cpu at the point it was
1477  * stopped.
1478  */
1479 void
1480 lwkt_smp_stopped(void)
1481 {
1482     globaldata_t gd = mycpu;
1483
1484     crit_enter_gd(gd);
1485     if (dumping) {
1486         lwkt_process_ipiq();
1487         splz();
1488     } else {
1489         lwkt_process_ipiq();
1490     }
1491     crit_exit_gd(gd);
1492 }
1493
1494 /*
1495  * get_mplock() calls this routine if it is unable to obtain the MP lock.
1496  * get_mplock() has already incremented td_mpcount.  We must block and
1497  * not return until giant is held.
1498  *
1499  * All we have to do is lwkt_switch() away.  The LWKT scheduler will not
1500  * reschedule the thread until it can obtain the giant lock for it.
1501  */
1502 void
1503 lwkt_mp_lock_contested(void)
1504 {
1505 #ifdef _KERNEL
1506     loggiant(beg);
1507 #endif
1508     lwkt_switch();
1509 #ifdef _KERNEL
1510     loggiant(end);
1511 #endif
1512 }
1513
1514 #endif