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