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