3501185b517b824a084e8d0c6f3a982b3b09b568
[dragonfly.git] / sys / kern / lwkt_thread.c
1 /*
2  * Copyright (c) 2003-2011 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
35 /*
36  * Each cpu in a system has its own self-contained light weight kernel
37  * thread scheduler, which means that generally speaking we only need
38  * to use a critical section to avoid problems.  Foreign thread 
39  * scheduling is queued via (async) IPIs.
40  */
41
42 #include <sys/param.h>
43 #include <sys/systm.h>
44 #include <sys/kernel.h>
45 #include <sys/proc.h>
46 #include <sys/rtprio.h>
47 #include <sys/kinfo.h>
48 #include <sys/queue.h>
49 #include <sys/sysctl.h>
50 #include <sys/kthread.h>
51 #include <machine/cpu.h>
52 #include <sys/lock.h>
53 #include <sys/caps.h>
54 #include <sys/spinlock.h>
55 #include <sys/ktr.h>
56
57 #include <sys/thread2.h>
58 #include <sys/spinlock2.h>
59 #include <sys/mplock2.h>
60
61 #include <sys/dsched.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
72 #include <machine/stdarg.h>
73 #include <machine/smp.h>
74
75 #if !defined(KTR_CTXSW)
76 #define KTR_CTXSW KTR_ALL
77 #endif
78 KTR_INFO_MASTER(ctxsw);
79 KTR_INFO(KTR_CTXSW, ctxsw, sw, 0, "#cpu[%d].td = %p", int cpu, struct thread *td);
80 KTR_INFO(KTR_CTXSW, ctxsw, pre, 1, "#cpu[%d].td = %p", int cpu, struct thread *td);
81 KTR_INFO(KTR_CTXSW, ctxsw, newtd, 2, "#threads[%p].name = %s", struct thread *td, char *comm);
82 KTR_INFO(KTR_CTXSW, ctxsw, deadtd, 3, "#threads[%p].name = <dead>", struct thread *td);
83
84 static MALLOC_DEFINE(M_THREAD, "thread", "lwkt threads");
85
86 #ifdef  INVARIANTS
87 static int panic_on_cscount = 0;
88 #endif
89 static __int64_t switch_count = 0;
90 static __int64_t preempt_hit = 0;
91 static __int64_t preempt_miss = 0;
92 static __int64_t preempt_weird = 0;
93 static int lwkt_use_spin_port;
94 static struct objcache *thread_cache;
95
96 #ifdef SMP
97 static void lwkt_schedule_remote(void *arg, int arg2, struct intrframe *frame);
98 static void lwkt_setcpu_remote(void *arg);
99 #endif
100
101 extern void cpu_heavy_restore(void);
102 extern void cpu_lwkt_restore(void);
103 extern void cpu_kthread_restore(void);
104 extern void cpu_idle_restore(void);
105
106 /*
107  * We can make all thread ports use the spin backend instead of the thread
108  * backend.  This should only be set to debug the spin backend.
109  */
110 TUNABLE_INT("lwkt.use_spin_port", &lwkt_use_spin_port);
111
112 #ifdef  INVARIANTS
113 SYSCTL_INT(_lwkt, OID_AUTO, panic_on_cscount, CTLFLAG_RW, &panic_on_cscount, 0,
114     "Panic if attempting to switch lwkt's while mastering cpusync");
115 #endif
116 SYSCTL_QUAD(_lwkt, OID_AUTO, switch_count, CTLFLAG_RW, &switch_count, 0,
117     "Number of switched threads");
118 SYSCTL_QUAD(_lwkt, OID_AUTO, preempt_hit, CTLFLAG_RW, &preempt_hit, 0, 
119     "Successful preemption events");
120 SYSCTL_QUAD(_lwkt, OID_AUTO, preempt_miss, CTLFLAG_RW, &preempt_miss, 0, 
121     "Failed preemption events");
122 SYSCTL_QUAD(_lwkt, OID_AUTO, preempt_weird, CTLFLAG_RW, &preempt_weird, 0,
123     "Number of preempted threads.");
124 static int fairq_enable = 0;
125 SYSCTL_INT(_lwkt, OID_AUTO, fairq_enable, CTLFLAG_RW,
126         &fairq_enable, 0, "Turn on fairq priority accumulators");
127 static int fairq_bypass = -1;
128 SYSCTL_INT(_lwkt, OID_AUTO, fairq_bypass, CTLFLAG_RW,
129         &fairq_bypass, 0, "Allow fairq to bypass td on token failure");
130 extern int lwkt_sched_debug;
131 int lwkt_sched_debug = 0;
132 SYSCTL_INT(_lwkt, OID_AUTO, sched_debug, CTLFLAG_RW,
133         &lwkt_sched_debug, 0, "Scheduler debug");
134 static int lwkt_spin_loops = 10;
135 SYSCTL_INT(_lwkt, OID_AUTO, spin_loops, CTLFLAG_RW,
136         &lwkt_spin_loops, 0, "Scheduler spin loops until sorted decon");
137 static int lwkt_spin_reseq = 0;
138 SYSCTL_INT(_lwkt, OID_AUTO, spin_reseq, CTLFLAG_RW,
139         &lwkt_spin_reseq, 0, "Scheduler resequencer enable");
140 static int lwkt_spin_monitor = 0;
141 SYSCTL_INT(_lwkt, OID_AUTO, spin_monitor, CTLFLAG_RW,
142         &lwkt_spin_monitor, 0, "Scheduler uses monitor/mwait");
143 static int lwkt_spin_fatal = 0; /* disabled */
144 SYSCTL_INT(_lwkt, OID_AUTO, spin_fatal, CTLFLAG_RW,
145         &lwkt_spin_fatal, 0, "LWKT scheduler spin loops till fatal panic");
146 static int preempt_enable = 1;
147 SYSCTL_INT(_lwkt, OID_AUTO, preempt_enable, CTLFLAG_RW,
148         &preempt_enable, 0, "Enable preemption");
149 static int lwkt_cache_threads = 0;
150 SYSCTL_INT(_lwkt, OID_AUTO, cache_threads, CTLFLAG_RD,
151         &lwkt_cache_threads, 0, "thread+kstack cache");
152
153 static __cachealign int lwkt_cseq_rindex;
154 static __cachealign int lwkt_cseq_windex;
155
156 /*
157  * These helper procedures handle the runq, they can only be called from
158  * within a critical section.
159  *
160  * WARNING!  Prior to SMP being brought up it is possible to enqueue and
161  * dequeue threads belonging to other cpus, so be sure to use td->td_gd
162  * instead of 'mycpu' when referencing the globaldata structure.   Once
163  * SMP live enqueuing and dequeueing only occurs on the current cpu.
164  */
165 static __inline
166 void
167 _lwkt_dequeue(thread_t td)
168 {
169     if (td->td_flags & TDF_RUNQ) {
170         struct globaldata *gd = td->td_gd;
171
172         td->td_flags &= ~TDF_RUNQ;
173         TAILQ_REMOVE(&gd->gd_tdrunq, td, td_threadq);
174         --gd->gd_tdrunqcount;
175         if (TAILQ_FIRST(&gd->gd_tdrunq) == NULL)
176                 atomic_clear_int(&gd->gd_reqflags, RQF_RUNNING);
177     }
178 }
179
180 /*
181  * Priority enqueue.
182  *
183  * NOTE: There are a limited number of lwkt threads runnable since user
184  *       processes only schedule one at a time per cpu.
185  */
186 static __inline
187 void
188 _lwkt_enqueue(thread_t td)
189 {
190     thread_t xtd;
191
192     if ((td->td_flags & (TDF_RUNQ|TDF_MIGRATING|TDF_BLOCKQ)) == 0) {
193         struct globaldata *gd = td->td_gd;
194
195         td->td_flags |= TDF_RUNQ;
196         xtd = TAILQ_FIRST(&gd->gd_tdrunq);
197         if (xtd == NULL) {
198             TAILQ_INSERT_TAIL(&gd->gd_tdrunq, td, td_threadq);
199             atomic_set_int(&gd->gd_reqflags, RQF_RUNNING);
200         } else {
201             while (xtd && xtd->td_pri >= td->td_pri)
202                 xtd = TAILQ_NEXT(xtd, td_threadq);
203             if (xtd)
204                 TAILQ_INSERT_BEFORE(xtd, td, td_threadq);
205             else
206                 TAILQ_INSERT_TAIL(&gd->gd_tdrunq, td, td_threadq);
207         }
208         ++gd->gd_tdrunqcount;
209
210         /*
211          * Request a LWKT reschedule if we are now at the head of the queue.
212          */
213         if (TAILQ_FIRST(&gd->gd_tdrunq) == td)
214             need_lwkt_resched();
215     }
216 }
217
218 static __boolean_t
219 _lwkt_thread_ctor(void *obj, void *privdata, int ocflags)
220 {
221         struct thread *td = (struct thread *)obj;
222
223         td->td_kstack = NULL;
224         td->td_kstack_size = 0;
225         td->td_flags = TDF_ALLOCATED_THREAD;
226         td->td_mpflags = 0;
227         return (1);
228 }
229
230 static void
231 _lwkt_thread_dtor(void *obj, void *privdata)
232 {
233         struct thread *td = (struct thread *)obj;
234
235         KASSERT(td->td_flags & TDF_ALLOCATED_THREAD,
236             ("_lwkt_thread_dtor: not allocated from objcache"));
237         KASSERT((td->td_flags & TDF_ALLOCATED_STACK) && td->td_kstack &&
238                 td->td_kstack_size > 0,
239             ("_lwkt_thread_dtor: corrupted stack"));
240         kmem_free(&kernel_map, (vm_offset_t)td->td_kstack, td->td_kstack_size);
241         td->td_kstack = NULL;
242         td->td_flags = 0;
243 }
244
245 /*
246  * Initialize the lwkt s/system.
247  *
248  * Nominally cache up to 32 thread + kstack structures.  Cache more on
249  * systems with a lot of cpu cores.
250  */
251 void
252 lwkt_init(void)
253 {
254     TUNABLE_INT("lwkt.cache_threads", &lwkt_cache_threads);
255     if (lwkt_cache_threads == 0) {
256         lwkt_cache_threads = ncpus * 4;
257         if (lwkt_cache_threads < 32)
258             lwkt_cache_threads = 32;
259     }
260     thread_cache = objcache_create_mbacked(
261                                 M_THREAD, sizeof(struct thread),
262                                 NULL, lwkt_cache_threads,
263                                 _lwkt_thread_ctor, _lwkt_thread_dtor, NULL);
264 }
265
266 /*
267  * Schedule a thread to run.  As the current thread we can always safely
268  * schedule ourselves, and a shortcut procedure is provided for that
269  * function.
270  *
271  * (non-blocking, self contained on a per cpu basis)
272  */
273 void
274 lwkt_schedule_self(thread_t td)
275 {
276     KKASSERT((td->td_flags & TDF_MIGRATING) == 0);
277     crit_enter_quick(td);
278     KASSERT(td != &td->td_gd->gd_idlethread,
279             ("lwkt_schedule_self(): scheduling gd_idlethread is illegal!"));
280     KKASSERT(td->td_lwp == NULL ||
281              (td->td_lwp->lwp_mpflags & LWP_MP_ONRUNQ) == 0);
282     _lwkt_enqueue(td);
283     crit_exit_quick(td);
284 }
285
286 /*
287  * Deschedule a thread.
288  *
289  * (non-blocking, self contained on a per cpu basis)
290  */
291 void
292 lwkt_deschedule_self(thread_t td)
293 {
294     crit_enter_quick(td);
295     _lwkt_dequeue(td);
296     crit_exit_quick(td);
297 }
298
299 /*
300  * LWKTs operate on a per-cpu basis
301  *
302  * WARNING!  Called from early boot, 'mycpu' may not work yet.
303  */
304 void
305 lwkt_gdinit(struct globaldata *gd)
306 {
307     TAILQ_INIT(&gd->gd_tdrunq);
308     TAILQ_INIT(&gd->gd_tdallq);
309 }
310
311 /*
312  * Create a new thread.  The thread must be associated with a process context
313  * or LWKT start address before it can be scheduled.  If the target cpu is
314  * -1 the thread will be created on the current cpu.
315  *
316  * If you intend to create a thread without a process context this function
317  * does everything except load the startup and switcher function.
318  */
319 thread_t
320 lwkt_alloc_thread(struct thread *td, int stksize, int cpu, int flags)
321 {
322     static int cpu_rotator;
323     globaldata_t gd = mycpu;
324     void *stack;
325
326     /*
327      * If static thread storage is not supplied allocate a thread.  Reuse
328      * a cached free thread if possible.  gd_freetd is used to keep an exiting
329      * thread intact through the exit.
330      */
331     if (td == NULL) {
332         crit_enter_gd(gd);
333         if ((td = gd->gd_freetd) != NULL) {
334             KKASSERT((td->td_flags & (TDF_RUNNING|TDF_PREEMPT_LOCK|
335                                       TDF_RUNQ)) == 0);
336             gd->gd_freetd = NULL;
337         } else {
338             td = objcache_get(thread_cache, M_WAITOK);
339             KKASSERT((td->td_flags & (TDF_RUNNING|TDF_PREEMPT_LOCK|
340                                       TDF_RUNQ)) == 0);
341         }
342         crit_exit_gd(gd);
343         KASSERT((td->td_flags &
344                  (TDF_ALLOCATED_THREAD|TDF_RUNNING|TDF_PREEMPT_LOCK)) ==
345                  TDF_ALLOCATED_THREAD,
346                 ("lwkt_alloc_thread: corrupted td flags 0x%X", td->td_flags));
347         flags |= td->td_flags & (TDF_ALLOCATED_THREAD|TDF_ALLOCATED_STACK);
348     }
349
350     /*
351      * Try to reuse cached stack.
352      */
353     if ((stack = td->td_kstack) != NULL && td->td_kstack_size != stksize) {
354         if (flags & TDF_ALLOCATED_STACK) {
355             kmem_free(&kernel_map, (vm_offset_t)stack, td->td_kstack_size);
356             stack = NULL;
357         }
358     }
359     if (stack == NULL) {
360         stack = (void *)kmem_alloc_stack(&kernel_map, stksize);
361         flags |= TDF_ALLOCATED_STACK;
362     }
363     if (cpu < 0) {
364         cpu = ++cpu_rotator;
365         cpu_ccfence();
366         cpu %= ncpus;
367     }
368     lwkt_init_thread(td, stack, stksize, flags, globaldata_find(cpu));
369     return(td);
370 }
371
372 /*
373  * Initialize a preexisting thread structure.  This function is used by
374  * lwkt_alloc_thread() and also used to initialize the per-cpu idlethread.
375  *
376  * All threads start out in a critical section at a priority of
377  * TDPRI_KERN_DAEMON.  Higher level code will modify the priority as
378  * appropriate.  This function may send an IPI message when the 
379  * requested cpu is not the current cpu and consequently gd_tdallq may
380  * not be initialized synchronously from the point of view of the originating
381  * cpu.
382  *
383  * NOTE! we have to be careful in regards to creating threads for other cpus
384  * if SMP has not yet been activated.
385  */
386 #ifdef SMP
387
388 static void
389 lwkt_init_thread_remote(void *arg)
390 {
391     thread_t td = arg;
392
393     /*
394      * Protected by critical section held by IPI dispatch
395      */
396     TAILQ_INSERT_TAIL(&td->td_gd->gd_tdallq, td, td_allq);
397 }
398
399 #endif
400
401 /*
402  * lwkt core thread structural initialization.
403  *
404  * NOTE: All threads are initialized as mpsafe threads.
405  */
406 void
407 lwkt_init_thread(thread_t td, void *stack, int stksize, int flags,
408                 struct globaldata *gd)
409 {
410     globaldata_t mygd = mycpu;
411
412     bzero(td, sizeof(struct thread));
413     td->td_kstack = stack;
414     td->td_kstack_size = stksize;
415     td->td_flags = flags;
416     td->td_mpflags = 0;
417     td->td_gd = gd;
418     td->td_pri = TDPRI_KERN_DAEMON;
419     td->td_critcount = 1;
420     td->td_toks_have = NULL;
421     td->td_toks_stop = &td->td_toks_base;
422     if (lwkt_use_spin_port || (flags & TDF_FORCE_SPINPORT))
423         lwkt_initport_spin(&td->td_msgport, td);
424     else
425         lwkt_initport_thread(&td->td_msgport, td);
426     pmap_init_thread(td);
427 #ifdef SMP
428     /*
429      * Normally initializing a thread for a remote cpu requires sending an
430      * IPI.  However, the idlethread is setup before the other cpus are
431      * activated so we have to treat it as a special case.  XXX manipulation
432      * of gd_tdallq requires the BGL.
433      */
434     if (gd == mygd || td == &gd->gd_idlethread) {
435         crit_enter_gd(mygd);
436         TAILQ_INSERT_TAIL(&gd->gd_tdallq, td, td_allq);
437         crit_exit_gd(mygd);
438     } else {
439         lwkt_send_ipiq(gd, lwkt_init_thread_remote, td);
440     }
441 #else
442     crit_enter_gd(mygd);
443     TAILQ_INSERT_TAIL(&gd->gd_tdallq, td, td_allq);
444     crit_exit_gd(mygd);
445 #endif
446
447     dsched_new_thread(td);
448 }
449
450 void
451 lwkt_set_comm(thread_t td, const char *ctl, ...)
452 {
453     __va_list va;
454
455     __va_start(va, ctl);
456     kvsnprintf(td->td_comm, sizeof(td->td_comm), ctl, va);
457     __va_end(va);
458     KTR_LOG(ctxsw_newtd, td, td->td_comm);
459 }
460
461 /*
462  * Prevent the thread from getting destroyed.  Note that unlike PHOLD/PRELE
463  * this does not prevent the thread from migrating to another cpu so the
464  * gd_tdallq state is not protected by this.
465  */
466 void
467 lwkt_hold(thread_t td)
468 {
469     atomic_add_int(&td->td_refs, 1);
470 }
471
472 void
473 lwkt_rele(thread_t td)
474 {
475     KKASSERT(td->td_refs > 0);
476     atomic_add_int(&td->td_refs, -1);
477 }
478
479 void
480 lwkt_free_thread(thread_t td)
481 {
482     KKASSERT(td->td_refs == 0);
483     KKASSERT((td->td_flags & (TDF_RUNNING | TDF_PREEMPT_LOCK |
484                               TDF_RUNQ | TDF_TSLEEPQ)) == 0);
485     if (td->td_flags & TDF_ALLOCATED_THREAD) {
486         objcache_put(thread_cache, td);
487     } else if (td->td_flags & TDF_ALLOCATED_STACK) {
488         /* client-allocated struct with internally allocated stack */
489         KASSERT(td->td_kstack && td->td_kstack_size > 0,
490             ("lwkt_free_thread: corrupted stack"));
491         kmem_free(&kernel_map, (vm_offset_t)td->td_kstack, td->td_kstack_size);
492         td->td_kstack = NULL;
493         td->td_kstack_size = 0;
494     }
495     KTR_LOG(ctxsw_deadtd, td);
496 }
497
498
499 /*
500  * Switch to the next runnable lwkt.  If no LWKTs are runnable then 
501  * switch to the idlethread.  Switching must occur within a critical
502  * section to avoid races with the scheduling queue.
503  *
504  * We always have full control over our cpu's run queue.  Other cpus
505  * that wish to manipulate our queue must use the cpu_*msg() calls to
506  * talk to our cpu, so a critical section is all that is needed and
507  * the result is very, very fast thread switching.
508  *
509  * The LWKT scheduler uses a fixed priority model and round-robins at
510  * each priority level.  User process scheduling is a totally
511  * different beast and LWKT priorities should not be confused with
512  * user process priorities.
513  *
514  * PREEMPTION NOTE: Preemption occurs via lwkt_preempt().  lwkt_switch()
515  * is not called by the current thread in the preemption case, only when
516  * the preempting thread blocks (in order to return to the original thread).
517  *
518  * SPECIAL NOTE ON SWITCH ATOMICY: Certain operations such as thread
519  * migration and tsleep deschedule the current lwkt thread and call
520  * lwkt_switch().  In particular, the target cpu of the migration fully
521  * expects the thread to become non-runnable and can deadlock against
522  * cpusync operations if we run any IPIs prior to switching the thread out.
523  *
524  * WE MUST BE VERY CAREFUL NOT TO RUN SPLZ DIRECTLY OR INDIRECTLY IF
525  * THE CURRENT THREAD HAS BEEN DESCHEDULED!
526  */
527 void
528 lwkt_switch(void)
529 {
530     globaldata_t gd = mycpu;
531     thread_t td = gd->gd_curthread;
532     thread_t ntd;
533     int spinning = 0;
534
535     KKASSERT(gd->gd_processing_ipiq == 0);
536     KKASSERT(td->td_flags & TDF_RUNNING);
537
538     /*
539      * Switching from within a 'fast' (non thread switched) interrupt or IPI
540      * is illegal.  However, we may have to do it anyway if we hit a fatal
541      * kernel trap or we have paniced.
542      *
543      * If this case occurs save and restore the interrupt nesting level.
544      */
545     if (gd->gd_intr_nesting_level) {
546         int savegdnest;
547         int savegdtrap;
548
549         if (gd->gd_trap_nesting_level == 0 && panic_cpu_gd != mycpu) {
550             panic("lwkt_switch: Attempt to switch from a "
551                   "fast interrupt, ipi, or hard code section, "
552                   "td %p\n",
553                   td);
554         } else {
555             savegdnest = gd->gd_intr_nesting_level;
556             savegdtrap = gd->gd_trap_nesting_level;
557             gd->gd_intr_nesting_level = 0;
558             gd->gd_trap_nesting_level = 0;
559             if ((td->td_flags & TDF_PANICWARN) == 0) {
560                 td->td_flags |= TDF_PANICWARN;
561                 kprintf("Warning: thread switch from interrupt, IPI, "
562                         "or hard code section.\n"
563                         "thread %p (%s)\n", td, td->td_comm);
564                 print_backtrace(-1);
565             }
566             lwkt_switch();
567             gd->gd_intr_nesting_level = savegdnest;
568             gd->gd_trap_nesting_level = savegdtrap;
569             return;
570         }
571     }
572
573     /*
574      * Release our current user process designation if we are blocking
575      * or if a user reschedule was requested.
576      *
577      * NOTE: This function is NOT called if we are switching into or
578      *       returning from a preemption.
579      *
580      * NOTE: Releasing our current user process designation may cause
581      *       it to be assigned to another thread, which in turn will
582      *       cause us to block in the usched acquire code when we attempt
583      *       to return to userland.
584      *
585      * NOTE: On SMP systems this can be very nasty when heavy token
586      *       contention is present so we want to be careful not to
587      *       release the designation gratuitously.
588      */
589     if (td->td_release &&
590         (user_resched_wanted() || (td->td_flags & TDF_RUNQ) == 0)) {
591             td->td_release(td);
592     }
593
594     /*
595      * Release all tokens
596      */
597     crit_enter_gd(gd);
598     if (TD_TOKS_HELD(td))
599             lwkt_relalltokens(td);
600
601     /*
602      * We had better not be holding any spin locks, but don't get into an
603      * endless panic loop.
604      */
605     KASSERT(gd->gd_spinlocks_wr == 0 || panicstr != NULL, 
606             ("lwkt_switch: still holding %d exclusive spinlocks!",
607              gd->gd_spinlocks_wr));
608
609
610 #ifdef SMP
611 #ifdef  INVARIANTS
612     if (td->td_cscount) {
613         kprintf("Diagnostic: attempt to switch while mastering cpusync: %p\n",
614                 td);
615         if (panic_on_cscount)
616             panic("switching while mastering cpusync");
617     }
618 #endif
619 #endif
620
621     /*
622      * If we had preempted another thread on this cpu, resume the preempted
623      * thread.  This occurs transparently, whether the preempted thread
624      * was scheduled or not (it may have been preempted after descheduling
625      * itself).
626      *
627      * We have to setup the MP lock for the original thread after backing
628      * out the adjustment that was made to curthread when the original
629      * was preempted.
630      */
631     if ((ntd = td->td_preempted) != NULL) {
632         KKASSERT(ntd->td_flags & TDF_PREEMPT_LOCK);
633         ntd->td_flags |= TDF_PREEMPT_DONE;
634
635         /*
636          * The interrupt may have woken a thread up, we need to properly
637          * set the reschedule flag if the originally interrupted thread is
638          * at a lower priority.
639          *
640          * The interrupt may not have descheduled.
641          */
642         if (TAILQ_FIRST(&gd->gd_tdrunq) != ntd)
643             need_lwkt_resched();
644         goto havethread_preempted;
645     }
646
647     /*
648      * If we cannot obtain ownership of the tokens we cannot immediately
649      * schedule the target thread.
650      *
651      * Reminder: Again, we cannot afford to run any IPIs in this path if
652      * the current thread has been descheduled.
653      */
654     for (;;) {
655         clear_lwkt_resched();
656
657         /*
658          * Hotpath - pull the head of the run queue and attempt to schedule
659          * it.
660          */
661         ntd = TAILQ_FIRST(&gd->gd_tdrunq);
662
663         if (ntd == NULL) {
664             /*
665              * Runq is empty, switch to idle to allow it to halt.
666              */
667             ntd = &gd->gd_idlethread;
668 #ifdef SMP
669             if (gd->gd_trap_nesting_level == 0 && panicstr == NULL)
670                 ASSERT_NO_TOKENS_HELD(ntd);
671 #endif
672             cpu_time.cp_msg[0] = 0;
673             cpu_time.cp_stallpc = 0;
674             goto haveidle;
675         }
676
677         /*
678          * Hotpath - schedule ntd.
679          *
680          * NOTE: For UP there is no mplock and lwkt_getalltokens()
681          *           always succeeds.
682          */
683         if (TD_TOKS_NOT_HELD(ntd) ||
684             lwkt_getalltokens(ntd, (spinning >= lwkt_spin_loops)))
685         {
686             goto havethread;
687         }
688
689         /*
690          * Coldpath (SMP only since tokens always succeed on UP)
691          *
692          * We had some contention on the thread we wanted to schedule.
693          * What we do now is try to find a thread that we can schedule
694          * in its stead.
695          *
696          * The coldpath scan does NOT rearrange threads in the run list.
697          * The lwkt_schedulerclock() will assert need_lwkt_resched() on
698          * the next tick whenever the current head is not the current thread.
699          */
700 #ifdef  INVARIANTS
701         ++ntd->td_contended;
702 #endif
703         ++gd->gd_cnt.v_token_colls;
704
705         if (fairq_bypass > 0)
706                 goto skip;
707
708         while ((ntd = TAILQ_NEXT(ntd, td_threadq)) != NULL) {
709                 /*
710                  * Never schedule threads returning to userland or the
711                  * user thread scheduler helper thread when higher priority
712                  * threads are present.  The runq is sorted by priority
713                  * so we can give up traversing it when we find the first
714                  * low priority thread.
715                  */
716                 if (ntd->td_pri < TDPRI_KERN_LPSCHED) {
717                         ntd = NULL;
718                         break;
719                 }
720
721                 /*
722                  * Try this one.
723                  */
724                 if (TD_TOKS_NOT_HELD(ntd) ||
725                     lwkt_getalltokens(ntd, (spinning >= lwkt_spin_loops))) {
726                         goto havethread;
727                 }
728 #ifdef  INVARIANTS
729                 ++ntd->td_contended;
730 #endif
731                 ++gd->gd_cnt.v_token_colls;
732         }
733
734 skip:
735         /*
736          * We exhausted the run list, meaning that all runnable threads
737          * are contested.
738          */
739         cpu_pause();
740         ntd = &gd->gd_idlethread;
741 #ifdef SMP
742         if (gd->gd_trap_nesting_level == 0 && panicstr == NULL)
743             ASSERT_NO_TOKENS_HELD(ntd);
744         /* contention case, do not clear contention mask */
745 #endif
746
747         /*
748          * We are going to have to retry but if the current thread is not
749          * on the runq we instead switch through the idle thread to get away
750          * from the current thread.  We have to flag for lwkt reschedule
751          * to prevent the idle thread from halting.
752          *
753          * NOTE: A non-zero spinning is passed to lwkt_getalltokens() to
754          *       instruct it to deal with the potential for deadlocks by
755          *       ordering the tokens by address.
756          */
757         if ((td->td_flags & TDF_RUNQ) == 0) {
758             need_lwkt_resched();        /* prevent hlt */
759             goto haveidle;
760         }
761 #if defined(INVARIANTS) && defined(__amd64__)
762         if ((read_rflags() & PSL_I) == 0) {
763                 cpu_enable_intr();
764                 panic("lwkt_switch() called with interrupts disabled");
765         }
766 #endif
767
768         /*
769          * Number iterations so far.  After a certain point we switch to
770          * a sorted-address/monitor/mwait version of lwkt_getalltokens()
771          */
772         if (spinning < 0x7FFFFFFF)
773             ++spinning;
774
775 #ifdef SMP
776         /*
777          * lwkt_getalltokens() failed in sorted token mode, we can use
778          * monitor/mwait in this case.
779          */
780         if (spinning >= lwkt_spin_loops &&
781             (cpu_mi_feature & CPU_MI_MONITOR) &&
782             lwkt_spin_monitor)
783         {
784             cpu_mmw_pause_int(&gd->gd_reqflags,
785                               (gd->gd_reqflags | RQF_SPINNING) &
786                               ~RQF_IDLECHECK_WK_MASK);
787         }
788 #endif
789
790         /*
791          * We already checked that td is still scheduled so this should be
792          * safe.
793          */
794         splz_check();
795
796         /*
797          * This experimental resequencer is used as a fall-back to reduce
798          * hw cache line contention by placing each core's scheduler into a
799          * time-domain-multplexed slot.
800          *
801          * The resequencer is disabled by default.  It's functionality has
802          * largely been superceeded by the token algorithm which limits races
803          * to a subset of cores.
804          *
805          * The resequencer algorithm tends to break down when more than
806          * 20 cores are contending.  What appears to happen is that new
807          * tokens can be obtained out of address-sorted order by new cores
808          * while existing cores languish in long delays between retries and
809          * wind up being starved-out of the token acquisition.
810          */
811         if (lwkt_spin_reseq && spinning >= lwkt_spin_reseq) {
812             int cseq = atomic_fetchadd_int(&lwkt_cseq_windex, 1);
813             int oseq;
814
815             while ((oseq = lwkt_cseq_rindex) != cseq) {
816                 cpu_ccfence();
817 #if 1
818                 if (cpu_mi_feature & CPU_MI_MONITOR) {
819                     cpu_mmw_pause_int(&lwkt_cseq_rindex, oseq);
820                 } else {
821 #endif
822                     cpu_pause();
823                     cpu_lfence();
824 #if 1
825                 }
826 #endif
827             }
828             DELAY(1);
829             atomic_add_int(&lwkt_cseq_rindex, 1);
830         }
831         /* highest level for(;;) loop */
832     }
833
834 havethread:
835     /*
836      * Clear gd_idle_repeat when doing a normal switch to a non-idle
837      * thread.
838      */
839     ntd->td_wmesg = NULL;
840     ++gd->gd_cnt.v_swtch;
841     gd->gd_idle_repeat = 0;
842
843 havethread_preempted:
844     /*
845      * If the new target does not need the MP lock and we are holding it,
846      * release the MP lock.  If the new target requires the MP lock we have
847      * already acquired it for the target.
848      */
849     ;
850 haveidle:
851     KASSERT(ntd->td_critcount,
852             ("priority problem in lwkt_switch %d %d",
853             td->td_critcount, ntd->td_critcount));
854
855     if (td != ntd) {
856         /*
857          * Execute the actual thread switch operation.  This function
858          * returns to the current thread and returns the previous thread
859          * (which may be different from the thread we switched to).
860          *
861          * We are responsible for marking ntd as TDF_RUNNING.
862          */
863         KKASSERT((ntd->td_flags & TDF_RUNNING) == 0);
864         ++switch_count;
865         KTR_LOG(ctxsw_sw, gd->gd_cpuid, ntd);
866         ntd->td_flags |= TDF_RUNNING;
867         lwkt_switch_return(td->td_switch(ntd));
868         /* ntd invalid, td_switch() can return a different thread_t */
869     }
870
871     /*
872      * catch-all.  XXX is this strictly needed?
873      */
874     splz_check();
875
876     /* NOTE: current cpu may have changed after switch */
877     crit_exit_quick(td);
878 }
879
880 /*
881  * Called by assembly in the td_switch (thread restore path) for thread
882  * bootstrap cases which do not 'return' to lwkt_switch().
883  */
884 void
885 lwkt_switch_return(thread_t otd)
886 {
887 #ifdef SMP
888         globaldata_t rgd;
889
890         /*
891          * Check if otd was migrating.  Now that we are on ntd we can finish
892          * up the migration.  This is a bit messy but it is the only place
893          * where td is known to be fully descheduled.
894          *
895          * We can only activate the migration if otd was migrating but not
896          * held on the cpu due to a preemption chain.  We still have to
897          * clear TDF_RUNNING on the old thread either way.
898          *
899          * We are responsible for clearing the previously running thread's
900          * TDF_RUNNING.
901          */
902         if ((rgd = otd->td_migrate_gd) != NULL &&
903             (otd->td_flags & TDF_PREEMPT_LOCK) == 0) {
904                 KKASSERT((otd->td_flags & (TDF_MIGRATING | TDF_RUNNING)) ==
905                          (TDF_MIGRATING | TDF_RUNNING));
906                 otd->td_migrate_gd = NULL;
907                 otd->td_flags &= ~TDF_RUNNING;
908                 lwkt_send_ipiq(rgd, lwkt_setcpu_remote, otd);
909         } else {
910                 otd->td_flags &= ~TDF_RUNNING;
911         }
912 #else
913         otd->td_flags &= ~TDF_RUNNING;
914 #endif
915
916         /*
917          * Final exit validations (see lwp_wait()).  Note that otd becomes
918          * invalid the *instant* we set TDF_MP_EXITSIG.
919          */
920         while (otd->td_flags & TDF_EXITING) {
921                 u_int mpflags;
922
923                 mpflags = otd->td_mpflags;
924                 cpu_ccfence();
925
926                 if (mpflags & TDF_MP_EXITWAIT) {
927                         if (atomic_cmpset_int(&otd->td_mpflags, mpflags,
928                                               mpflags | TDF_MP_EXITSIG)) {
929                                 wakeup(otd);
930                                 break;
931                         }
932                 } else {
933                         if (atomic_cmpset_int(&otd->td_mpflags, mpflags,
934                                               mpflags | TDF_MP_EXITSIG)) {
935                                 wakeup(otd);
936                                 break;
937                         }
938                 }
939         }
940 }
941
942 /*
943  * Request that the target thread preempt the current thread.  Preemption
944  * can only occur if our only critical section is the one that we were called
945  * with, the relative priority of the target thread is higher, and the target
946  * thread holds no tokens.  This also only works if we are not holding any
947  * spinlocks (obviously).
948  *
949  * THE CALLER OF LWKT_PREEMPT() MUST BE IN A CRITICAL SECTION.  Typically
950  * this is called via lwkt_schedule() through the td_preemptable callback.
951  * critcount is the managed critical priority that we should ignore in order
952  * to determine whether preemption is possible (aka usually just the crit
953  * priority of lwkt_schedule() itself).
954  *
955  * Preemption is typically limited to interrupt threads.
956  *
957  * Operation works in a fairly straight-forward manner.  The normal
958  * scheduling code is bypassed and we switch directly to the target
959  * thread.  When the target thread attempts to block or switch away
960  * code at the base of lwkt_switch() will switch directly back to our
961  * thread.  Our thread is able to retain whatever tokens it holds and
962  * if the target needs one of them the target will switch back to us
963  * and reschedule itself normally.
964  */
965 void
966 lwkt_preempt(thread_t ntd, int critcount)
967 {
968     struct globaldata *gd = mycpu;
969     thread_t xtd;
970     thread_t td;
971     int save_gd_intr_nesting_level;
972
973     /*
974      * The caller has put us in a critical section.  We can only preempt
975      * if the caller of the caller was not in a critical section (basically
976      * a local interrupt), as determined by the 'critcount' parameter.  We
977      * also can't preempt if the caller is holding any spinlocks (even if
978      * he isn't in a critical section).  This also handles the tokens test.
979      *
980      * YYY The target thread must be in a critical section (else it must
981      * inherit our critical section?  I dunno yet).
982      */
983     KASSERT(ntd->td_critcount, ("BADCRIT0 %d", ntd->td_pri));
984
985     td = gd->gd_curthread;
986     if (preempt_enable == 0) {
987         ++preempt_miss;
988         return;
989     }
990     if (ntd->td_pri <= td->td_pri) {
991         ++preempt_miss;
992         return;
993     }
994     if (td->td_critcount > critcount) {
995         ++preempt_miss;
996         return;
997     }
998 #ifdef SMP
999     if (td->td_cscount) {
1000         ++preempt_miss;
1001         return;
1002     }
1003     if (ntd->td_gd != gd) {
1004         ++preempt_miss;
1005         return;
1006     }
1007 #endif
1008     /*
1009      * We don't have to check spinlocks here as they will also bump
1010      * td_critcount.
1011      *
1012      * Do not try to preempt if the target thread is holding any tokens.
1013      * We could try to acquire the tokens but this case is so rare there
1014      * is no need to support it.
1015      */
1016     KKASSERT(gd->gd_spinlocks_wr == 0);
1017
1018     if (TD_TOKS_HELD(ntd)) {
1019         ++preempt_miss;
1020         return;
1021     }
1022     if (td == ntd || ((td->td_flags | ntd->td_flags) & TDF_PREEMPT_LOCK)) {
1023         ++preempt_weird;
1024         return;
1025     }
1026     if (ntd->td_preempted) {
1027         ++preempt_hit;
1028         return;
1029     }
1030     KKASSERT(gd->gd_processing_ipiq == 0);
1031
1032     /*
1033      * Since we are able to preempt the current thread, there is no need to
1034      * call need_lwkt_resched().
1035      *
1036      * We must temporarily clear gd_intr_nesting_level around the switch
1037      * since switchouts from the target thread are allowed (they will just
1038      * return to our thread), and since the target thread has its own stack.
1039      *
1040      * A preemption must switch back to the original thread, assert the
1041      * case.
1042      */
1043     ++preempt_hit;
1044     ntd->td_preempted = td;
1045     td->td_flags |= TDF_PREEMPT_LOCK;
1046     KTR_LOG(ctxsw_pre, gd->gd_cpuid, ntd);
1047     save_gd_intr_nesting_level = gd->gd_intr_nesting_level;
1048     gd->gd_intr_nesting_level = 0;
1049
1050     KKASSERT((ntd->td_flags & TDF_RUNNING) == 0);
1051     ntd->td_flags |= TDF_RUNNING;
1052     xtd = td->td_switch(ntd);
1053     KKASSERT(xtd == ntd);
1054     lwkt_switch_return(xtd);
1055     gd->gd_intr_nesting_level = save_gd_intr_nesting_level;
1056
1057     KKASSERT(ntd->td_preempted && (td->td_flags & TDF_PREEMPT_DONE));
1058     ntd->td_preempted = NULL;
1059     td->td_flags &= ~(TDF_PREEMPT_LOCK|TDF_PREEMPT_DONE);
1060 }
1061
1062 /*
1063  * Conditionally call splz() if gd_reqflags indicates work is pending.
1064  * This will work inside a critical section but not inside a hard code
1065  * section.
1066  *
1067  * (self contained on a per cpu basis)
1068  */
1069 void
1070 splz_check(void)
1071 {
1072     globaldata_t gd = mycpu;
1073     thread_t td = gd->gd_curthread;
1074
1075     if ((gd->gd_reqflags & RQF_IDLECHECK_MASK) &&
1076         gd->gd_intr_nesting_level == 0 &&
1077         td->td_nest_count < 2)
1078     {
1079         splz();
1080     }
1081 }
1082
1083 /*
1084  * This version is integrated into crit_exit, reqflags has already
1085  * been tested but td_critcount has not.
1086  *
1087  * We only want to execute the splz() on the 1->0 transition of
1088  * critcount and not in a hard code section or if too deeply nested.
1089  *
1090  * NOTE: gd->gd_spinlocks_wr is implied to be 0 when td_critcount is 0.
1091  */
1092 void
1093 lwkt_maybe_splz(thread_t td)
1094 {
1095     globaldata_t gd = td->td_gd;
1096
1097     if (td->td_critcount == 0 &&
1098         gd->gd_intr_nesting_level == 0 &&
1099         td->td_nest_count < 2)
1100     {
1101         splz();
1102     }
1103 }
1104
1105 /*
1106  * Drivers which set up processing co-threads can call this function to
1107  * run the co-thread at a higher priority and to allow it to preempt
1108  * normal threads.
1109  */
1110 void
1111 lwkt_set_interrupt_support_thread(void)
1112 {
1113         thread_t td = curthread;
1114
1115         lwkt_setpri_self(TDPRI_INT_SUPPORT);
1116         td->td_flags |= TDF_INTTHREAD;
1117         td->td_preemptable = lwkt_preempt;
1118 }
1119
1120
1121 /*
1122  * This function is used to negotiate a passive release of the current
1123  * process/lwp designation with the user scheduler, allowing the user
1124  * scheduler to schedule another user thread.  The related kernel thread
1125  * (curthread) continues running in the released state.
1126  */
1127 void
1128 lwkt_passive_release(struct thread *td)
1129 {
1130     struct lwp *lp = td->td_lwp;
1131
1132     td->td_release = NULL;
1133     lwkt_setpri_self(TDPRI_KERN_USER);
1134     lp->lwp_proc->p_usched->release_curproc(lp);
1135 }
1136
1137
1138 /*
1139  * This implements a LWKT yield, allowing a kernel thread to yield to other
1140  * kernel threads at the same or higher priority.  This function can be
1141  * called in a tight loop and will typically only yield once per tick.
1142  *
1143  * Most kernel threads run at the same priority in order to allow equal
1144  * sharing.
1145  *
1146  * (self contained on a per cpu basis)
1147  */
1148 void
1149 lwkt_yield(void)
1150 {
1151     globaldata_t gd = mycpu;
1152     thread_t td = gd->gd_curthread;
1153
1154     if ((gd->gd_reqflags & RQF_IDLECHECK_MASK) && td->td_nest_count < 2)
1155         splz();
1156     if (lwkt_resched_wanted()) {
1157         lwkt_schedule_self(curthread);
1158         lwkt_switch();
1159     }
1160 }
1161
1162 /*
1163  * The quick version processes pending interrupts and higher-priority
1164  * LWKT threads but will not round-robin same-priority LWKT threads.
1165  *
1166  * When called while attempting to return to userland the only same-pri
1167  * threads are the ones which have already tried to become the current
1168  * user process.
1169  */
1170 void
1171 lwkt_yield_quick(void)
1172 {
1173     globaldata_t gd = mycpu;
1174     thread_t td = gd->gd_curthread;
1175
1176     if ((gd->gd_reqflags & RQF_IDLECHECK_MASK) && td->td_nest_count < 2)
1177         splz();
1178     if (lwkt_resched_wanted()) {
1179         if (TAILQ_FIRST(&gd->gd_tdrunq) == td) {
1180             clear_lwkt_resched();
1181         } else {
1182             lwkt_schedule_self(curthread);
1183             lwkt_switch();
1184         }
1185     }
1186 }
1187
1188 /*
1189  * This yield is designed for kernel threads with a user context.
1190  *
1191  * The kernel acting on behalf of the user is potentially cpu-bound,
1192  * this function will efficiently allow other threads to run and also
1193  * switch to other processes by releasing.
1194  *
1195  * The lwkt_user_yield() function is designed to have very low overhead
1196  * if no yield is determined to be needed.
1197  */
1198 void
1199 lwkt_user_yield(void)
1200 {
1201     globaldata_t gd = mycpu;
1202     thread_t td = gd->gd_curthread;
1203
1204     /*
1205      * Always run any pending interrupts in case we are in a critical
1206      * section.
1207      */
1208     if ((gd->gd_reqflags & RQF_IDLECHECK_MASK) && td->td_nest_count < 2)
1209         splz();
1210
1211     /*
1212      * Switch (which forces a release) if another kernel thread needs
1213      * the cpu, if userland wants us to resched, or if our kernel
1214      * quantum has run out.
1215      */
1216     if (lwkt_resched_wanted() ||
1217         user_resched_wanted())
1218     {
1219         lwkt_switch();
1220     }
1221
1222 #if 0
1223     /*
1224      * Reacquire the current process if we are released.
1225      *
1226      * XXX not implemented atm.  The kernel may be holding locks and such,
1227      *     so we want the thread to continue to receive cpu.
1228      */
1229     if (td->td_release == NULL && lp) {
1230         lp->lwp_proc->p_usched->acquire_curproc(lp);
1231         td->td_release = lwkt_passive_release;
1232         lwkt_setpri_self(TDPRI_USER_NORM);
1233     }
1234 #endif
1235 }
1236
1237 /*
1238  * Generic schedule.  Possibly schedule threads belonging to other cpus and
1239  * deal with threads that might be blocked on a wait queue.
1240  *
1241  * We have a little helper inline function which does additional work after
1242  * the thread has been enqueued, including dealing with preemption and
1243  * setting need_lwkt_resched() (which prevents the kernel from returning
1244  * to userland until it has processed higher priority threads).
1245  *
1246  * It is possible for this routine to be called after a failed _enqueue
1247  * (due to the target thread migrating, sleeping, or otherwise blocked).
1248  * We have to check that the thread is actually on the run queue!
1249  */
1250 static __inline
1251 void
1252 _lwkt_schedule_post(globaldata_t gd, thread_t ntd, int ccount)
1253 {
1254     if (ntd->td_flags & TDF_RUNQ) {
1255         if (ntd->td_preemptable) {
1256             ntd->td_preemptable(ntd, ccount);   /* YYY +token */
1257         }
1258     }
1259 }
1260
1261 static __inline
1262 void
1263 _lwkt_schedule(thread_t td)
1264 {
1265     globaldata_t mygd = mycpu;
1266
1267     KASSERT(td != &td->td_gd->gd_idlethread,
1268             ("lwkt_schedule(): scheduling gd_idlethread is illegal!"));
1269     KKASSERT((td->td_flags & TDF_MIGRATING) == 0);
1270     crit_enter_gd(mygd);
1271     KKASSERT(td->td_lwp == NULL ||
1272              (td->td_lwp->lwp_mpflags & LWP_MP_ONRUNQ) == 0);
1273
1274     if (td == mygd->gd_curthread) {
1275         _lwkt_enqueue(td);
1276     } else {
1277         /*
1278          * If we own the thread, there is no race (since we are in a
1279          * critical section).  If we do not own the thread there might
1280          * be a race but the target cpu will deal with it.
1281          */
1282 #ifdef SMP
1283         if (td->td_gd == mygd) {
1284             _lwkt_enqueue(td);
1285             _lwkt_schedule_post(mygd, td, 1);
1286         } else {
1287             lwkt_send_ipiq3(td->td_gd, lwkt_schedule_remote, td, 0);
1288         }
1289 #else
1290         _lwkt_enqueue(td);
1291         _lwkt_schedule_post(mygd, td, 1);
1292 #endif
1293     }
1294     crit_exit_gd(mygd);
1295 }
1296
1297 void
1298 lwkt_schedule(thread_t td)
1299 {
1300     _lwkt_schedule(td);
1301 }
1302
1303 void
1304 lwkt_schedule_noresched(thread_t td)    /* XXX not impl */
1305 {
1306     _lwkt_schedule(td);
1307 }
1308
1309 #ifdef SMP
1310
1311 /*
1312  * When scheduled remotely if frame != NULL the IPIQ is being
1313  * run via doreti or an interrupt then preemption can be allowed.
1314  *
1315  * To allow preemption we have to drop the critical section so only
1316  * one is present in _lwkt_schedule_post.
1317  */
1318 static void
1319 lwkt_schedule_remote(void *arg, int arg2, struct intrframe *frame)
1320 {
1321     thread_t td = curthread;
1322     thread_t ntd = arg;
1323
1324     if (frame && ntd->td_preemptable) {
1325         crit_exit_noyield(td);
1326         _lwkt_schedule(ntd);
1327         crit_enter_quick(td);
1328     } else {
1329         _lwkt_schedule(ntd);
1330     }
1331 }
1332
1333 /*
1334  * Thread migration using a 'Pull' method.  The thread may or may not be
1335  * the current thread.  It MUST be descheduled and in a stable state.
1336  * lwkt_giveaway() must be called on the cpu owning the thread.
1337  *
1338  * At any point after lwkt_giveaway() is called, the target cpu may
1339  * 'pull' the thread by calling lwkt_acquire().
1340  *
1341  * We have to make sure the thread is not sitting on a per-cpu tsleep
1342  * queue or it will blow up when it moves to another cpu.
1343  *
1344  * MPSAFE - must be called under very specific conditions.
1345  */
1346 void
1347 lwkt_giveaway(thread_t td)
1348 {
1349     globaldata_t gd = mycpu;
1350
1351     crit_enter_gd(gd);
1352     if (td->td_flags & TDF_TSLEEPQ)
1353         tsleep_remove(td);
1354     KKASSERT(td->td_gd == gd);
1355     TAILQ_REMOVE(&gd->gd_tdallq, td, td_allq);
1356     td->td_flags |= TDF_MIGRATING;
1357     crit_exit_gd(gd);
1358 }
1359
1360 void
1361 lwkt_acquire(thread_t td)
1362 {
1363     globaldata_t gd;
1364     globaldata_t mygd;
1365     int retry = 10000000;
1366
1367     KKASSERT(td->td_flags & TDF_MIGRATING);
1368     gd = td->td_gd;
1369     mygd = mycpu;
1370     if (gd != mycpu) {
1371         cpu_lfence();
1372         KKASSERT((td->td_flags & TDF_RUNQ) == 0);
1373         crit_enter_gd(mygd);
1374         DEBUG_PUSH_INFO("lwkt_acquire");
1375         while (td->td_flags & (TDF_RUNNING|TDF_PREEMPT_LOCK)) {
1376 #ifdef SMP
1377             lwkt_process_ipiq();
1378 #endif
1379             cpu_lfence();
1380             if (--retry == 0) {
1381                 kprintf("lwkt_acquire: stuck: td %p td->td_flags %08x\n",
1382                         td, td->td_flags);
1383                 retry = 10000000;
1384             }
1385         }
1386         DEBUG_POP_INFO();
1387         cpu_mfence();
1388         td->td_gd = mygd;
1389         TAILQ_INSERT_TAIL(&mygd->gd_tdallq, td, td_allq);
1390         td->td_flags &= ~TDF_MIGRATING;
1391         crit_exit_gd(mygd);
1392     } else {
1393         crit_enter_gd(mygd);
1394         TAILQ_INSERT_TAIL(&mygd->gd_tdallq, td, td_allq);
1395         td->td_flags &= ~TDF_MIGRATING;
1396         crit_exit_gd(mygd);
1397     }
1398 }
1399
1400 #endif
1401
1402 /*
1403  * Generic deschedule.  Descheduling threads other then your own should be
1404  * done only in carefully controlled circumstances.  Descheduling is 
1405  * asynchronous.  
1406  *
1407  * This function may block if the cpu has run out of messages.
1408  */
1409 void
1410 lwkt_deschedule(thread_t td)
1411 {
1412     crit_enter();
1413 #ifdef SMP
1414     if (td == curthread) {
1415         _lwkt_dequeue(td);
1416     } else {
1417         if (td->td_gd == mycpu) {
1418             _lwkt_dequeue(td);
1419         } else {
1420             lwkt_send_ipiq(td->td_gd, (ipifunc1_t)lwkt_deschedule, td);
1421         }
1422     }
1423 #else
1424     _lwkt_dequeue(td);
1425 #endif
1426     crit_exit();
1427 }
1428
1429 /*
1430  * Set the target thread's priority.  This routine does not automatically
1431  * switch to a higher priority thread, LWKT threads are not designed for
1432  * continuous priority changes.  Yield if you want to switch.
1433  */
1434 void
1435 lwkt_setpri(thread_t td, int pri)
1436 {
1437     if (td->td_pri != pri) {
1438         KKASSERT(pri >= 0);
1439         crit_enter();
1440         if (td->td_flags & TDF_RUNQ) {
1441             KKASSERT(td->td_gd == mycpu);
1442             _lwkt_dequeue(td);
1443             td->td_pri = pri;
1444             _lwkt_enqueue(td);
1445         } else {
1446             td->td_pri = pri;
1447         }
1448         crit_exit();
1449     }
1450 }
1451
1452 /*
1453  * Set the initial priority for a thread prior to it being scheduled for
1454  * the first time.  The thread MUST NOT be scheduled before or during
1455  * this call.  The thread may be assigned to a cpu other then the current
1456  * cpu.
1457  *
1458  * Typically used after a thread has been created with TDF_STOPPREQ,
1459  * and before the thread is initially scheduled.
1460  */
1461 void
1462 lwkt_setpri_initial(thread_t td, int pri)
1463 {
1464     KKASSERT(pri >= 0);
1465     KKASSERT((td->td_flags & TDF_RUNQ) == 0);
1466     td->td_pri = pri;
1467 }
1468
1469 void
1470 lwkt_setpri_self(int pri)
1471 {
1472     thread_t td = curthread;
1473
1474     KKASSERT(pri >= 0 && pri <= TDPRI_MAX);
1475     crit_enter();
1476     if (td->td_flags & TDF_RUNQ) {
1477         _lwkt_dequeue(td);
1478         td->td_pri = pri;
1479         _lwkt_enqueue(td);
1480     } else {
1481         td->td_pri = pri;
1482     }
1483     crit_exit();
1484 }
1485
1486 /*
1487  * hz tick scheduler clock for LWKT threads
1488  */
1489 void
1490 lwkt_schedulerclock(thread_t td)
1491 {
1492     globaldata_t gd = td->td_gd;
1493     thread_t xtd;
1494
1495     if (TAILQ_FIRST(&gd->gd_tdrunq) == td) {
1496         /*
1497          * If the current thread is at the head of the runq shift it to the
1498          * end of any equal-priority threads and request a LWKT reschedule
1499          * if it moved.
1500          */
1501         xtd = TAILQ_NEXT(td, td_threadq);
1502         if (xtd && xtd->td_pri == td->td_pri) {
1503             TAILQ_REMOVE(&gd->gd_tdrunq, td, td_threadq);
1504             while (xtd && xtd->td_pri == td->td_pri)
1505                 xtd = TAILQ_NEXT(xtd, td_threadq);
1506             if (xtd)
1507                 TAILQ_INSERT_BEFORE(xtd, td, td_threadq);
1508             else
1509                 TAILQ_INSERT_TAIL(&gd->gd_tdrunq, td, td_threadq);
1510             need_lwkt_resched();
1511         }
1512     } else {
1513         /*
1514          * If we scheduled a thread other than the one at the head of the
1515          * queue always request a reschedule every tick.
1516          */
1517         need_lwkt_resched();
1518     }
1519 }
1520
1521 /*
1522  * Migrate the current thread to the specified cpu. 
1523  *
1524  * This is accomplished by descheduling ourselves from the current cpu
1525  * and setting td_migrate_gd.  The lwkt_switch() code will detect that the
1526  * 'old' thread wants to migrate after it has been completely switched out
1527  * and will complete the migration.
1528  *
1529  * TDF_MIGRATING prevents scheduling races while the thread is being migrated.
1530  *
1531  * We must be sure to release our current process designation (if a user
1532  * process) before clearing out any tsleepq we are on because the release
1533  * code may re-add us.
1534  *
1535  * We must be sure to remove ourselves from the current cpu's tsleepq
1536  * before potentially moving to another queue.  The thread can be on
1537  * a tsleepq due to a left-over tsleep_interlock().
1538  */
1539
1540 void
1541 lwkt_setcpu_self(globaldata_t rgd)
1542 {
1543 #ifdef SMP
1544     thread_t td = curthread;
1545
1546     if (td->td_gd != rgd) {
1547         crit_enter_quick(td);
1548
1549         if (td->td_release)
1550             td->td_release(td);
1551         if (td->td_flags & TDF_TSLEEPQ)
1552             tsleep_remove(td);
1553
1554         /*
1555          * Set TDF_MIGRATING to prevent a spurious reschedule while we are
1556          * trying to deschedule ourselves and switch away, then deschedule
1557          * ourself, remove us from tdallq, and set td_migrate_gd.  Finally,
1558          * call lwkt_switch() to complete the operation.
1559          */
1560         td->td_flags |= TDF_MIGRATING;
1561         lwkt_deschedule_self(td);
1562         TAILQ_REMOVE(&td->td_gd->gd_tdallq, td, td_allq);
1563         td->td_migrate_gd = rgd;
1564         lwkt_switch();
1565
1566         /*
1567          * We are now on the target cpu
1568          */
1569         KKASSERT(rgd == mycpu);
1570         TAILQ_INSERT_TAIL(&rgd->gd_tdallq, td, td_allq);
1571         crit_exit_quick(td);
1572     }
1573 #endif
1574 }
1575
1576 void
1577 lwkt_migratecpu(int cpuid)
1578 {
1579 #ifdef SMP
1580         globaldata_t rgd;
1581
1582         rgd = globaldata_find(cpuid);
1583         lwkt_setcpu_self(rgd);
1584 #endif
1585 }
1586
1587 #ifdef SMP
1588 /*
1589  * Remote IPI for cpu migration (called while in a critical section so we
1590  * do not have to enter another one).
1591  *
1592  * The thread (td) has already been completely descheduled from the
1593  * originating cpu and we can simply assert the case.  The thread is
1594  * assigned to the new cpu and enqueued.
1595  *
1596  * The thread will re-add itself to tdallq when it resumes execution.
1597  */
1598 static void
1599 lwkt_setcpu_remote(void *arg)
1600 {
1601     thread_t td = arg;
1602     globaldata_t gd = mycpu;
1603
1604     KKASSERT((td->td_flags & (TDF_RUNNING|TDF_PREEMPT_LOCK)) == 0);
1605     td->td_gd = gd;
1606     cpu_mfence();
1607     td->td_flags &= ~TDF_MIGRATING;
1608     KKASSERT(td->td_migrate_gd == NULL);
1609     KKASSERT(td->td_lwp == NULL ||
1610             (td->td_lwp->lwp_mpflags & LWP_MP_ONRUNQ) == 0);
1611     _lwkt_enqueue(td);
1612 }
1613 #endif
1614
1615 struct lwp *
1616 lwkt_preempted_proc(void)
1617 {
1618     thread_t td = curthread;
1619     while (td->td_preempted)
1620         td = td->td_preempted;
1621     return(td->td_lwp);
1622 }
1623
1624 /*
1625  * Create a kernel process/thread/whatever.  It shares it's address space
1626  * with proc0 - ie: kernel only.
1627  *
1628  * If the cpu is not specified one will be selected.  In the future
1629  * specifying a cpu of -1 will enable kernel thread migration between
1630  * cpus.
1631  */
1632 int
1633 lwkt_create(void (*func)(void *), void *arg, struct thread **tdp,
1634             thread_t template, int tdflags, int cpu, const char *fmt, ...)
1635 {
1636     thread_t td;
1637     __va_list ap;
1638
1639     td = lwkt_alloc_thread(template, LWKT_THREAD_STACK, cpu,
1640                            tdflags);
1641     if (tdp)
1642         *tdp = td;
1643     cpu_set_thread_handler(td, lwkt_exit, func, arg);
1644
1645     /*
1646      * Set up arg0 for 'ps' etc
1647      */
1648     __va_start(ap, fmt);
1649     kvsnprintf(td->td_comm, sizeof(td->td_comm), fmt, ap);
1650     __va_end(ap);
1651
1652     /*
1653      * Schedule the thread to run
1654      */
1655     if (td->td_flags & TDF_NOSTART)
1656         td->td_flags &= ~TDF_NOSTART;
1657     else
1658         lwkt_schedule(td);
1659     return 0;
1660 }
1661
1662 /*
1663  * Destroy an LWKT thread.   Warning!  This function is not called when
1664  * a process exits, cpu_proc_exit() directly calls cpu_thread_exit() and
1665  * uses a different reaping mechanism.
1666  */
1667 void
1668 lwkt_exit(void)
1669 {
1670     thread_t td = curthread;
1671     thread_t std;
1672     globaldata_t gd;
1673
1674     /*
1675      * Do any cleanup that might block here
1676      */
1677     if (td->td_flags & TDF_VERBOSE)
1678         kprintf("kthread %p %s has exited\n", td, td->td_comm);
1679     caps_exit(td);
1680     biosched_done(td);
1681     dsched_exit_thread(td);
1682
1683     /*
1684      * Get us into a critical section to interlock gd_freetd and loop
1685      * until we can get it freed.
1686      *
1687      * We have to cache the current td in gd_freetd because objcache_put()ing
1688      * it would rip it out from under us while our thread is still active.
1689      *
1690      * We are the current thread so of course our own TDF_RUNNING bit will
1691      * be set, so unlike the lwp reap code we don't wait for it to clear.
1692      */
1693     gd = mycpu;
1694     crit_enter_quick(td);
1695     for (;;) {
1696         if (td->td_refs) {
1697             tsleep(td, 0, "tdreap", 1);
1698             continue;
1699         }
1700         if ((std = gd->gd_freetd) != NULL) {
1701             KKASSERT((std->td_flags & (TDF_RUNNING|TDF_PREEMPT_LOCK)) == 0);
1702             gd->gd_freetd = NULL;
1703             objcache_put(thread_cache, std);
1704             continue;
1705         }
1706         break;
1707     }
1708
1709     /*
1710      * Remove thread resources from kernel lists and deschedule us for
1711      * the last time.  We cannot block after this point or we may end
1712      * up with a stale td on the tsleepq.
1713      *
1714      * None of this may block, the critical section is the only thing
1715      * protecting tdallq and the only thing preventing new lwkt_hold()
1716      * thread refs now.
1717      */
1718     if (td->td_flags & TDF_TSLEEPQ)
1719         tsleep_remove(td);
1720     lwkt_deschedule_self(td);
1721     lwkt_remove_tdallq(td);
1722     KKASSERT(td->td_refs == 0);
1723
1724     /*
1725      * Final cleanup
1726      */
1727     KKASSERT(gd->gd_freetd == NULL);
1728     if (td->td_flags & TDF_ALLOCATED_THREAD)
1729         gd->gd_freetd = td;
1730     cpu_thread_exit();
1731 }
1732
1733 void
1734 lwkt_remove_tdallq(thread_t td)
1735 {
1736     KKASSERT(td->td_gd == mycpu);
1737     TAILQ_REMOVE(&td->td_gd->gd_tdallq, td, td_allq);
1738 }
1739
1740 /*
1741  * Code reduction and branch prediction improvements.  Call/return
1742  * overhead on modern cpus often degenerates into 0 cycles due to
1743  * the cpu's branch prediction hardware and return pc cache.  We
1744  * can take advantage of this by not inlining medium-complexity
1745  * functions and we can also reduce the branch prediction impact
1746  * by collapsing perfectly predictable branches into a single
1747  * procedure instead of duplicating it.
1748  *
1749  * Is any of this noticeable?  Probably not, so I'll take the
1750  * smaller code size.
1751  */
1752 void
1753 crit_exit_wrapper(__DEBUG_CRIT_ARG__)
1754 {
1755     _crit_exit(mycpu __DEBUG_CRIT_PASS_ARG__);
1756 }
1757
1758 void
1759 crit_panic(void)
1760 {
1761     thread_t td = curthread;
1762     int lcrit = td->td_critcount;
1763
1764     td->td_critcount = 0;
1765     panic("td_critcount is/would-go negative! %p %d", td, lcrit);
1766     /* NOT REACHED */
1767 }
1768
1769 #ifdef SMP
1770
1771 /*
1772  * Called from debugger/panic on cpus which have been stopped.  We must still
1773  * process the IPIQ while stopped, even if we were stopped while in a critical
1774  * section (XXX).
1775  *
1776  * If we are dumping also try to process any pending interrupts.  This may
1777  * or may not work depending on the state of the cpu at the point it was
1778  * stopped.
1779  */
1780 void
1781 lwkt_smp_stopped(void)
1782 {
1783     globaldata_t gd = mycpu;
1784
1785     crit_enter_gd(gd);
1786     if (dumping) {
1787         lwkt_process_ipiq();
1788         splz();
1789     } else {
1790         lwkt_process_ipiq();
1791     }
1792     crit_exit_gd(gd);
1793 }
1794
1795 #endif