xref: /dflybsd-src/sys/kern/usched_bsd4.c (revision 37d4ea13cefac0f93287e0a0a1d5f304a492ffe7)
1 /*
2  * Copyright (c) 1999 Peter Wemm <peter@FreeBSD.org>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  * $DragonFly: src/sys/kern/usched_bsd4.c,v 1.26 2008/11/01 23:31:19 dillon Exp $
27  */
28 
29 #include <sys/param.h>
30 #include <sys/systm.h>
31 #include <sys/kernel.h>
32 #include <sys/lock.h>
33 #include <sys/queue.h>
34 #include <sys/proc.h>
35 #include <sys/rtprio.h>
36 #include <sys/uio.h>
37 #include <sys/sysctl.h>
38 #include <sys/resourcevar.h>
39 #include <sys/spinlock.h>
40 #include <machine/cpu.h>
41 #include <machine/smp.h>
42 
43 #include <sys/thread2.h>
44 #include <sys/spinlock2.h>
45 #include <sys/mplock2.h>
46 
47 /*
48  * Priorities.  Note that with 32 run queues per scheduler each queue
49  * represents four priority levels.
50  */
51 
52 #define MAXPRI			128
53 #define PRIMASK			(MAXPRI - 1)
54 #define PRIBASE_REALTIME	0
55 #define PRIBASE_NORMAL		MAXPRI
56 #define PRIBASE_IDLE		(MAXPRI * 2)
57 #define PRIBASE_THREAD		(MAXPRI * 3)
58 #define PRIBASE_NULL		(MAXPRI * 4)
59 
60 #define NQS	32			/* 32 run queues. */
61 #define PPQ	(MAXPRI / NQS)		/* priorities per queue */
62 #define PPQMASK	(PPQ - 1)
63 
64 /*
65  * NICEPPQ	- number of nice units per priority queue
66  * ESTCPURAMP	- number of scheduler ticks for estcpu to switch queues
67  *
68  * ESTCPUPPQ	- number of estcpu units per priority queue
69  * ESTCPUMAX	- number of estcpu units
70  * ESTCPUINCR	- amount we have to increment p_estcpu per scheduling tick at
71  *		  100% cpu.
72  */
73 #define NICEPPQ		2
74 #define ESTCPURAMP	4
75 #define ESTCPUPPQ	512
76 #define ESTCPUMAX	(ESTCPUPPQ * NQS)
77 #define ESTCPUINCR	(ESTCPUPPQ / ESTCPURAMP)
78 #define PRIO_RANGE	(PRIO_MAX - PRIO_MIN + 1)
79 
80 #define ESTCPULIM(v)	min((v), ESTCPUMAX)
81 
82 TAILQ_HEAD(rq, lwp);
83 
84 #define lwp_priority	lwp_usdata.bsd4.priority
85 #define lwp_rqindex	lwp_usdata.bsd4.rqindex
86 #define lwp_origcpu	lwp_usdata.bsd4.origcpu
87 #define lwp_estcpu	lwp_usdata.bsd4.estcpu
88 #define lwp_rqtype	lwp_usdata.bsd4.rqtype
89 
90 static void bsd4_acquire_curproc(struct lwp *lp);
91 static void bsd4_release_curproc(struct lwp *lp);
92 static void bsd4_select_curproc(globaldata_t gd);
93 static void bsd4_setrunqueue(struct lwp *lp);
94 static void bsd4_schedulerclock(struct lwp *lp, sysclock_t period,
95 				sysclock_t cpstamp);
96 static void bsd4_recalculate_estcpu(struct lwp *lp);
97 static void bsd4_resetpriority(struct lwp *lp);
98 static void bsd4_forking(struct lwp *plp, struct lwp *lp);
99 static void bsd4_exiting(struct lwp *plp, struct lwp *lp);
100 static void bsd4_yield(struct lwp *lp);
101 
102 #ifdef SMP
103 static void need_user_resched_remote(void *dummy);
104 #endif
105 static struct lwp *chooseproc_locked(struct lwp *chklp);
106 static void bsd4_remrunqueue_locked(struct lwp *lp);
107 static void bsd4_setrunqueue_locked(struct lwp *lp);
108 
109 struct usched usched_bsd4 = {
110 	{ NULL },
111 	"bsd4", "Original DragonFly Scheduler",
112 	NULL,			/* default registration */
113 	NULL,			/* default deregistration */
114 	bsd4_acquire_curproc,
115 	bsd4_release_curproc,
116 	bsd4_setrunqueue,
117 	bsd4_schedulerclock,
118 	bsd4_recalculate_estcpu,
119 	bsd4_resetpriority,
120 	bsd4_forking,
121 	bsd4_exiting,
122 	NULL,			/* setcpumask not supported */
123 	bsd4_yield
124 };
125 
126 struct usched_bsd4_pcpu {
127 	struct thread helper_thread;
128 	short	rrcount;
129 	short	upri;
130 	struct lwp *uschedcp;
131 };
132 
133 typedef struct usched_bsd4_pcpu	*bsd4_pcpu_t;
134 
135 /*
136  * We have NQS (32) run queues per scheduling class.  For the normal
137  * class, there are 128 priorities scaled onto these 32 queues.  New
138  * processes are added to the last entry in each queue, and processes
139  * are selected for running by taking them from the head and maintaining
140  * a simple FIFO arrangement.  Realtime and Idle priority processes have
141  * and explicit 0-31 priority which maps directly onto their class queue
142  * index.  When a queue has something in it, the corresponding bit is
143  * set in the queuebits variable, allowing a single read to determine
144  * the state of all 32 queues and then a ffs() to find the first busy
145  * queue.
146  */
147 static struct rq bsd4_queues[NQS];
148 static struct rq bsd4_rtqueues[NQS];
149 static struct rq bsd4_idqueues[NQS];
150 static u_int32_t bsd4_queuebits;
151 static u_int32_t bsd4_rtqueuebits;
152 static u_int32_t bsd4_idqueuebits;
153 static cpumask_t bsd4_curprocmask = -1;	/* currently running a user process */
154 static cpumask_t bsd4_rdyprocmask;	/* ready to accept a user process */
155 static int	 bsd4_runqcount;
156 #ifdef SMP
157 static volatile int bsd4_scancpu;
158 #endif
159 static struct spinlock bsd4_spin;
160 static struct usched_bsd4_pcpu bsd4_pcpu[MAXCPU];
161 
162 SYSCTL_INT(_debug, OID_AUTO, bsd4_runqcount, CTLFLAG_RD, &bsd4_runqcount, 0,
163     "Number of run queues");
164 #ifdef INVARIANTS
165 static int usched_nonoptimal;
166 SYSCTL_INT(_debug, OID_AUTO, usched_nonoptimal, CTLFLAG_RW,
167         &usched_nonoptimal, 0, "acquire_curproc() was not optimal");
168 static int usched_optimal;
169 SYSCTL_INT(_debug, OID_AUTO, usched_optimal, CTLFLAG_RW,
170         &usched_optimal, 0, "acquire_curproc() was optimal");
171 #endif
172 static int usched_debug = -1;
173 SYSCTL_INT(_debug, OID_AUTO, scdebug, CTLFLAG_RW, &usched_debug, 0,
174     "Print debug information for this pid");
175 #ifdef SMP
176 static int remote_resched_nonaffinity;
177 static int remote_resched_affinity;
178 static int choose_affinity;
179 SYSCTL_INT(_debug, OID_AUTO, remote_resched_nonaffinity, CTLFLAG_RD,
180         &remote_resched_nonaffinity, 0, "Number of remote rescheds");
181 SYSCTL_INT(_debug, OID_AUTO, remote_resched_affinity, CTLFLAG_RD,
182         &remote_resched_affinity, 0, "Number of remote rescheds");
183 SYSCTL_INT(_debug, OID_AUTO, choose_affinity, CTLFLAG_RD,
184         &choose_affinity, 0, "chooseproc() was smart");
185 #endif
186 
187 static int usched_bsd4_rrinterval = (ESTCPUFREQ + 9) / 10;
188 SYSCTL_INT(_kern, OID_AUTO, usched_bsd4_rrinterval, CTLFLAG_RW,
189         &usched_bsd4_rrinterval, 0, "");
190 static int usched_bsd4_decay = 1;
191 SYSCTL_INT(_kern, OID_AUTO, usched_bsd4_decay, CTLFLAG_RW,
192         &usched_bsd4_decay, 0, "Extra decay when not running");
193 
194 /*
195  * Initialize the run queues at boot time.
196  */
197 static void
198 rqinit(void *dummy)
199 {
200 	int i;
201 
202 	spin_init(&bsd4_spin);
203 	for (i = 0; i < NQS; i++) {
204 		TAILQ_INIT(&bsd4_queues[i]);
205 		TAILQ_INIT(&bsd4_rtqueues[i]);
206 		TAILQ_INIT(&bsd4_idqueues[i]);
207 	}
208 	atomic_clear_cpumask(&bsd4_curprocmask, 1);
209 }
210 SYSINIT(runqueue, SI_BOOT2_USCHED, SI_ORDER_FIRST, rqinit, NULL)
211 
212 /*
213  * BSD4_ACQUIRE_CURPROC
214  *
215  * This function is called when the kernel intends to return to userland.
216  * It is responsible for making the thread the current designated userland
217  * thread for this cpu, blocking if necessary.
218  *
219  * The kernel has already depressed our LWKT priority so we must not switch
220  * until we have either assigned or disposed of the thread.
221  *
222  * WARNING! THIS FUNCTION IS ALLOWED TO CAUSE THE CURRENT THREAD TO MIGRATE
223  * TO ANOTHER CPU!  Because most of the kernel assumes that no migration will
224  * occur, this function is called only under very controlled circumstances.
225  *
226  * MPSAFE
227  */
228 static void
229 bsd4_acquire_curproc(struct lwp *lp)
230 {
231 	globaldata_t gd;
232 	bsd4_pcpu_t dd;
233 	struct lwp *olp;
234 
235 	crit_enter();
236 	bsd4_recalculate_estcpu(lp);
237 
238 	/*
239 	 * If a reschedule was requested give another thread the
240 	 * driver's seat.
241 	 */
242 	if (user_resched_wanted()) {
243 		clear_user_resched();
244 		bsd4_release_curproc(lp);
245 	}
246 
247 	/*
248 	 * Loop until we are the current user thread
249 	 */
250 	do {
251 		/*
252 		 * Reload after a switch or setrunqueue/switch possibly
253 		 * moved us to another cpu.
254 		 */
255 		/*clear_lwkt_resched();*/
256 		gd = mycpu;
257 		dd = &bsd4_pcpu[gd->gd_cpuid];
258 
259 		/*
260 		 * Become the currently scheduled user thread for this cpu
261 		 * if we can do so trivially.
262 		 *
263 		 * We can steal another thread's current thread designation
264 		 * on this cpu since if we are running that other thread
265 		 * must not be, so we can safely deschedule it.
266 		 */
267 		if (dd->uschedcp == lp) {
268 			/*
269 			 * We are already the current lwp (hot path).
270 			 */
271 			dd->upri = lp->lwp_priority;
272 		} else if (dd->uschedcp == NULL) {
273 			/*
274 			 * We can trivially become the current lwp.
275 			 */
276 			atomic_set_cpumask(&bsd4_curprocmask, gd->gd_cpumask);
277 			dd->uschedcp = lp;
278 			dd->upri = lp->lwp_priority;
279 		} else if (dd->upri > lp->lwp_priority) {
280 			/*
281 			 * We can steal the current lwp designation from the
282 			 * olp that was previously assigned to this cpu.
283 			 */
284 			olp = dd->uschedcp;
285 			dd->uschedcp = lp;
286 			dd->upri = lp->lwp_priority;
287 			lwkt_deschedule(olp->lwp_thread);
288 			bsd4_setrunqueue(olp);
289 		} else {
290 			/*
291 			 * We cannot become the current lwp, place the lp
292 			 * on the bsd4 run-queue and deschedule ourselves.
293 			 */
294 			lwkt_deschedule(lp->lwp_thread);
295 			bsd4_setrunqueue(lp);
296 			lwkt_switch();
297 		}
298 
299 		/*
300 		 * Other threads at our current user priority have already
301 		 * put in their bids, but we must run any kernel threads
302 		 * at higher priorities, and we could lose our bid to
303 		 * another thread trying to return to user mode in the
304 		 * process.
305 		 *
306 		 * If we lose our bid we will be descheduled and put on
307 		 * the run queue.  When we are reactivated we will have
308 		 * another chance.
309 		 */
310 		if (lwkt_resched_wanted() ||
311 		    lp->lwp_thread->td_fairq_accum < 0) {
312 			lwkt_switch();
313 		}
314 	} while (dd->uschedcp != lp);
315 
316 	crit_exit();
317 	KKASSERT((lp->lwp_flag & LWP_ONRUNQ) == 0);
318 }
319 
320 /*
321  * BSD4_RELEASE_CURPROC
322  *
323  * This routine detaches the current thread from the userland scheduler,
324  * usually because the thread needs to run or block in the kernel (at
325  * kernel priority) for a while.
326  *
327  * This routine is also responsible for selecting a new thread to
328  * make the current thread.
329  *
330  * NOTE: This implementation differs from the dummy example in that
331  * bsd4_select_curproc() is able to select the current process, whereas
332  * dummy_select_curproc() is not able to select the current process.
333  * This means we have to NULL out uschedcp.
334  *
335  * Additionally, note that we may already be on a run queue if releasing
336  * via the lwkt_switch() in bsd4_setrunqueue().
337  *
338  * MPSAFE
339  */
340 static void
341 bsd4_release_curproc(struct lwp *lp)
342 {
343 	globaldata_t gd = mycpu;
344 	bsd4_pcpu_t dd = &bsd4_pcpu[gd->gd_cpuid];
345 
346 	if (dd->uschedcp == lp) {
347 		crit_enter();
348 		KKASSERT((lp->lwp_flag & LWP_ONRUNQ) == 0);
349 		dd->uschedcp = NULL;	/* don't let lp be selected */
350 		dd->upri = PRIBASE_NULL;
351 		atomic_clear_cpumask(&bsd4_curprocmask, gd->gd_cpumask);
352 		bsd4_select_curproc(gd);
353 		crit_exit();
354 	}
355 }
356 
357 /*
358  * BSD4_SELECT_CURPROC
359  *
360  * Select a new current process for this cpu and clear any pending user
361  * reschedule request.  The cpu currently has no current process.
362  *
363  * This routine is also responsible for equal-priority round-robining,
364  * typically triggered from bsd4_schedulerclock().  In our dummy example
365  * all the 'user' threads are LWKT scheduled all at once and we just
366  * call lwkt_switch().
367  *
368  * The calling process is not on the queue and cannot be selected.
369  *
370  * MPSAFE
371  */
372 static
373 void
374 bsd4_select_curproc(globaldata_t gd)
375 {
376 	bsd4_pcpu_t dd = &bsd4_pcpu[gd->gd_cpuid];
377 	struct lwp *nlp;
378 	int cpuid = gd->gd_cpuid;
379 
380 	crit_enter_gd(gd);
381 
382 	spin_lock(&bsd4_spin);
383 	if ((nlp = chooseproc_locked(dd->uschedcp)) != NULL) {
384 		atomic_set_cpumask(&bsd4_curprocmask, CPUMASK(cpuid));
385 		dd->upri = nlp->lwp_priority;
386 		dd->uschedcp = nlp;
387 		spin_unlock(&bsd4_spin);
388 #ifdef SMP
389 		lwkt_acquire(nlp->lwp_thread);
390 #endif
391 		lwkt_schedule(nlp->lwp_thread);
392 	} else {
393 		spin_unlock(&bsd4_spin);
394 	}
395 #if 0
396 	} else if (bsd4_runqcount && (bsd4_rdyprocmask & CPUMASK(cpuid))) {
397 		atomic_clear_cpumask(&bsd4_rdyprocmask, CPUMASK(cpuid));
398 		spin_unlock(&bsd4_spin);
399 		lwkt_schedule(&dd->helper_thread);
400 	} else {
401 		spin_unlock(&bsd4_spin);
402 	}
403 #endif
404 	crit_exit_gd(gd);
405 }
406 
407 /*
408  * BSD4_SETRUNQUEUE
409  *
410  * Place the specified lwp on the user scheduler's run queue.  This routine
411  * must be called with the thread descheduled.  The lwp must be runnable.
412  *
413  * The thread may be the current thread as a special case.
414  *
415  * MPSAFE
416  */
417 static void
418 bsd4_setrunqueue(struct lwp *lp)
419 {
420 	globaldata_t gd;
421 	bsd4_pcpu_t dd;
422 #ifdef SMP
423 	int cpuid;
424 	cpumask_t mask;
425 	cpumask_t tmpmask;
426 #endif
427 
428 	/*
429 	 * First validate the process state relative to the current cpu.
430 	 * We don't need the spinlock for this, just a critical section.
431 	 * We are in control of the process.
432 	 */
433 	crit_enter();
434 	KASSERT(lp->lwp_stat == LSRUN, ("setrunqueue: lwp not LSRUN"));
435 	KASSERT((lp->lwp_flag & LWP_ONRUNQ) == 0,
436 	    ("lwp %d/%d already on runq! flag %08x/%08x", lp->lwp_proc->p_pid,
437 	     lp->lwp_tid, lp->lwp_proc->p_flag, lp->lwp_flag));
438 	KKASSERT((lp->lwp_thread->td_flags & TDF_RUNQ) == 0);
439 
440 	/*
441 	 * Note: gd and dd are relative to the target thread's last cpu,
442 	 * NOT our current cpu.
443 	 */
444 	gd = lp->lwp_thread->td_gd;
445 	dd = &bsd4_pcpu[gd->gd_cpuid];
446 
447 	/*
448 	 * This process is not supposed to be scheduled anywhere or assigned
449 	 * as the current process anywhere.  Assert the condition.
450 	 */
451 	KKASSERT(dd->uschedcp != lp);
452 
453 #ifndef SMP
454 	/*
455 	 * If we are not SMP we do not have a scheduler helper to kick
456 	 * and must directly activate the process if none are scheduled.
457 	 *
458 	 * This is really only an issue when bootstrapping init since
459 	 * the caller in all other cases will be a user process, and
460 	 * even if released (dd->uschedcp == NULL), that process will
461 	 * kickstart the scheduler when it returns to user mode from
462 	 * the kernel.
463 	 */
464 	if (dd->uschedcp == NULL) {
465 		atomic_set_cpumask(&bsd4_curprocmask, gd->gd_cpumask);
466 		dd->uschedcp = lp;
467 		dd->upri = lp->lwp_priority;
468 		lwkt_schedule(lp->lwp_thread);
469 		crit_exit();
470 		return;
471 	}
472 #endif
473 
474 #ifdef SMP
475 	/*
476 	 * XXX fixme.  Could be part of a remrunqueue/setrunqueue
477 	 * operation when the priority is recalculated, so TDF_MIGRATING
478 	 * may already be set.
479 	 */
480 	if ((lp->lwp_thread->td_flags & TDF_MIGRATING) == 0)
481 		lwkt_giveaway(lp->lwp_thread);
482 #endif
483 
484 	/*
485 	 * We lose control of lp the moment we release the spinlock after
486 	 * having placed lp on the queue.  i.e. another cpu could pick it
487 	 * up and it could exit, or its priority could be further adjusted,
488 	 * or something like that.
489 	 */
490 	spin_lock(&bsd4_spin);
491 	bsd4_setrunqueue_locked(lp);
492 
493 #ifdef SMP
494 	/*
495 	 * Kick the scheduler helper on one of the other cpu's
496 	 * and request a reschedule if appropriate.
497 	 *
498 	 * NOTE: We check all cpus whos rdyprocmask is set.  First we
499 	 *	 look for cpus without designated lps, then we look for
500 	 *	 cpus with designated lps with a worse priority than our
501 	 *	 process.
502 	 */
503 	++bsd4_scancpu;
504 	cpuid = (bsd4_scancpu & 0xFFFF) % ncpus;
505 	mask = ~bsd4_curprocmask & bsd4_rdyprocmask & lp->lwp_cpumask &
506 	       smp_active_mask & usched_global_cpumask;
507 
508 	while (mask) {
509 		tmpmask = ~(CPUMASK(cpuid) - 1);
510 		if (mask & tmpmask)
511 			cpuid = BSFCPUMASK(mask & tmpmask);
512 		else
513 			cpuid = BSFCPUMASK(mask);
514 		gd = globaldata_find(cpuid);
515 		dd = &bsd4_pcpu[cpuid];
516 
517 		if ((dd->upri & ~PPQMASK) >= (lp->lwp_priority & ~PPQMASK))
518 			goto found;
519 		mask &= ~CPUMASK(cpuid);
520 	}
521 
522 	/*
523 	 * Then cpus which might have a currently running lp
524 	 */
525 	mask = bsd4_curprocmask & bsd4_rdyprocmask &
526 	       lp->lwp_cpumask & smp_active_mask & usched_global_cpumask;
527 
528 	while (mask) {
529 		tmpmask = ~(CPUMASK(cpuid) - 1);
530 		if (mask & tmpmask)
531 			cpuid = BSFCPUMASK(mask & tmpmask);
532 		else
533 			cpuid = BSFCPUMASK(mask);
534 		gd = globaldata_find(cpuid);
535 		dd = &bsd4_pcpu[cpuid];
536 
537 		if ((dd->upri & ~PPQMASK) > (lp->lwp_priority & ~PPQMASK))
538 			goto found;
539 		mask &= ~CPUMASK(cpuid);
540 	}
541 
542 	/*
543 	 * If we cannot find a suitable cpu we reload from bsd4_scancpu
544 	 * and round-robin.  Other cpus will pickup as they release their
545 	 * current lwps or become ready.
546 	 *
547 	 * Avoid a degenerate system lockup case if usched_global_cpumask
548 	 * is set to 0 or otherwise does not cover lwp_cpumask.
549 	 *
550 	 * We only kick the target helper thread in this case, we do not
551 	 * set the user resched flag because
552 	 */
553 	cpuid = (bsd4_scancpu & 0xFFFF) % ncpus;
554 	if ((CPUMASK(cpuid) & usched_global_cpumask) == 0) {
555 		cpuid = 0;
556 	}
557 	gd = globaldata_find(cpuid);
558 	dd = &bsd4_pcpu[cpuid];
559 found:
560 	if (gd == mycpu) {
561 		spin_unlock(&bsd4_spin);
562 		if ((dd->upri & ~PPQMASK) > (lp->lwp_priority & ~PPQMASK)) {
563 			if (dd->uschedcp == NULL) {
564 				lwkt_schedule(&dd->helper_thread);
565 			} else {
566 				need_user_resched();
567 			}
568 		}
569 	} else {
570 		atomic_clear_cpumask(&bsd4_rdyprocmask, CPUMASK(cpuid));
571 		spin_unlock(&bsd4_spin);
572 		if ((dd->upri & ~PPQMASK) > (lp->lwp_priority & ~PPQMASK))
573 			lwkt_send_ipiq(gd, need_user_resched_remote, NULL);
574 		else
575 			lwkt_schedule(&dd->helper_thread);
576 	}
577 #else
578 	/*
579 	 * Request a reschedule if appropriate.
580 	 */
581 	spin_unlock(&bsd4_spin);
582 	if ((dd->upri & ~PPQMASK) > (lp->lwp_priority & ~PPQMASK)) {
583 		need_user_resched();
584 	}
585 #endif
586 	crit_exit();
587 }
588 
589 /*
590  * This routine is called from a systimer IPI.  It MUST be MP-safe and
591  * the BGL IS NOT HELD ON ENTRY.  This routine is called at ESTCPUFREQ on
592  * each cpu.
593  *
594  * MPSAFE
595  */
596 static
597 void
598 bsd4_schedulerclock(struct lwp *lp, sysclock_t period, sysclock_t cpstamp)
599 {
600 	globaldata_t gd = mycpu;
601 	bsd4_pcpu_t dd = &bsd4_pcpu[gd->gd_cpuid];
602 
603 	/*
604 	 * Do we need to round-robin?  We round-robin 10 times a second.
605 	 * This should only occur for cpu-bound batch processes.
606 	 */
607 	if (++dd->rrcount >= usched_bsd4_rrinterval) {
608 		dd->rrcount = 0;
609 		need_user_resched();
610 	}
611 
612 	/*
613 	 * As the process accumulates cpu time p_estcpu is bumped and may
614 	 * push the process into another scheduling queue.  It typically
615 	 * takes 4 ticks to bump the queue.
616 	 */
617 	lp->lwp_estcpu = ESTCPULIM(lp->lwp_estcpu + ESTCPUINCR);
618 
619 	/*
620 	 * Reducing p_origcpu over time causes more of our estcpu to be
621 	 * returned to the parent when we exit.  This is a small tweak
622 	 * for the batch detection heuristic.
623 	 */
624 	if (lp->lwp_origcpu)
625 		--lp->lwp_origcpu;
626 
627 	/*
628 	 * Spinlocks also hold a critical section so there should not be
629 	 * any active.
630 	 */
631 	KKASSERT(gd->gd_spinlocks_wr == 0);
632 
633 	bsd4_resetpriority(lp);
634 #if 0
635 	/*
636 	* if we can't call bsd4_resetpriority for some reason we must call
637 	 * need user_resched().
638 	 */
639 	need_user_resched();
640 #endif
641 }
642 
643 /*
644  * Called from acquire and from kern_synch's one-second timer (one of the
645  * callout helper threads) with a critical section held.
646  *
647  * Decay p_estcpu based on the number of ticks we haven't been running
648  * and our p_nice.  As the load increases each process observes a larger
649  * number of idle ticks (because other processes are running in them).
650  * This observation leads to a larger correction which tends to make the
651  * system more 'batchy'.
652  *
653  * Note that no recalculation occurs for a process which sleeps and wakes
654  * up in the same tick.  That is, a system doing thousands of context
655  * switches per second will still only do serious estcpu calculations
656  * ESTCPUFREQ times per second.
657  *
658  * MPSAFE
659  */
660 static
661 void
662 bsd4_recalculate_estcpu(struct lwp *lp)
663 {
664 	globaldata_t gd = mycpu;
665 	sysclock_t cpbase;
666 	int loadfac;
667 	int ndecay;
668 	int nticks;
669 	int nleft;
670 
671 	/*
672 	 * We have to subtract periodic to get the last schedclock
673 	 * timeout time, otherwise we would get the upcoming timeout.
674 	 * Keep in mind that a process can migrate between cpus and
675 	 * while the scheduler clock should be very close, boundary
676 	 * conditions could lead to a small negative delta.
677 	 */
678 	cpbase = gd->gd_schedclock.time - gd->gd_schedclock.periodic;
679 
680 	if (lp->lwp_slptime > 1) {
681 		/*
682 		 * Too much time has passed, do a coarse correction.
683 		 */
684 		lp->lwp_estcpu = lp->lwp_estcpu >> 1;
685 		bsd4_resetpriority(lp);
686 		lp->lwp_cpbase = cpbase;
687 		lp->lwp_cpticks = 0;
688 	} else if (lp->lwp_cpbase != cpbase) {
689 		/*
690 		 * Adjust estcpu if we are in a different tick.  Don't waste
691 		 * time if we are in the same tick.
692 		 *
693 		 * First calculate the number of ticks in the measurement
694 		 * interval.  The nticks calculation can wind up 0 due to
695 		 * a bug in the handling of lwp_slptime  (as yet not found),
696 		 * so make sure we do not get a divide by 0 panic.
697 		 */
698 		nticks = (cpbase - lp->lwp_cpbase) / gd->gd_schedclock.periodic;
699 		if (nticks <= 0)
700 			nticks = 1;
701 		updatepcpu(lp, lp->lwp_cpticks, nticks);
702 
703 		if ((nleft = nticks - lp->lwp_cpticks) < 0)
704 			nleft = 0;
705 		if (usched_debug == lp->lwp_proc->p_pid) {
706 			kprintf("pid %d tid %d estcpu %d cpticks %d "
707 				"nticks %d nleft %d",
708 				lp->lwp_proc->p_pid, lp->lwp_tid,
709 				lp->lwp_estcpu, lp->lwp_cpticks,
710 				nticks, nleft);
711 		}
712 
713 		/*
714 		 * Calculate a decay value based on ticks remaining scaled
715 		 * down by the instantanious load and p_nice.
716 		 */
717 		if ((loadfac = bsd4_runqcount) < 2)
718 			loadfac = 2;
719 		ndecay = nleft * usched_bsd4_decay * 2 *
720 			(PRIO_MAX * 2 - lp->lwp_proc->p_nice) /
721 			(loadfac * PRIO_MAX * 2);
722 
723 		/*
724 		 * Adjust p_estcpu.  Handle a border case where batch jobs
725 		 * can get stalled long enough to decay to zero when they
726 		 * shouldn't.
727 		 *
728 		 * Only adjust estcpu downward if the lwp is not in a
729 		 * runnable state.  Note that normal tsleeps or timer ticks
730 		 * will adjust estcpu up or down.   The decay we do here
731 		 * is not really needed and may be removed in the future.
732 		 */
733 		if (lp->lwp_stat != LSRUN) {
734 			if (lp->lwp_estcpu > ndecay * 2)
735 				lp->lwp_estcpu -= ndecay;
736 			else
737 				lp->lwp_estcpu >>= 1;
738 		}
739 
740 		if (usched_debug == lp->lwp_proc->p_pid) {
741 			kprintf(" ndecay %d estcpu %d\n",
742 				ndecay, lp->lwp_estcpu);
743 		}
744 		bsd4_resetpriority(lp);
745 		lp->lwp_cpbase = cpbase;
746 		lp->lwp_cpticks = 0;
747 	}
748 }
749 
750 /*
751  * Compute the priority of a process when running in user mode.
752  * Arrange to reschedule if the resulting priority is better
753  * than that of the current process.
754  *
755  * This routine may be called with any process.
756  *
757  * This routine is called by fork1() for initial setup with the process
758  * of the run queue, and also may be called normally with the process on or
759  * off the run queue.
760  *
761  * MPSAFE
762  */
763 static void
764 bsd4_resetpriority(struct lwp *lp)
765 {
766 	bsd4_pcpu_t dd;
767 	int newpriority;
768 	u_short newrqtype;
769 	int reschedcpu;
770 
771 	/*
772 	 * Calculate the new priority and queue type
773 	 */
774 	crit_enter();
775 	spin_lock(&bsd4_spin);
776 
777 	newrqtype = lp->lwp_rtprio.type;
778 
779 	switch(newrqtype) {
780 	case RTP_PRIO_REALTIME:
781 	case RTP_PRIO_FIFO:
782 		newpriority = PRIBASE_REALTIME +
783 			     (lp->lwp_rtprio.prio & PRIMASK);
784 		break;
785 	case RTP_PRIO_NORMAL:
786 		newpriority = (lp->lwp_proc->p_nice - PRIO_MIN) * PPQ / NICEPPQ;
787 		newpriority += lp->lwp_estcpu * PPQ / ESTCPUPPQ;
788 		newpriority = newpriority * MAXPRI / (PRIO_RANGE * PPQ /
789 			      NICEPPQ + ESTCPUMAX * PPQ / ESTCPUPPQ);
790 		newpriority = PRIBASE_NORMAL + (newpriority & PRIMASK);
791 		break;
792 	case RTP_PRIO_IDLE:
793 		newpriority = PRIBASE_IDLE + (lp->lwp_rtprio.prio & PRIMASK);
794 		break;
795 	case RTP_PRIO_THREAD:
796 		newpriority = PRIBASE_THREAD + (lp->lwp_rtprio.prio & PRIMASK);
797 		break;
798 	default:
799 		panic("Bad RTP_PRIO %d", newrqtype);
800 		/* NOT REACHED */
801 	}
802 
803 	/*
804 	 * The newpriority incorporates the queue type so do a simple masked
805 	 * check to determine if the process has moved to another queue.  If
806 	 * it has, and it is currently on a run queue, then move it.
807 	 */
808 	if ((lp->lwp_priority ^ newpriority) & ~PPQMASK) {
809 		lp->lwp_priority = newpriority;
810 		if (lp->lwp_flag & LWP_ONRUNQ) {
811 			bsd4_remrunqueue_locked(lp);
812 			lp->lwp_rqtype = newrqtype;
813 			lp->lwp_rqindex = (newpriority & PRIMASK) / PPQ;
814 			bsd4_setrunqueue_locked(lp);
815 			reschedcpu = lp->lwp_thread->td_gd->gd_cpuid;
816 		} else {
817 			lp->lwp_rqtype = newrqtype;
818 			lp->lwp_rqindex = (newpriority & PRIMASK) / PPQ;
819 			reschedcpu = -1;
820 		}
821 	} else {
822 		lp->lwp_priority = newpriority;
823 		reschedcpu = -1;
824 	}
825 
826 	/*
827 	 * Determine if we need to reschedule the target cpu.  This only
828 	 * occurs if the LWP is already on a scheduler queue, which means
829 	 * that idle cpu notification has already occured.  At most we
830 	 * need only issue a need_user_resched() on the appropriate cpu.
831 	 *
832 	 * The LWP may be owned by a CPU different from the current one,
833 	 * in which case dd->uschedcp may be modified without an MP lock
834 	 * or a spinlock held.  The worst that happens is that the code
835 	 * below causes a spurious need_user_resched() on the target CPU
836 	 * and dd->pri to be wrong for a short period of time, both of
837 	 * which are harmless.
838 	 */
839 	if (reschedcpu >= 0) {
840 		dd = &bsd4_pcpu[reschedcpu];
841 		if ((bsd4_rdyprocmask & CPUMASK(reschedcpu)) &&
842 		    (dd->upri & ~PRIMASK) > (lp->lwp_priority & ~PRIMASK)) {
843 #ifdef SMP
844 			if (reschedcpu == mycpu->gd_cpuid) {
845 				spin_unlock(&bsd4_spin);
846 				need_user_resched();
847 			} else {
848 				spin_unlock(&bsd4_spin);
849 				atomic_clear_cpumask(&bsd4_rdyprocmask,
850 						     CPUMASK(reschedcpu));
851 				lwkt_send_ipiq(lp->lwp_thread->td_gd,
852 					       need_user_resched_remote, NULL);
853 			}
854 #else
855 			spin_unlock(&bsd4_spin);
856 			need_user_resched();
857 #endif
858 		} else {
859 			spin_unlock(&bsd4_spin);
860 		}
861 	} else {
862 		spin_unlock(&bsd4_spin);
863 	}
864 	crit_exit();
865 }
866 
867 /*
868  * MPSAFE
869  */
870 static
871 void
872 bsd4_yield(struct lwp *lp)
873 {
874 #if 0
875 	/* FUTURE (or something similar) */
876 	switch(lp->lwp_rqtype) {
877 	case RTP_PRIO_NORMAL:
878 		lp->lwp_estcpu = ESTCPULIM(lp->lwp_estcpu + ESTCPUINCR);
879 		break;
880 	default:
881 		break;
882 	}
883 #endif
884         need_user_resched();
885 }
886 
887 /*
888  * Called from fork1() when a new child process is being created.
889  *
890  * Give the child process an initial estcpu that is more batch then
891  * its parent and dock the parent for the fork (but do not
892  * reschedule the parent).   This comprises the main part of our batch
893  * detection heuristic for both parallel forking and sequential execs.
894  *
895  * Interactive processes will decay the boosted estcpu quickly while batch
896  * processes will tend to compound it.
897  *
898  * NOTE: We don't want to dock the parent too much because it may cause
899  *	 the parent to 'go batch' too quickly in cases where the children
900  *	 are short-lived.
901  *
902  * XXX lwp should be "spawning" instead of "forking"
903  *
904  * MPSAFE
905  */
906 static void
907 bsd4_forking(struct lwp *plp, struct lwp *lp)
908 {
909 	lp->lwp_estcpu = ESTCPULIM(plp->lwp_estcpu + ESTCPUPPQ);
910 	lp->lwp_origcpu = lp->lwp_estcpu;
911 	plp->lwp_estcpu = ESTCPULIM(plp->lwp_estcpu + 1);
912 }
913 
914 /*
915  * Called when the parent reaps a child.   Propogate cpu use by the child
916  * back to the parent.
917  *
918  * MPSAFE
919  */
920 static void
921 bsd4_exiting(struct lwp *plp, struct lwp *lp)
922 {
923 	int delta;
924 
925 	if (plp->lwp_proc->p_pid != 1) {
926 		delta = lp->lwp_estcpu - lp->lwp_origcpu;
927 		if (delta > 0)
928 			plp->lwp_estcpu = ESTCPULIM(plp->lwp_estcpu + delta);
929 	}
930 }
931 
932 
933 /*
934  * chooseproc() is called when a cpu needs a user process to LWKT schedule,
935  * it selects a user process and returns it.  If chklp is non-NULL and chklp
936  * has a better or equal priority then the process that would otherwise be
937  * chosen, NULL is returned.
938  *
939  * Until we fix the RUNQ code the chklp test has to be strict or we may
940  * bounce between processes trying to acquire the current process designation.
941  *
942  * MPSAFE - must be called with bsd4_spin exclusive held.  The spinlock is
943  *	    left intact through the entire routine.
944  */
945 static
946 struct lwp *
947 chooseproc_locked(struct lwp *chklp)
948 {
949 	struct lwp *lp;
950 	struct rq *q;
951 	u_int32_t *which, *which2;
952 	u_int32_t pri;
953 	u_int32_t rtqbits;
954 	u_int32_t tsqbits;
955 	u_int32_t idqbits;
956 	cpumask_t cpumask;
957 
958 	rtqbits = bsd4_rtqueuebits;
959 	tsqbits = bsd4_queuebits;
960 	idqbits = bsd4_idqueuebits;
961 	cpumask = mycpu->gd_cpumask;
962 
963 #ifdef SMP
964 again:
965 #endif
966 	if (rtqbits) {
967 		pri = bsfl(rtqbits);
968 		q = &bsd4_rtqueues[pri];
969 		which = &bsd4_rtqueuebits;
970 		which2 = &rtqbits;
971 	} else if (tsqbits) {
972 		pri = bsfl(tsqbits);
973 		q = &bsd4_queues[pri];
974 		which = &bsd4_queuebits;
975 		which2 = &tsqbits;
976 	} else if (idqbits) {
977 		pri = bsfl(idqbits);
978 		q = &bsd4_idqueues[pri];
979 		which = &bsd4_idqueuebits;
980 		which2 = &idqbits;
981 	} else {
982 		return NULL;
983 	}
984 	lp = TAILQ_FIRST(q);
985 	KASSERT(lp, ("chooseproc: no lwp on busy queue"));
986 
987 #ifdef SMP
988 	while ((lp->lwp_cpumask & cpumask) == 0) {
989 		lp = TAILQ_NEXT(lp, lwp_procq);
990 		if (lp == NULL) {
991 			*which2 &= ~(1 << pri);
992 			goto again;
993 		}
994 	}
995 #endif
996 
997 	/*
998 	 * If the passed lwp <chklp> is reasonably close to the selected
999 	 * lwp <lp>, return NULL (indicating that <chklp> should be kept).
1000 	 *
1001 	 * Note that we must error on the side of <chklp> to avoid bouncing
1002 	 * between threads in the acquire code.
1003 	 */
1004 	if (chklp) {
1005 		if (chklp->lwp_priority < lp->lwp_priority + PPQ)
1006 			return(NULL);
1007 	}
1008 
1009 #ifdef SMP
1010 	/*
1011 	 * If the chosen lwp does not reside on this cpu spend a few
1012 	 * cycles looking for a better candidate at the same priority level.
1013 	 * This is a fallback check, setrunqueue() tries to wakeup the
1014 	 * correct cpu and is our front-line affinity.
1015 	 */
1016 	if (lp->lwp_thread->td_gd != mycpu &&
1017 	    (chklp = TAILQ_NEXT(lp, lwp_procq)) != NULL
1018 	) {
1019 		if (chklp->lwp_thread->td_gd == mycpu) {
1020 			++choose_affinity;
1021 			lp = chklp;
1022 		}
1023 	}
1024 #endif
1025 
1026 	TAILQ_REMOVE(q, lp, lwp_procq);
1027 	--bsd4_runqcount;
1028 	if (TAILQ_EMPTY(q))
1029 		*which &= ~(1 << pri);
1030 	KASSERT((lp->lwp_flag & LWP_ONRUNQ) != 0, ("not on runq6!"));
1031 	lp->lwp_flag &= ~LWP_ONRUNQ;
1032 	return lp;
1033 }
1034 
1035 #ifdef SMP
1036 
1037 static
1038 void
1039 need_user_resched_remote(void *dummy)
1040 {
1041 	globaldata_t gd = mycpu;
1042 	bsd4_pcpu_t  dd = &bsd4_pcpu[gd->gd_cpuid];
1043 
1044 	need_user_resched();
1045 	lwkt_schedule(&dd->helper_thread);
1046 }
1047 
1048 #endif
1049 
1050 /*
1051  * bsd4_remrunqueue_locked() removes a given process from the run queue
1052  * that it is on, clearing the queue busy bit if it becomes empty.
1053  *
1054  * Note that user process scheduler is different from the LWKT schedule.
1055  * The user process scheduler only manages user processes but it uses LWKT
1056  * underneath, and a user process operating in the kernel will often be
1057  * 'released' from our management.
1058  *
1059  * MPSAFE - bsd4_spin must be held exclusively on call
1060  */
1061 static void
1062 bsd4_remrunqueue_locked(struct lwp *lp)
1063 {
1064 	struct rq *q;
1065 	u_int32_t *which;
1066 	u_int8_t pri;
1067 
1068 	KKASSERT(lp->lwp_flag & LWP_ONRUNQ);
1069 	lp->lwp_flag &= ~LWP_ONRUNQ;
1070 	--bsd4_runqcount;
1071 	KKASSERT(bsd4_runqcount >= 0);
1072 
1073 	pri = lp->lwp_rqindex;
1074 	switch(lp->lwp_rqtype) {
1075 	case RTP_PRIO_NORMAL:
1076 		q = &bsd4_queues[pri];
1077 		which = &bsd4_queuebits;
1078 		break;
1079 	case RTP_PRIO_REALTIME:
1080 	case RTP_PRIO_FIFO:
1081 		q = &bsd4_rtqueues[pri];
1082 		which = &bsd4_rtqueuebits;
1083 		break;
1084 	case RTP_PRIO_IDLE:
1085 		q = &bsd4_idqueues[pri];
1086 		which = &bsd4_idqueuebits;
1087 		break;
1088 	default:
1089 		panic("remrunqueue: invalid rtprio type");
1090 		/* NOT REACHED */
1091 	}
1092 	TAILQ_REMOVE(q, lp, lwp_procq);
1093 	if (TAILQ_EMPTY(q)) {
1094 		KASSERT((*which & (1 << pri)) != 0,
1095 			("remrunqueue: remove from empty queue"));
1096 		*which &= ~(1 << pri);
1097 	}
1098 }
1099 
1100 /*
1101  * bsd4_setrunqueue_locked()
1102  *
1103  * Add a process whos rqtype and rqindex had previously been calculated
1104  * onto the appropriate run queue.   Determine if the addition requires
1105  * a reschedule on a cpu and return the cpuid or -1.
1106  *
1107  * NOTE: Lower priorities are better priorities.
1108  *
1109  * MPSAFE - bsd4_spin must be held exclusively on call
1110  */
1111 static void
1112 bsd4_setrunqueue_locked(struct lwp *lp)
1113 {
1114 	struct rq *q;
1115 	u_int32_t *which;
1116 	int pri;
1117 
1118 	KKASSERT((lp->lwp_flag & LWP_ONRUNQ) == 0);
1119 	lp->lwp_flag |= LWP_ONRUNQ;
1120 	++bsd4_runqcount;
1121 
1122 	pri = lp->lwp_rqindex;
1123 
1124 	switch(lp->lwp_rqtype) {
1125 	case RTP_PRIO_NORMAL:
1126 		q = &bsd4_queues[pri];
1127 		which = &bsd4_queuebits;
1128 		break;
1129 	case RTP_PRIO_REALTIME:
1130 	case RTP_PRIO_FIFO:
1131 		q = &bsd4_rtqueues[pri];
1132 		which = &bsd4_rtqueuebits;
1133 		break;
1134 	case RTP_PRIO_IDLE:
1135 		q = &bsd4_idqueues[pri];
1136 		which = &bsd4_idqueuebits;
1137 		break;
1138 	default:
1139 		panic("remrunqueue: invalid rtprio type");
1140 		/* NOT REACHED */
1141 	}
1142 
1143 	/*
1144 	 * Add to the correct queue and set the appropriate bit.  If no
1145 	 * lower priority (i.e. better) processes are in the queue then
1146 	 * we want a reschedule, calculate the best cpu for the job.
1147 	 *
1148 	 * Always run reschedules on the LWPs original cpu.
1149 	 */
1150 	TAILQ_INSERT_TAIL(q, lp, lwp_procq);
1151 	*which |= 1 << pri;
1152 }
1153 
1154 #ifdef SMP
1155 
1156 /*
1157  * For SMP systems a user scheduler helper thread is created for each
1158  * cpu and is used to allow one cpu to wakeup another for the purposes of
1159  * scheduling userland threads from setrunqueue().
1160  *
1161  * UP systems do not need the helper since there is only one cpu.
1162  *
1163  * We can't use the idle thread for this because we might block.
1164  * Additionally, doing things this way allows us to HLT idle cpus
1165  * on MP systems.
1166  *
1167  * MPSAFE
1168  */
1169 static void
1170 sched_thread(void *dummy)
1171 {
1172     globaldata_t gd;
1173     bsd4_pcpu_t  dd;
1174     struct lwp *nlp;
1175     cpumask_t mask;
1176     int cpuid;
1177 #ifdef SMP
1178     cpumask_t tmpmask;
1179     int tmpid;
1180 #endif
1181 
1182     gd = mycpu;
1183     cpuid = gd->gd_cpuid;	/* doesn't change */
1184     mask = gd->gd_cpumask;	/* doesn't change */
1185     dd = &bsd4_pcpu[cpuid];
1186 
1187     /*
1188      * Since we are woken up only when no user processes are scheduled
1189      * on a cpu, we can run at an ultra low priority.
1190      */
1191     lwkt_setpri_self(TDPRI_USER_SCHEDULER);
1192 
1193     for (;;) {
1194 	/*
1195 	 * We use the LWKT deschedule-interlock trick to avoid racing
1196 	 * bsd4_rdyprocmask.  This means we cannot block through to the
1197 	 * manual lwkt_switch() call we make below.
1198 	 */
1199 	crit_enter_gd(gd);
1200 	lwkt_deschedule_self(gd->gd_curthread);
1201 	spin_lock(&bsd4_spin);
1202 	atomic_set_cpumask(&bsd4_rdyprocmask, mask);
1203 
1204 	clear_user_resched();	/* This satisfied the reschedule request */
1205 	dd->rrcount = 0;	/* Reset the round-robin counter */
1206 
1207 	if ((bsd4_curprocmask & mask) == 0) {
1208 		/*
1209 		 * No thread is currently scheduled.
1210 		 */
1211 		KKASSERT(dd->uschedcp == NULL);
1212 		if ((nlp = chooseproc_locked(NULL)) != NULL) {
1213 			atomic_set_cpumask(&bsd4_curprocmask, mask);
1214 			dd->upri = nlp->lwp_priority;
1215 			dd->uschedcp = nlp;
1216 			spin_unlock(&bsd4_spin);
1217 			lwkt_acquire(nlp->lwp_thread);
1218 			lwkt_schedule(nlp->lwp_thread);
1219 		} else {
1220 			spin_unlock(&bsd4_spin);
1221 		}
1222 	} else if (bsd4_runqcount) {
1223 		if ((nlp = chooseproc_locked(dd->uschedcp)) != NULL) {
1224 			dd->upri = nlp->lwp_priority;
1225 			dd->uschedcp = nlp;
1226 			spin_unlock(&bsd4_spin);
1227 			lwkt_acquire(nlp->lwp_thread);
1228 			lwkt_schedule(nlp->lwp_thread);
1229 		} else {
1230 			/*
1231 			 * CHAINING CONDITION TRAIN
1232 			 *
1233 			 * We could not deal with the scheduler wakeup
1234 			 * request on this cpu, locate a ready scheduler
1235 			 * with no current lp assignment and chain to it.
1236 			 *
1237 			 * This ensures that a wakeup race which fails due
1238 			 * to priority test does not leave other unscheduled
1239 			 * cpus idle when the runqueue is not empty.
1240 			 */
1241 			tmpmask = ~bsd4_curprocmask & bsd4_rdyprocmask &
1242 				  smp_active_mask;
1243 			if (tmpmask) {
1244 				tmpid = BSFCPUMASK(tmpmask);
1245 				gd = globaldata_find(cpuid);
1246 				dd = &bsd4_pcpu[cpuid];
1247 				atomic_clear_cpumask(&bsd4_rdyprocmask,
1248 						     CPUMASK(tmpid));
1249 				spin_unlock(&bsd4_spin);
1250 				lwkt_schedule(&dd->helper_thread);
1251 			} else {
1252 				spin_unlock(&bsd4_spin);
1253 			}
1254 		}
1255 	} else {
1256 		/*
1257 		 * The runq is empty.
1258 		 */
1259 		spin_unlock(&bsd4_spin);
1260 	}
1261 	crit_exit_gd(gd);
1262 	lwkt_switch();
1263     }
1264 }
1265 
1266 /*
1267  * Setup our scheduler helpers.  Note that curprocmask bit 0 has already
1268  * been cleared by rqinit() and we should not mess with it further.
1269  */
1270 static void
1271 sched_thread_cpu_init(void)
1272 {
1273     int i;
1274 
1275     if (bootverbose)
1276 	kprintf("start scheduler helpers on cpus:");
1277 
1278     for (i = 0; i < ncpus; ++i) {
1279 	bsd4_pcpu_t dd = &bsd4_pcpu[i];
1280 	cpumask_t mask = CPUMASK(i);
1281 
1282 	if ((mask & smp_active_mask) == 0)
1283 	    continue;
1284 
1285 	if (bootverbose)
1286 	    kprintf(" %d", i);
1287 
1288 	lwkt_create(sched_thread, NULL, NULL, &dd->helper_thread,
1289 		    TDF_STOPREQ, i, "usched %d", i);
1290 
1291 	/*
1292 	 * Allow user scheduling on the target cpu.  cpu #0 has already
1293 	 * been enabled in rqinit().
1294 	 */
1295 	if (i)
1296 	    atomic_clear_cpumask(&bsd4_curprocmask, mask);
1297 	atomic_set_cpumask(&bsd4_rdyprocmask, mask);
1298 	dd->upri = PRIBASE_NULL;
1299     }
1300     if (bootverbose)
1301 	kprintf("\n");
1302 }
1303 SYSINIT(uschedtd, SI_BOOT2_USCHED, SI_ORDER_SECOND,
1304 	sched_thread_cpu_init, NULL)
1305 
1306 #endif
1307 
1308