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