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