1d29f59680973ca5dce712df00cb60bdf5b1a7c1
[dragonfly.git] / sys / kern / usched_bsd4.c
1 /*
2  * Copyright (c) 2012 The DragonFly Project.  All rights reserved.
3  * Copyright (c) 1999 Peter Wemm <peter@FreeBSD.org>.  All rights reserved.
4  *
5  * This code is derived from software contributed to The DragonFly Project
6  * by Matthew Dillon <dillon@backplane.com>,
7  * by Mihai Carabas <mihai.carabas@gmail.com>
8  * and many others.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31
32 #include <sys/param.h>
33 #include <sys/systm.h>
34 #include <sys/kernel.h>
35 #include <sys/lock.h>
36 #include <sys/queue.h>
37 #include <sys/proc.h>
38 #include <sys/rtprio.h>
39 #include <sys/uio.h>
40 #include <sys/sysctl.h>
41 #include <sys/resourcevar.h>
42 #include <sys/spinlock.h>
43 #include <sys/cpu_topology.h>
44 #include <sys/thread2.h>
45 #include <sys/spinlock2.h>
46 #include <sys/mplock2.h>
47
48 #include <sys/ktr.h>
49
50 #include <machine/cpu.h>
51 #include <machine/smp.h>
52
53 /*
54  * Priorities.  Note that with 32 run queues per scheduler each queue
55  * represents four priority levels.
56  */
57
58 #define MAXPRI                  128
59 #define PRIMASK                 (MAXPRI - 1)
60 #define PRIBASE_REALTIME        0
61 #define PRIBASE_NORMAL          MAXPRI
62 #define PRIBASE_IDLE            (MAXPRI * 2)
63 #define PRIBASE_THREAD          (MAXPRI * 3)
64 #define PRIBASE_NULL            (MAXPRI * 4)
65
66 #define NQS     32                      /* 32 run queues. */
67 #define PPQ     (MAXPRI / NQS)          /* priorities per queue */
68 #define PPQMASK (PPQ - 1)
69
70 /*
71  * NICEPPQ      - number of nice units per priority queue
72  *
73  * ESTCPUPPQ    - number of estcpu units per priority queue
74  * ESTCPUMAX    - number of estcpu units
75  */
76 #define NICEPPQ         2
77 #define ESTCPUPPQ       512
78 #define ESTCPUMAX       (ESTCPUPPQ * NQS)
79 #define BATCHMAX        (ESTCPUFREQ * 30)
80 #define PRIO_RANGE      (PRIO_MAX - PRIO_MIN + 1)
81
82 #define ESTCPULIM(v)    min((v), ESTCPUMAX)
83
84 TAILQ_HEAD(rq, lwp);
85
86 #define lwp_priority    lwp_usdata.bsd4.priority
87 #define lwp_rqindex     lwp_usdata.bsd4.rqindex
88 #define lwp_estcpu      lwp_usdata.bsd4.estcpu
89 #define lwp_batch       lwp_usdata.bsd4.batch
90 #define lwp_rqtype      lwp_usdata.bsd4.rqtype
91
92 static void bsd4_acquire_curproc(struct lwp *lp);
93 static void bsd4_release_curproc(struct lwp *lp);
94 static void bsd4_select_curproc(globaldata_t gd);
95 static void bsd4_setrunqueue(struct lwp *lp);
96 static void bsd4_schedulerclock(struct lwp *lp, sysclock_t period,
97                                 sysclock_t cpstamp);
98 static void bsd4_recalculate_estcpu(struct lwp *lp);
99 static void bsd4_resetpriority(struct lwp *lp);
100 static void bsd4_forking(struct lwp *plp, struct lwp *lp);
101 static void bsd4_exiting(struct lwp *lp, struct proc *);
102 static void bsd4_uload_update(struct lwp *lp);
103 static void bsd4_yield(struct lwp *lp);
104
105 #ifdef SMP
106 static void bsd4_need_user_resched_remote(void *dummy);
107 static int bsd4_batchy_looser_pri_test(struct lwp* lp);
108 static struct lwp *bsd4_chooseproc_locked_cache_coherent(struct lwp *chklp);
109 static void bsd4_kick_helper(struct lwp *lp);
110 #endif
111 static struct lwp *bsd4_chooseproc_locked(struct lwp *chklp);
112 static void bsd4_remrunqueue_locked(struct lwp *lp);
113 static void bsd4_setrunqueue_locked(struct lwp *lp);
114
115 struct usched usched_bsd4 = {
116         { NULL },
117         "bsd4", "Original DragonFly Scheduler",
118         NULL,                   /* default registration */
119         NULL,                   /* default deregistration */
120         bsd4_acquire_curproc,
121         bsd4_release_curproc,
122         bsd4_setrunqueue,
123         bsd4_schedulerclock,
124         bsd4_recalculate_estcpu,
125         bsd4_resetpriority,
126         bsd4_forking,
127         bsd4_exiting,
128         bsd4_uload_update,
129         NULL,                   /* setcpumask not supported */
130         bsd4_yield
131 };
132
133 struct usched_bsd4_pcpu {
134         struct thread   helper_thread;
135         short           rrcount;
136         short           upri;
137         struct lwp      *uschedcp;
138         struct lwp      *old_uschedcp;
139 #ifdef SMP
140         cpu_node_t      *cpunode;
141 #endif
142 };
143
144 typedef struct usched_bsd4_pcpu *bsd4_pcpu_t;
145
146 /*
147  * We have NQS (32) run queues per scheduling class.  For the normal
148  * class, there are 128 priorities scaled onto these 32 queues.  New
149  * processes are added to the last entry in each queue, and processes
150  * are selected for running by taking them from the head and maintaining
151  * a simple FIFO arrangement.  Realtime and Idle priority processes have
152  * and explicit 0-31 priority which maps directly onto their class queue
153  * index.  When a queue has something in it, the corresponding bit is
154  * set in the queuebits variable, allowing a single read to determine
155  * the state of all 32 queues and then a ffs() to find the first busy
156  * queue.
157  */
158 static struct rq bsd4_queues[NQS];
159 static struct rq bsd4_rtqueues[NQS];
160 static struct rq bsd4_idqueues[NQS];
161 static u_int32_t bsd4_queuebits;
162 static u_int32_t bsd4_rtqueuebits;
163 static u_int32_t bsd4_idqueuebits;
164 static cpumask_t bsd4_curprocmask = -1; /* currently running a user process */
165 static cpumask_t bsd4_rdyprocmask;      /* ready to accept a user process */
166 static int       bsd4_runqcount;
167 #ifdef SMP
168 static volatile int bsd4_scancpu;
169 #endif
170 static struct spinlock bsd4_spin;
171 static struct usched_bsd4_pcpu bsd4_pcpu[MAXCPU];
172 static struct sysctl_ctx_list usched_bsd4_sysctl_ctx;
173 static struct sysctl_oid *usched_bsd4_sysctl_tree;
174
175 /* Debug info exposed through debug.* sysctl */
176
177 SYSCTL_INT(_debug, OID_AUTO, bsd4_runqcount, CTLFLAG_RD,
178            &bsd4_runqcount, 0,
179            "Number of run queues");
180
181 static int usched_bsd4_debug = -1;
182 SYSCTL_INT(_debug, OID_AUTO, bsd4_scdebug, CTLFLAG_RW,
183            &usched_bsd4_debug, 0,
184            "Print debug information for this pid");
185
186 static int usched_bsd4_pid_debug = -1;
187 SYSCTL_INT(_debug, OID_AUTO, bsd4_pid_debug, CTLFLAG_RW,
188            &usched_bsd4_pid_debug, 0,
189            "Print KTR debug information for this pid");
190
191 /* Tunning usched_bsd4 - configurable through kern.usched_bsd4.* */
192 #ifdef SMP
193 static int usched_bsd4_smt = 0;
194 static int usched_bsd4_cache_coherent = 0;
195 static int usched_bsd4_upri_affinity = 16; /* 32 queues - half-way */
196 static int usched_bsd4_queue_checks = 5;
197 static int usched_bsd4_stick_to_level = 0;
198 static long usched_bsd4_kicks;
199 #endif
200 static int usched_bsd4_rrinterval = (ESTCPUFREQ + 9) / 10;
201 static int usched_bsd4_decay = 8;
202 static int usched_bsd4_batch_time = 10;
203
204 /* KTR debug printings */
205
206 KTR_INFO_MASTER(usched);
207
208 #if !defined(KTR_USCHED_BSD4)
209 #define KTR_USCHED_BSD4 KTR_ALL
210 #endif
211
212 KTR_INFO(KTR_USCHED_BSD4, usched, bsd4_acquire_curproc_urw, 0,
213     "USCHED_BSD4(bsd4_acquire_curproc in user_reseched_wanted "
214     "after release: pid %d, cpuid %d, curr_cpuid %d)",
215     pid_t pid, int cpuid, int curr);
216 KTR_INFO(KTR_USCHED_BSD4, usched, bsd4_acquire_curproc_before_loop, 0,
217     "USCHED_BSD4(bsd4_acquire_curproc before loop: pid %d, cpuid %d, "
218     "curr_cpuid %d)",
219     pid_t pid, int cpuid, int curr);
220 KTR_INFO(KTR_USCHED_BSD4, usched, bsd4_acquire_curproc_not, 0,
221     "USCHED_BSD4(bsd4_acquire_curproc couldn't acquire after "
222     "bsd4_setrunqueue: pid %d, cpuid %d, curr_lp pid %d, curr_cpuid %d)",
223     pid_t pid, int cpuid, pid_t curr_pid, int curr_cpuid);
224 KTR_INFO(KTR_USCHED_BSD4, usched, bsd4_acquire_curproc_switch, 0,
225     "USCHED_BSD4(bsd4_acquire_curproc after lwkt_switch: pid %d, "
226     "cpuid %d, curr_cpuid %d)",
227     pid_t pid, int cpuid, int curr);
228
229 KTR_INFO(KTR_USCHED_BSD4, usched, bsd4_release_curproc, 0,
230     "USCHED_BSD4(bsd4_release_curproc before select: pid %d, "
231     "cpuid %d, curr_cpuid %d)",
232     pid_t pid, int cpuid, int curr);
233
234 KTR_INFO(KTR_USCHED_BSD4, usched, bsd4_select_curproc, 0,
235     "USCHED_BSD4(bsd4_release_curproc before select: pid %d, "
236     "cpuid %d, old_pid %d, old_cpuid %d, curr_cpuid %d)",
237     pid_t pid, int cpuid, pid_t old_pid, int old_cpuid, int curr);
238
239 #ifdef SMP
240 KTR_INFO(KTR_USCHED_BSD4, usched, batchy_test_false, 0,
241     "USCHED_BSD4(batchy_looser_pri_test false: pid %d, "
242     "cpuid %d, verify_mask %lu)",
243     pid_t pid, int cpuid, cpumask_t mask);
244 KTR_INFO(KTR_USCHED_BSD4, usched, batchy_test_true, 0,
245     "USCHED_BSD4(batchy_looser_pri_test true: pid %d, "
246     "cpuid %d, verify_mask %lu)",
247     pid_t pid, int cpuid, cpumask_t mask);
248
249 KTR_INFO(KTR_USCHED_BSD4, usched, bsd4_setrunqueue_fc_smt, 0,
250     "USCHED_BSD4(bsd4_setrunqueue free cpus smt: pid %d, cpuid %d, "
251     "mask %lu, curr_cpuid %d)",
252     pid_t pid, int cpuid, cpumask_t mask, int curr);
253 KTR_INFO(KTR_USCHED_BSD4, usched, bsd4_setrunqueue_fc_non_smt, 0,
254     "USCHED_BSD4(bsd4_setrunqueue free cpus check non_smt: pid %d, "
255     "cpuid %d, mask %lu, curr_cpuid %d)",
256     pid_t pid, int cpuid, cpumask_t mask, int curr);
257 KTR_INFO(KTR_USCHED_BSD4, usched, bsd4_setrunqueue_rc, 0,
258     "USCHED_BSD4(bsd4_setrunqueue running cpus check: pid %d, "
259     "cpuid %d, mask %lu, curr_cpuid %d)",
260     pid_t pid, int cpuid, cpumask_t mask, int curr);
261 KTR_INFO(KTR_USCHED_BSD4, usched, bsd4_setrunqueue_found, 0,
262     "USCHED_BSD4(bsd4_setrunqueue found cpu: pid %d, cpuid %d, "
263     "mask %lu, found_cpuid %d, curr_cpuid %d)",
264     pid_t pid, int cpuid, cpumask_t mask, int found_cpuid, int curr);
265 KTR_INFO(KTR_USCHED_BSD4, usched, bsd4_setrunqueue_not_found, 0,
266     "USCHED_BSD4(bsd4_setrunqueue not found cpu: pid %d, cpuid %d, "
267     "try_cpuid %d, curr_cpuid %d)",
268     pid_t pid, int cpuid, int try_cpuid, int curr);
269 KTR_INFO(KTR_USCHED_BSD4, usched, bsd4_setrunqueue_found_best_cpuid, 0,
270     "USCHED_BSD4(bsd4_setrunqueue found cpu: pid %d, cpuid %d, "
271     "mask %lu, found_cpuid %d, curr_cpuid %d)",
272     pid_t pid, int cpuid, cpumask_t mask, int found_cpuid, int curr);
273 #endif
274
275 KTR_INFO(KTR_USCHED_BSD4, usched, chooseproc, 0,
276     "USCHED_BSD4(chooseproc: pid %d, old_cpuid %d, curr_cpuid %d)",
277     pid_t pid, int old_cpuid, int curr);
278 #ifdef SMP
279 KTR_INFO(KTR_USCHED_BSD4, usched, chooseproc_cc, 0,
280     "USCHED_BSD4(chooseproc_cc: pid %d, old_cpuid %d, curr_cpuid %d)",
281     pid_t pid, int old_cpuid, int curr);
282 KTR_INFO(KTR_USCHED_BSD4, usched, chooseproc_cc_not_good, 0,
283     "USCHED_BSD4(chooseproc_cc not good: pid %d, old_cpumask %lu, "
284     "sibling_mask %lu, curr_cpumask %lu)",
285     pid_t pid, cpumask_t old_cpumask, cpumask_t sibling_mask, cpumask_t curr);
286 KTR_INFO(KTR_USCHED_BSD4, usched, chooseproc_cc_elected, 0,
287     "USCHED_BSD4(chooseproc_cc elected: pid %d, old_cpumask %lu, "
288     "sibling_mask %lu, curr_cpumask: %lu)",
289     pid_t pid, cpumask_t old_cpumask, cpumask_t sibling_mask, cpumask_t curr);
290
291 KTR_INFO(KTR_USCHED_BSD4, usched, sched_thread_no_process, 0,
292     "USCHED_BSD4(sched_thread %d no process scheduled: pid %d, old_cpuid %d)",
293     int id, pid_t pid, int cpuid);
294 KTR_INFO(KTR_USCHED_BSD4, usched, sched_thread_process, 0,
295     "USCHED_BSD4(sched_thread %d process scheduled: pid %d, old_cpuid %d)",
296     int id, pid_t pid, int cpuid);
297 KTR_INFO(KTR_USCHED_BSD4, usched, sched_thread_no_process_found, 0,
298     "USCHED_BSD4(sched_thread %d no process found; tmpmask %lu)",
299     int id, cpumask_t tmpmask);
300 #endif
301
302 /*
303  * Initialize the run queues at boot time.
304  */
305 static void
306 bsd4_rqinit(void *dummy)
307 {
308         int i;
309
310         spin_init(&bsd4_spin);
311         for (i = 0; i < NQS; i++) {
312                 TAILQ_INIT(&bsd4_queues[i]);
313                 TAILQ_INIT(&bsd4_rtqueues[i]);
314                 TAILQ_INIT(&bsd4_idqueues[i]);
315         }
316         atomic_clear_cpumask(&bsd4_curprocmask, 1);
317 }
318 SYSINIT(runqueue, SI_BOOT2_USCHED, SI_ORDER_FIRST, bsd4_rqinit, NULL)
319
320 /*
321  * BSD4_ACQUIRE_CURPROC
322  *
323  * This function is called when the kernel intends to return to userland.
324  * It is responsible for making the thread the current designated userland
325  * thread for this cpu, blocking if necessary.
326  *
327  * The kernel has already depressed our LWKT priority so we must not switch
328  * until we have either assigned or disposed of the thread.
329  *
330  * WARNING! THIS FUNCTION IS ALLOWED TO CAUSE THE CURRENT THREAD TO MIGRATE
331  * TO ANOTHER CPU!  Because most of the kernel assumes that no migration will
332  * occur, this function is called only under very controlled circumstances.
333  *
334  * MPSAFE
335  */
336 static void
337 bsd4_acquire_curproc(struct lwp *lp)
338 {
339         globaldata_t gd;
340         bsd4_pcpu_t dd;
341         thread_t td;
342 #if 0
343         struct lwp *olp;
344 #endif
345
346         /*
347          * Make sure we aren't sitting on a tsleep queue.
348          */
349         td = lp->lwp_thread;
350         crit_enter_quick(td);
351         if (td->td_flags & TDF_TSLEEPQ)
352                 tsleep_remove(td);
353         bsd4_recalculate_estcpu(lp);
354
355         /*
356          * If a reschedule was requested give another thread the
357          * driver's seat.
358          */
359         if (user_resched_wanted()) {
360                 clear_user_resched();
361                 bsd4_release_curproc(lp);
362
363                 KTR_COND_LOG(usched_bsd4_acquire_curproc_urw,
364                     lp->lwp_proc->p_pid == usched_bsd4_pid_debug,
365                     lp->lwp_proc->p_pid,
366                     lp->lwp_thread->td_gd->gd_cpuid,
367                     mycpu->gd_cpuid);
368         }
369
370         /*
371          * Loop until we are the current user thread
372          */
373         gd = mycpu;
374         dd = &bsd4_pcpu[gd->gd_cpuid];
375
376         KTR_COND_LOG(usched_bsd4_acquire_curproc_before_loop,
377             lp->lwp_proc->p_pid == usched_bsd4_pid_debug,
378             lp->lwp_proc->p_pid,
379             lp->lwp_thread->td_gd->gd_cpuid,
380             gd->gd_cpuid);
381
382         do {
383                 /*
384                  * Process any pending events and higher priority threads.
385                  */
386                 lwkt_yield();
387
388                 /*
389                  * Become the currently scheduled user thread for this cpu
390                  * if we can do so trivially.
391                  *
392                  * We can steal another thread's current thread designation
393                  * on this cpu since if we are running that other thread
394                  * must not be, so we can safely deschedule it.
395                  */
396                 if (dd->uschedcp == lp) {
397                         /*
398                          * We are already the current lwp (hot path).
399                          */
400                         dd->upri = lp->lwp_priority;
401                 } else if (dd->uschedcp == NULL) {
402                         /*
403                          * We can trivially become the current lwp.
404                          */
405                         atomic_set_cpumask(&bsd4_curprocmask, gd->gd_cpumask);
406                         dd->uschedcp = lp;
407                         dd->upri = lp->lwp_priority;
408                 } else if (dd->upri > lp->lwp_priority) {
409                         /*
410                          * We can steal the current cpu's lwp designation
411                          * away simply by replacing it.  The other thread
412                          * will stall when it tries to return to userland.
413                          */
414                         dd->uschedcp = lp;
415                         dd->upri = lp->lwp_priority;
416                         /*
417                         lwkt_deschedule(olp->lwp_thread);
418                         bsd4_setrunqueue(olp);
419                         */
420                 } else {
421                         /*
422                          * We cannot become the current lwp, place the lp
423                          * on the bsd4 run-queue and deschedule ourselves.
424                          *
425                          * When we are reactivated we will have another
426                          * chance.
427                          */
428                         lwkt_deschedule(lp->lwp_thread);
429
430                         bsd4_setrunqueue(lp);
431
432                         KTR_COND_LOG(usched_bsd4_acquire_curproc_not,
433                             lp->lwp_proc->p_pid == usched_bsd4_pid_debug,
434                             lp->lwp_proc->p_pid,
435                             lp->lwp_thread->td_gd->gd_cpuid,
436                             dd->uschedcp->lwp_proc->p_pid,
437                             gd->gd_cpuid);
438
439
440                         lwkt_switch();
441
442                         /*
443                          * Reload after a switch or setrunqueue/switch possibly
444                          * moved us to another cpu.
445                          */
446                         gd = mycpu;
447                         dd = &bsd4_pcpu[gd->gd_cpuid];
448
449                         KTR_COND_LOG(usched_bsd4_acquire_curproc_switch,
450                             lp->lwp_proc->p_pid == usched_bsd4_pid_debug,
451                             lp->lwp_proc->p_pid,
452                             lp->lwp_thread->td_gd->gd_cpuid,
453                             gd->gd_cpuid);
454                 }
455         } while (dd->uschedcp != lp);
456
457         crit_exit_quick(td);
458         KKASSERT((lp->lwp_mpflags & LWP_MP_ONRUNQ) == 0);
459 }
460
461 /*
462  * BSD4_RELEASE_CURPROC
463  *
464  * This routine detaches the current thread from the userland scheduler,
465  * usually because the thread needs to run or block in the kernel (at
466  * kernel priority) for a while.
467  *
468  * This routine is also responsible for selecting a new thread to
469  * make the current thread.
470  *
471  * NOTE: This implementation differs from the dummy example in that
472  * bsd4_select_curproc() is able to select the current process, whereas
473  * dummy_select_curproc() is not able to select the current process.
474  * This means we have to NULL out uschedcp.
475  *
476  * Additionally, note that we may already be on a run queue if releasing
477  * via the lwkt_switch() in bsd4_setrunqueue().
478  *
479  * MPSAFE
480  */
481
482 static void
483 bsd4_release_curproc(struct lwp *lp)
484 {
485         globaldata_t gd = mycpu;
486         bsd4_pcpu_t dd = &bsd4_pcpu[gd->gd_cpuid];
487
488         if (dd->uschedcp == lp) {
489                 crit_enter();
490                 KKASSERT((lp->lwp_mpflags & LWP_MP_ONRUNQ) == 0);
491
492                 KTR_COND_LOG(usched_bsd4_release_curproc,
493                     lp->lwp_proc->p_pid == usched_bsd4_pid_debug,
494                     lp->lwp_proc->p_pid,
495                     lp->lwp_thread->td_gd->gd_cpuid,
496                     gd->gd_cpuid);
497
498                 dd->uschedcp = NULL;    /* don't let lp be selected */
499                 dd->upri = PRIBASE_NULL;
500                 atomic_clear_cpumask(&bsd4_curprocmask, gd->gd_cpumask);
501                 dd->old_uschedcp = lp;  /* used only for KTR debug prints */
502                 bsd4_select_curproc(gd);
503                 crit_exit();
504         }
505 }
506
507 /*
508  * BSD4_SELECT_CURPROC
509  *
510  * Select a new current process for this cpu and clear any pending user
511  * reschedule request.  The cpu currently has no current process.
512  *
513  * This routine is also responsible for equal-priority round-robining,
514  * typically triggered from bsd4_schedulerclock().  In our dummy example
515  * all the 'user' threads are LWKT scheduled all at once and we just
516  * call lwkt_switch().
517  *
518  * The calling process is not on the queue and cannot be selected.
519  *
520  * MPSAFE
521  */
522 static
523 void
524 bsd4_select_curproc(globaldata_t gd)
525 {
526         bsd4_pcpu_t dd = &bsd4_pcpu[gd->gd_cpuid];
527         struct lwp *nlp;
528         int cpuid = gd->gd_cpuid;
529
530         crit_enter_gd(gd);
531
532         spin_lock(&bsd4_spin);
533 #ifdef SMP
534         if(usched_bsd4_cache_coherent)
535                 nlp = bsd4_chooseproc_locked_cache_coherent(dd->uschedcp);
536         else
537 #endif
538                 nlp = bsd4_chooseproc_locked(dd->uschedcp);
539
540         if (nlp) {
541
542                 KTR_COND_LOG(usched_bsd4_select_curproc,
543                     nlp->lwp_proc->p_pid == usched_bsd4_pid_debug,
544                     nlp->lwp_proc->p_pid,
545                     nlp->lwp_thread->td_gd->gd_cpuid,
546                     dd->old_uschedcp->lwp_proc->p_pid,
547                     dd->old_uschedcp->lwp_thread->td_gd->gd_cpuid,
548                     gd->gd_cpuid);
549
550                 atomic_set_cpumask(&bsd4_curprocmask, CPUMASK(cpuid));
551                 dd->upri = nlp->lwp_priority;
552                 dd->uschedcp = nlp;
553                 dd->rrcount = 0;                /* reset round robin */
554                 spin_unlock(&bsd4_spin);
555 #ifdef SMP
556                 lwkt_acquire(nlp->lwp_thread);
557 #endif
558                 lwkt_schedule(nlp->lwp_thread);
559         } else {
560                 spin_unlock(&bsd4_spin);
561         }
562
563 #if 0
564         } else if (bsd4_runqcount && (bsd4_rdyprocmask & CPUMASK(cpuid))) {
565                 atomic_clear_cpumask(&bsd4_rdyprocmask, CPUMASK(cpuid));
566                 spin_unlock(&bsd4_spin);
567                 lwkt_schedule(&dd->helper_thread);
568         } else {
569                 spin_unlock(&bsd4_spin);
570         }
571 #endif
572         crit_exit_gd(gd);
573 }
574 #ifdef SMP
575
576 /*
577  * batchy_looser_pri_test() - determine if a process is batchy or not
578  * relative to the other processes running in the system
579  */
580 static int
581 bsd4_batchy_looser_pri_test(struct lwp* lp)
582 {
583         cpumask_t mask;
584         bsd4_pcpu_t other_dd;
585         int cpu;
586
587         /* Current running processes */
588         mask = bsd4_curprocmask & smp_active_mask
589             & usched_global_cpumask;
590
591         while(mask) {
592                 cpu = BSFCPUMASK(mask);
593                 other_dd = &bsd4_pcpu[cpu];
594                 if (other_dd->upri - lp->lwp_priority > usched_bsd4_upri_affinity * PPQ) {
595
596                         KTR_COND_LOG(usched_batchy_test_false,
597                             lp->lwp_proc->p_pid == usched_bsd4_pid_debug,
598                             lp->lwp_proc->p_pid,
599                             lp->lwp_thread->td_gd->gd_cpuid,
600                             (unsigned long)mask);
601
602                         return 0;
603                 }
604                 mask &= ~CPUMASK(cpu);
605         }
606
607         KTR_COND_LOG(usched_batchy_test_true,
608             lp->lwp_proc->p_pid == usched_bsd4_pid_debug,
609             lp->lwp_proc->p_pid,
610             lp->lwp_thread->td_gd->gd_cpuid,
611             (unsigned long)mask);
612
613         return 1;
614 }
615
616 #endif
617 /*
618  *
619  * BSD4_SETRUNQUEUE
620  *
621  * Place the specified lwp on the user scheduler's run queue.  This routine
622  * must be called with the thread descheduled.  The lwp must be runnable.
623  *
624  * The thread may be the current thread as a special case.
625  *
626  * MPSAFE
627  */
628 static void
629 bsd4_setrunqueue(struct lwp *lp)
630 {
631         globaldata_t gd;
632         bsd4_pcpu_t dd;
633 #ifdef SMP
634         int cpuid;
635         cpumask_t mask;
636         cpumask_t tmpmask;
637 #endif
638
639         /*
640          * First validate the process state relative to the current cpu.
641          * We don't need the spinlock for this, just a critical section.
642          * We are in control of the process.
643          */
644         crit_enter();
645         KASSERT(lp->lwp_stat == LSRUN, ("setrunqueue: lwp not LSRUN"));
646         KASSERT((lp->lwp_mpflags & LWP_MP_ONRUNQ) == 0,
647             ("lwp %d/%d already on runq! flag %08x/%08x", lp->lwp_proc->p_pid,
648              lp->lwp_tid, lp->lwp_proc->p_flags, lp->lwp_flags));
649         KKASSERT((lp->lwp_thread->td_flags & TDF_RUNQ) == 0);
650
651         /*
652          * Note: gd and dd are relative to the target thread's last cpu,
653          * NOT our current cpu.
654          */
655         gd = lp->lwp_thread->td_gd;
656         dd = &bsd4_pcpu[gd->gd_cpuid];
657
658         /*
659          * This process is not supposed to be scheduled anywhere or assigned
660          * as the current process anywhere.  Assert the condition.
661          */
662         KKASSERT(dd->uschedcp != lp);
663
664 #ifndef SMP
665         /*
666          * If we are not SMP we do not have a scheduler helper to kick
667          * and must directly activate the process if none are scheduled.
668          *
669          * This is really only an issue when bootstrapping init since
670          * the caller in all other cases will be a user process, and
671          * even if released (dd->uschedcp == NULL), that process will
672          * kickstart the scheduler when it returns to user mode from
673          * the kernel.
674          */
675         if (dd->uschedcp == NULL) {
676                 atomic_set_cpumask(&bsd4_curprocmask, gd->gd_cpumask);
677                 dd->uschedcp = lp;
678                 dd->upri = lp->lwp_priority;
679                 lwkt_schedule(lp->lwp_thread);
680                 crit_exit();
681                 return;
682         }
683 #endif
684
685 #ifdef SMP
686         /*
687          * XXX fixme.  Could be part of a remrunqueue/setrunqueue
688          * operation when the priority is recalculated, so TDF_MIGRATING
689          * may already be set.
690          */
691         if ((lp->lwp_thread->td_flags & TDF_MIGRATING) == 0)
692                 lwkt_giveaway(lp->lwp_thread);
693 #endif
694
695         /*
696          * We lose control of lp the moment we release the spinlock after
697          * having placed lp on the queue.  i.e. another cpu could pick it
698          * up and it could exit, or its priority could be further adjusted,
699          * or something like that.
700          */
701         spin_lock(&bsd4_spin);
702         bsd4_setrunqueue_locked(lp);
703         lp->lwp_rebal_ticks = sched_ticks;
704
705 #ifdef SMP
706         /*
707          * Kick the scheduler helper on one of the other cpu's
708          * and request a reschedule if appropriate.
709          *
710          * NOTE: We check all cpus whos rdyprocmask is set.  First we
711          *       look for cpus without designated lps, then we look for
712          *       cpus with designated lps with a worse priority than our
713          *       process.
714          */
715         ++bsd4_scancpu;
716
717         if (usched_bsd4_smt) {
718
719                 /*
720                  * SMT heuristic - Try to schedule on a free physical core.
721                  * If no physical core found than choose the one that has
722                  * an interactive thread.
723                  */
724
725                 int best_cpuid = -1;
726                 int min_prio = MAXPRI * MAXPRI;
727                 int sibling;
728
729                 cpuid = (bsd4_scancpu & 0xFFFF) % ncpus;
730                 mask = ~bsd4_curprocmask & bsd4_rdyprocmask & lp->lwp_cpumask &
731                     smp_active_mask & usched_global_cpumask;
732
733                 KTR_COND_LOG(usched_bsd4_setrunqueue_fc_smt,
734                     lp->lwp_proc->p_pid == usched_bsd4_pid_debug,
735                     lp->lwp_proc->p_pid,
736                     lp->lwp_thread->td_gd->gd_cpuid,
737                     (unsigned long)mask,
738                     mycpu->gd_cpuid);
739
740                 while (mask) {
741                         tmpmask = ~(CPUMASK(cpuid) - 1);
742                         if (mask & tmpmask)
743                                 cpuid = BSFCPUMASK(mask & tmpmask);
744                         else
745                                 cpuid = BSFCPUMASK(mask);
746                         gd = globaldata_find(cpuid);
747                         dd = &bsd4_pcpu[cpuid];
748
749                         if ((dd->upri & ~PPQMASK) >= (lp->lwp_priority & ~PPQMASK)) {
750                                 if (dd->cpunode->parent_node->members & ~dd->cpunode->members & mask) {
751
752                                         KTR_COND_LOG(usched_bsd4_setrunqueue_found,
753                                             lp->lwp_proc->p_pid == usched_bsd4_pid_debug,
754                                             lp->lwp_proc->p_pid,
755                                             lp->lwp_thread->td_gd->gd_cpuid,
756                                             (unsigned long)mask,
757                                             cpuid,
758                                             mycpu->gd_cpuid);
759
760                                         goto found;
761                                 } else {
762                                         sibling = BSFCPUMASK(dd->cpunode->parent_node->members &
763                                             ~dd->cpunode->members);
764                                         if (min_prio > bsd4_pcpu[sibling].upri) {
765                                                 min_prio = bsd4_pcpu[sibling].upri;
766                                                 best_cpuid = cpuid;
767                                         }
768                                 }
769                         }
770                         mask &= ~CPUMASK(cpuid);
771                 }
772
773                 if (best_cpuid != -1) {
774                         cpuid = best_cpuid;
775                         gd = globaldata_find(cpuid);
776                         dd = &bsd4_pcpu[cpuid];
777
778                         KTR_COND_LOG(usched_bsd4_setrunqueue_found_best_cpuid,
779                             lp->lwp_proc->p_pid == usched_bsd4_pid_debug,
780                             lp->lwp_proc->p_pid,
781                             lp->lwp_thread->td_gd->gd_cpuid,
782                             (unsigned long)mask,
783                             cpuid,
784                             mycpu->gd_cpuid);
785
786                         goto found;
787                 }
788         } else {
789                 /* Fallback to the original heuristic */
790                 cpuid = (bsd4_scancpu & 0xFFFF) % ncpus;
791                 mask = ~bsd4_curprocmask & bsd4_rdyprocmask & lp->lwp_cpumask &
792                        smp_active_mask & usched_global_cpumask;
793
794                 KTR_COND_LOG(usched_bsd4_setrunqueue_fc_non_smt,
795                     lp->lwp_proc->p_pid == usched_bsd4_pid_debug,
796                     lp->lwp_proc->p_pid,
797                     lp->lwp_thread->td_gd->gd_cpuid,
798                     (unsigned long)mask,
799                     mycpu->gd_cpuid);
800
801                 while (mask) {
802                         tmpmask = ~(CPUMASK(cpuid) - 1);
803                         if (mask & tmpmask)
804                                 cpuid = BSFCPUMASK(mask & tmpmask);
805                         else
806                                 cpuid = BSFCPUMASK(mask);
807                         gd = globaldata_find(cpuid);
808                         dd = &bsd4_pcpu[cpuid];
809
810                         if ((dd->upri & ~PPQMASK) >= (lp->lwp_priority & ~PPQMASK)) {
811
812                                 KTR_COND_LOG(usched_bsd4_setrunqueue_found,
813                                     lp->lwp_proc->p_pid == usched_bsd4_pid_debug,
814                                     lp->lwp_proc->p_pid,
815                                     lp->lwp_thread->td_gd->gd_cpuid,
816                                     (unsigned long)mask,
817                                     cpuid,
818                                     mycpu->gd_cpuid);
819
820                                 goto found;
821                         }
822                         mask &= ~CPUMASK(cpuid);
823                 }
824         }
825
826         /*
827          * Then cpus which might have a currently running lp
828          */
829         mask = bsd4_curprocmask & bsd4_rdyprocmask &
830                lp->lwp_cpumask & smp_active_mask & usched_global_cpumask;
831
832         KTR_COND_LOG(usched_bsd4_setrunqueue_rc,
833             lp->lwp_proc->p_pid == usched_bsd4_pid_debug,
834             lp->lwp_proc->p_pid,
835             lp->lwp_thread->td_gd->gd_cpuid,
836             (unsigned long)mask,
837             mycpu->gd_cpuid);
838
839         while (mask) {
840                 tmpmask = ~(CPUMASK(cpuid) - 1);
841                 if (mask & tmpmask)
842                         cpuid = BSFCPUMASK(mask & tmpmask);
843                 else
844                         cpuid = BSFCPUMASK(mask);
845                 gd = globaldata_find(cpuid);
846                 dd = &bsd4_pcpu[cpuid];
847
848                 if ((dd->upri & ~PPQMASK) > (lp->lwp_priority & ~PPQMASK)) {
849
850                         KTR_COND_LOG(usched_bsd4_setrunqueue_found,
851                             lp->lwp_proc->p_pid == usched_bsd4_pid_debug,
852                             lp->lwp_proc->p_pid,
853                             lp->lwp_thread->td_gd->gd_cpuid,
854                             (unsigned long)mask,
855                             cpuid,
856                             mycpu->gd_cpuid);
857
858                         goto found;
859                 }
860                 mask &= ~CPUMASK(cpuid);
861         }
862
863         /*
864          * If we cannot find a suitable cpu we reload from bsd4_scancpu
865          * and round-robin.  Other cpus will pickup as they release their
866          * current lwps or become ready.
867          *
868          * Avoid a degenerate system lockup case if usched_global_cpumask
869          * is set to 0 or otherwise does not cover lwp_cpumask.
870          *
871          * We only kick the target helper thread in this case, we do not
872          * set the user resched flag because
873          */
874         cpuid = (bsd4_scancpu & 0xFFFF) % ncpus;
875         if ((CPUMASK(cpuid) & usched_global_cpumask) == 0) {
876                 cpuid = 0;
877         }
878         gd = globaldata_find(cpuid);
879         dd = &bsd4_pcpu[cpuid];
880
881         KTR_COND_LOG(usched_bsd4_setrunqueue_not_found,
882             lp->lwp_proc->p_pid == usched_bsd4_pid_debug,
883             lp->lwp_proc->p_pid,
884             lp->lwp_thread->td_gd->gd_cpuid,
885             cpuid,
886             mycpu->gd_cpuid);
887
888 found:
889         if (gd == mycpu) {
890                 spin_unlock(&bsd4_spin);
891                 if ((dd->upri & ~PPQMASK) > (lp->lwp_priority & ~PPQMASK)) {
892                         if (dd->uschedcp == NULL) {
893                                 wakeup_mycpu(&dd->helper_thread);
894                         } else {
895                                 need_user_resched();
896                         }
897                 }
898         } else {
899                 atomic_clear_cpumask(&bsd4_rdyprocmask, CPUMASK(cpuid));
900                 spin_unlock(&bsd4_spin);
901                 if ((dd->upri & ~PPQMASK) > (lp->lwp_priority & ~PPQMASK))
902                         lwkt_send_ipiq(gd, bsd4_need_user_resched_remote, NULL);
903                 else
904                         wakeup(&dd->helper_thread);
905         }
906 #else
907         /*
908          * Request a reschedule if appropriate.
909          */
910         spin_unlock(&bsd4_spin);
911         if ((dd->upri & ~PPQMASK) > (lp->lwp_priority & ~PPQMASK)) {
912                 need_user_resched();
913         }
914 #endif
915         crit_exit();
916 }
917
918 /*
919  * This routine is called from a systimer IPI.  It MUST be MP-safe and
920  * the BGL IS NOT HELD ON ENTRY.  This routine is called at ESTCPUFREQ on
921  * each cpu.
922  *
923  * MPSAFE
924  */
925 static
926 void
927 bsd4_schedulerclock(struct lwp *lp, sysclock_t period, sysclock_t cpstamp)
928 {
929         globaldata_t gd = mycpu;
930         bsd4_pcpu_t dd = &bsd4_pcpu[gd->gd_cpuid];
931
932         /*
933          * Do we need to round-robin?  We round-robin 10 times a second.
934          * This should only occur for cpu-bound batch processes.
935          */
936         if (++dd->rrcount >= usched_bsd4_rrinterval) {
937                 dd->rrcount = 0;
938                 need_user_resched();
939         }
940
941         /*
942          * Adjust estcpu upward using a real time equivalent calculation.
943          */
944         lp->lwp_estcpu = ESTCPULIM(lp->lwp_estcpu + ESTCPUMAX / ESTCPUFREQ + 1);
945
946         /*
947          * Spinlocks also hold a critical section so there should not be
948          * any active.
949          */
950         KKASSERT(gd->gd_spinlocks_wr == 0);
951
952         bsd4_resetpriority(lp);
953 #if 0
954         /*
955         * if we can't call bsd4_resetpriority for some reason we must call
956          * need user_resched().
957          */
958         need_user_resched();
959 #endif
960 }
961
962 /*
963  * Called from acquire and from kern_synch's one-second timer (one of the
964  * callout helper threads) with a critical section held.
965  *
966  * Decay p_estcpu based on the number of ticks we haven't been running
967  * and our p_nice.  As the load increases each process observes a larger
968  * number of idle ticks (because other processes are running in them).
969  * This observation leads to a larger correction which tends to make the
970  * system more 'batchy'.
971  *
972  * Note that no recalculation occurs for a process which sleeps and wakes
973  * up in the same tick.  That is, a system doing thousands of context
974  * switches per second will still only do serious estcpu calculations
975  * ESTCPUFREQ times per second.
976  *
977  * MPSAFE
978  */
979 static
980 void
981 bsd4_recalculate_estcpu(struct lwp *lp)
982 {
983         globaldata_t gd = mycpu;
984         sysclock_t cpbase;
985         sysclock_t ttlticks;
986         int estcpu;
987         int decay_factor;
988
989         /*
990          * We have to subtract periodic to get the last schedclock
991          * timeout time, otherwise we would get the upcoming timeout.
992          * Keep in mind that a process can migrate between cpus and
993          * while the scheduler clock should be very close, boundary
994          * conditions could lead to a small negative delta.
995          */
996         cpbase = gd->gd_schedclock.time - gd->gd_schedclock.periodic;
997
998         if (lp->lwp_slptime > 1) {
999                 /*
1000                  * Too much time has passed, do a coarse correction.
1001                  */
1002                 lp->lwp_estcpu = lp->lwp_estcpu >> 1;
1003                 bsd4_resetpriority(lp);
1004                 lp->lwp_cpbase = cpbase;
1005                 lp->lwp_cpticks = 0;
1006                 lp->lwp_batch -= ESTCPUFREQ;
1007                 if (lp->lwp_batch < 0)
1008                         lp->lwp_batch = 0;
1009         } else if (lp->lwp_cpbase != cpbase) {
1010                 /*
1011                  * Adjust estcpu if we are in a different tick.  Don't waste
1012                  * time if we are in the same tick.
1013                  *
1014                  * First calculate the number of ticks in the measurement
1015                  * interval.  The ttlticks calculation can wind up 0 due to
1016                  * a bug in the handling of lwp_slptime  (as yet not found),
1017                  * so make sure we do not get a divide by 0 panic.
1018                  */
1019                 ttlticks = (cpbase - lp->lwp_cpbase) /
1020                            gd->gd_schedclock.periodic;
1021                 if (ttlticks < 0) {
1022                         ttlticks = 0;
1023                         lp->lwp_cpbase = cpbase;
1024                 }
1025                 if (ttlticks == 0)
1026                         return;
1027                 updatepcpu(lp, lp->lwp_cpticks, ttlticks);
1028
1029                 /*
1030                  * Calculate the percentage of one cpu used factoring in ncpus
1031                  * and the load and adjust estcpu.  Handle degenerate cases
1032                  * by adding 1 to bsd4_runqcount.
1033                  *
1034                  * estcpu is scaled by ESTCPUMAX.
1035                  *
1036                  * bsd4_runqcount is the excess number of user processes
1037                  * that cannot be immediately scheduled to cpus.  We want
1038                  * to count these as running to avoid range compression
1039                  * in the base calculation (which is the actual percentage
1040                  * of one cpu used).
1041                  */
1042                 estcpu = (lp->lwp_cpticks * ESTCPUMAX) *
1043                          (bsd4_runqcount + ncpus) / (ncpus * ttlticks);
1044
1045                 /*
1046                  * If estcpu is > 50% we become more batch-like
1047                  * If estcpu is <= 50% we become less batch-like
1048                  *
1049                  * It takes 30 cpu seconds to traverse the entire range.
1050                  */
1051                 if (estcpu > ESTCPUMAX / 2) {
1052                         lp->lwp_batch += ttlticks;
1053                         if (lp->lwp_batch > BATCHMAX)
1054                                 lp->lwp_batch = BATCHMAX;
1055                 } else {
1056                         lp->lwp_batch -= ttlticks;
1057                         if (lp->lwp_batch < 0)
1058                                 lp->lwp_batch = 0;
1059                 }
1060
1061                 if (usched_bsd4_debug == lp->lwp_proc->p_pid) {
1062                         kprintf("pid %d lwp %p estcpu %3d %3d bat %d cp %d/%d",
1063                                 lp->lwp_proc->p_pid, lp,
1064                                 estcpu, lp->lwp_estcpu,
1065                                 lp->lwp_batch,
1066                                 lp->lwp_cpticks, ttlticks);
1067                 }
1068
1069                 /*
1070                  * Adjust lp->lwp_esetcpu.  The decay factor determines how
1071                  * quickly lwp_estcpu collapses to its realtime calculation.
1072                  * A slower collapse gives us a more accurate number but
1073                  * can cause a cpu hog to eat too much cpu before the
1074                  * scheduler decides to downgrade it.
1075                  *
1076                  * NOTE: p_nice is accounted for in bsd4_resetpriority(),
1077                  *       and not here, but we must still ensure that a
1078                  *       cpu-bound nice -20 process does not completely
1079                  *       override a cpu-bound nice +20 process.
1080                  *
1081                  * NOTE: We must use ESTCPULIM() here to deal with any
1082                  *       overshoot.
1083                  */
1084                 decay_factor = usched_bsd4_decay;
1085                 if (decay_factor < 1)
1086                         decay_factor = 1;
1087                 if (decay_factor > 1024)
1088                         decay_factor = 1024;
1089
1090                 lp->lwp_estcpu = ESTCPULIM(
1091                         (lp->lwp_estcpu * decay_factor + estcpu) /
1092                         (decay_factor + 1));
1093
1094                 if (usched_bsd4_debug == lp->lwp_proc->p_pid)
1095                         kprintf(" finalestcpu %d\n", lp->lwp_estcpu);
1096                 bsd4_resetpriority(lp);
1097                 lp->lwp_cpbase += ttlticks * gd->gd_schedclock.periodic;
1098                 lp->lwp_cpticks = 0;
1099         }
1100 }
1101
1102 /*
1103  * Compute the priority of a process when running in user mode.
1104  * Arrange to reschedule if the resulting priority is better
1105  * than that of the current process.
1106  *
1107  * This routine may be called with any process.
1108  *
1109  * This routine is called by fork1() for initial setup with the process
1110  * of the run queue, and also may be called normally with the process on or
1111  * off the run queue.
1112  *
1113  * MPSAFE
1114  */
1115 static void
1116 bsd4_resetpriority(struct lwp *lp)
1117 {
1118         bsd4_pcpu_t dd;
1119         int newpriority;
1120         u_short newrqtype;
1121         int reschedcpu;
1122         int checkpri;
1123         int estcpu;
1124
1125         /*
1126          * Calculate the new priority and queue type
1127          */
1128         crit_enter();
1129         spin_lock(&bsd4_spin);
1130
1131         newrqtype = lp->lwp_rtprio.type;
1132
1133         switch(newrqtype) {
1134         case RTP_PRIO_REALTIME:
1135         case RTP_PRIO_FIFO:
1136                 newpriority = PRIBASE_REALTIME +
1137                              (lp->lwp_rtprio.prio & PRIMASK);
1138                 break;
1139         case RTP_PRIO_NORMAL:
1140                 /*
1141                  * Detune estcpu based on batchiness.  lwp_batch ranges
1142                  * from 0 to  BATCHMAX.  Limit estcpu for the sake of
1143                  * the priority calculation to between 50% and 100%.
1144                  */
1145                 estcpu = lp->lwp_estcpu * (lp->lwp_batch + BATCHMAX) /
1146                          (BATCHMAX * 2);
1147
1148                 /*
1149                  * p_nice piece         Adds (0-40) * 2         0-80
1150                  * estcpu               Adds 16384  * 4 / 512   0-128
1151                  */
1152                 newpriority = (lp->lwp_proc->p_nice - PRIO_MIN) * PPQ / NICEPPQ;
1153                 newpriority += estcpu * PPQ / ESTCPUPPQ;
1154                 newpriority = newpriority * MAXPRI / (PRIO_RANGE * PPQ /
1155                               NICEPPQ + ESTCPUMAX * PPQ / ESTCPUPPQ);
1156                 newpriority = PRIBASE_NORMAL + (newpriority & PRIMASK);
1157                 break;
1158         case RTP_PRIO_IDLE:
1159                 newpriority = PRIBASE_IDLE + (lp->lwp_rtprio.prio & PRIMASK);
1160                 break;
1161         case RTP_PRIO_THREAD:
1162                 newpriority = PRIBASE_THREAD + (lp->lwp_rtprio.prio & PRIMASK);
1163                 break;
1164         default:
1165                 panic("Bad RTP_PRIO %d", newrqtype);
1166                 /* NOT REACHED */
1167         }
1168
1169         /*
1170          * The newpriority incorporates the queue type so do a simple masked
1171          * check to determine if the process has moved to another queue.  If
1172          * it has, and it is currently on a run queue, then move it.
1173          */
1174         if ((lp->lwp_priority ^ newpriority) & ~PPQMASK) {
1175                 lp->lwp_priority = newpriority;
1176                 if (lp->lwp_mpflags & LWP_MP_ONRUNQ) {
1177                         bsd4_remrunqueue_locked(lp);
1178                         lp->lwp_rqtype = newrqtype;
1179                         lp->lwp_rqindex = (newpriority & PRIMASK) / PPQ;
1180                         bsd4_setrunqueue_locked(lp);
1181                         checkpri = 1;
1182                 } else {
1183                         lp->lwp_rqtype = newrqtype;
1184                         lp->lwp_rqindex = (newpriority & PRIMASK) / PPQ;
1185                         checkpri = 0;
1186                 }
1187                 reschedcpu = lp->lwp_thread->td_gd->gd_cpuid;
1188         } else {
1189                 lp->lwp_priority = newpriority;
1190                 reschedcpu = -1;
1191                 checkpri = 1;
1192         }
1193
1194         /*
1195          * Determine if we need to reschedule the target cpu.  This only
1196          * occurs if the LWP is already on a scheduler queue, which means
1197          * that idle cpu notification has already occured.  At most we
1198          * need only issue a need_user_resched() on the appropriate cpu.
1199          *
1200          * The LWP may be owned by a CPU different from the current one,
1201          * in which case dd->uschedcp may be modified without an MP lock
1202          * or a spinlock held.  The worst that happens is that the code
1203          * below causes a spurious need_user_resched() on the target CPU
1204          * and dd->pri to be wrong for a short period of time, both of
1205          * which are harmless.
1206          *
1207          * If checkpri is 0 we are adjusting the priority of the current
1208          * process, possibly higher (less desireable), so ignore the upri
1209          * check which will fail in that case.
1210          */
1211         if (reschedcpu >= 0) {
1212                 dd = &bsd4_pcpu[reschedcpu];
1213                 if ((bsd4_rdyprocmask & CPUMASK(reschedcpu)) &&
1214                     (checkpri == 0 ||
1215                      (dd->upri & ~PRIMASK) > (lp->lwp_priority & ~PRIMASK))) {
1216 #ifdef SMP
1217                         if (reschedcpu == mycpu->gd_cpuid) {
1218                                 spin_unlock(&bsd4_spin);
1219                                 need_user_resched();
1220                         } else {
1221                                 spin_unlock(&bsd4_spin);
1222                                 atomic_clear_cpumask(&bsd4_rdyprocmask,
1223                                                      CPUMASK(reschedcpu));
1224                                 lwkt_send_ipiq(lp->lwp_thread->td_gd,
1225                                                bsd4_need_user_resched_remote,
1226                                                NULL);
1227                         }
1228 #else
1229                         spin_unlock(&bsd4_spin);
1230                         need_user_resched();
1231 #endif
1232                 } else {
1233                         spin_unlock(&bsd4_spin);
1234                 }
1235         } else {
1236                 spin_unlock(&bsd4_spin);
1237         }
1238         crit_exit();
1239 }
1240
1241 /*
1242  * MPSAFE
1243  */
1244 static
1245 void
1246 bsd4_yield(struct lwp *lp)
1247 {
1248 #if 0
1249         /* FUTURE (or something similar) */
1250         switch(lp->lwp_rqtype) {
1251         case RTP_PRIO_NORMAL:
1252                 lp->lwp_estcpu = ESTCPULIM(lp->lwp_estcpu + ESTCPUINCR);
1253                 break;
1254         default:
1255                 break;
1256         }
1257 #endif
1258         need_user_resched();
1259 }
1260
1261 /*
1262  * Called from fork1() when a new child process is being created.
1263  *
1264  * Give the child process an initial estcpu that is more batch then
1265  * its parent and dock the parent for the fork (but do not
1266  * reschedule the parent).   This comprises the main part of our batch
1267  * detection heuristic for both parallel forking and sequential execs.
1268  *
1269  * XXX lwp should be "spawning" instead of "forking"
1270  *
1271  * MPSAFE
1272  */
1273 static void
1274 bsd4_forking(struct lwp *plp, struct lwp *lp)
1275 {
1276         /*
1277          * Put the child 4 queue slots (out of 32) higher than the parent
1278          * (less desireable than the parent).
1279          */
1280         lp->lwp_estcpu = ESTCPULIM(plp->lwp_estcpu + ESTCPUPPQ * 4);
1281
1282         /*
1283          * The batch status of children always starts out centerline
1284          * and will inch-up or inch-down as appropriate.  It takes roughly
1285          * ~15 seconds of >50% cpu to hit the limit.
1286          */
1287         lp->lwp_batch = BATCHMAX / 2;
1288
1289         /*
1290          * Dock the parent a cost for the fork, protecting us from fork
1291          * bombs.  If the parent is forking quickly make the child more
1292          * batchy.
1293          */
1294         plp->lwp_estcpu = ESTCPULIM(plp->lwp_estcpu + ESTCPUPPQ / 16);
1295 }
1296
1297 /*
1298  * Called when a lwp is being removed from this scheduler, typically
1299  * during lwp_exit().
1300  */
1301 static void
1302 bsd4_exiting(struct lwp *lp, struct proc *child_proc)
1303 {
1304 }
1305
1306 static void
1307 bsd4_uload_update(struct lwp *lp)
1308 {
1309 }
1310
1311 /*
1312  * chooseproc() is called when a cpu needs a user process to LWKT schedule,
1313  * it selects a user process and returns it.  If chklp is non-NULL and chklp
1314  * has a better or equal priority then the process that would otherwise be
1315  * chosen, NULL is returned.
1316  *
1317  * Until we fix the RUNQ code the chklp test has to be strict or we may
1318  * bounce between processes trying to acquire the current process designation.
1319  *
1320  * MPSAFE - must be called with bsd4_spin exclusive held.  The spinlock is
1321  *          left intact through the entire routine.
1322  */
1323 static
1324 struct lwp *
1325 bsd4_chooseproc_locked(struct lwp *chklp)
1326 {
1327         struct lwp *lp;
1328         struct rq *q;
1329         u_int32_t *which, *which2;
1330         u_int32_t pri;
1331         u_int32_t rtqbits;
1332         u_int32_t tsqbits;
1333         u_int32_t idqbits;
1334         cpumask_t cpumask;
1335
1336         rtqbits = bsd4_rtqueuebits;
1337         tsqbits = bsd4_queuebits;
1338         idqbits = bsd4_idqueuebits;
1339         cpumask = mycpu->gd_cpumask;
1340
1341
1342 #ifdef SMP
1343 again:
1344 #endif
1345         if (rtqbits) {
1346                 pri = bsfl(rtqbits);
1347                 q = &bsd4_rtqueues[pri];
1348                 which = &bsd4_rtqueuebits;
1349                 which2 = &rtqbits;
1350         } else if (tsqbits) {
1351                 pri = bsfl(tsqbits);
1352                 q = &bsd4_queues[pri];
1353                 which = &bsd4_queuebits;
1354                 which2 = &tsqbits;
1355         } else if (idqbits) {
1356                 pri = bsfl(idqbits);
1357                 q = &bsd4_idqueues[pri];
1358                 which = &bsd4_idqueuebits;
1359                 which2 = &idqbits;
1360         } else {
1361                 return NULL;
1362         }
1363         lp = TAILQ_FIRST(q);
1364         KASSERT(lp, ("chooseproc: no lwp on busy queue"));
1365
1366 #ifdef SMP
1367         while ((lp->lwp_cpumask & cpumask) == 0) {
1368                 lp = TAILQ_NEXT(lp, lwp_procq);
1369                 if (lp == NULL) {
1370                         *which2 &= ~(1 << pri);
1371                         goto again;
1372                 }
1373         }
1374 #endif
1375
1376         /*
1377          * If the passed lwp <chklp> is reasonably close to the selected
1378          * lwp <lp>, return NULL (indicating that <chklp> should be kept).
1379          *
1380          * Note that we must error on the side of <chklp> to avoid bouncing
1381          * between threads in the acquire code.
1382          */
1383         if (chklp) {
1384                 if (chklp->lwp_priority < lp->lwp_priority + PPQ)
1385                         return(NULL);
1386         }
1387
1388 #ifdef SMP
1389         /*
1390          * If the chosen lwp does not reside on this cpu spend a few
1391          * cycles looking for a better candidate at the same priority level.
1392          * This is a fallback check, setrunqueue() tries to wakeup the
1393          * correct cpu and is our front-line affinity.
1394          */
1395         if (lp->lwp_thread->td_gd != mycpu &&
1396             (chklp = TAILQ_NEXT(lp, lwp_procq)) != NULL
1397         ) {
1398                 if (chklp->lwp_thread->td_gd == mycpu) {
1399                         lp = chklp;
1400                 }
1401         }
1402 #endif
1403
1404         KTR_COND_LOG(usched_chooseproc,
1405             lp->lwp_proc->p_pid == usched_bsd4_pid_debug,
1406             lp->lwp_proc->p_pid,
1407             lp->lwp_thread->td_gd->gd_cpuid,
1408             mycpu->gd_cpuid);
1409
1410         TAILQ_REMOVE(q, lp, lwp_procq);
1411         --bsd4_runqcount;
1412         if (TAILQ_EMPTY(q))
1413                 *which &= ~(1 << pri);
1414         KASSERT((lp->lwp_mpflags & LWP_MP_ONRUNQ) != 0, ("not on runq6!"));
1415         atomic_clear_int(&lp->lwp_mpflags, LWP_MP_ONRUNQ);
1416
1417         return lp;
1418 }
1419
1420 #ifdef SMP
1421 /*
1422  * chooseproc() - with a cache coherence heuristic. Try to pull a process that
1423  * has its home on the current CPU> If the process doesn't have its home here
1424  * and is a batchy one (see batcy_looser_pri_test), we can wait for a
1425  * sched_tick, may be its home will become free and pull it in. Anyway,
1426  * we can't wait more than one tick. If that tick expired, we pull in that
1427  * process, no matter what.
1428  */
1429 static
1430 struct lwp *
1431 bsd4_chooseproc_locked_cache_coherent(struct lwp *chklp)
1432 {
1433         struct lwp *lp;
1434         struct rq *q;
1435         u_int32_t *which, *which2;
1436         u_int32_t pri;
1437         u_int32_t checks;
1438         u_int32_t rtqbits;
1439         u_int32_t tsqbits;
1440         u_int32_t idqbits;
1441         cpumask_t cpumask;
1442
1443         struct lwp * min_level_lwp = NULL;
1444         struct rq *min_q = NULL;
1445         cpumask_t siblings;
1446         cpu_node_t* cpunode = NULL;
1447         u_int32_t min_level = MAXCPU;   /* number of levels < MAXCPU */
1448         u_int32_t *min_which = NULL;
1449         u_int32_t min_pri = 0;
1450         u_int32_t level = 0;
1451
1452         rtqbits = bsd4_rtqueuebits;
1453         tsqbits = bsd4_queuebits;
1454         idqbits = bsd4_idqueuebits;
1455         cpumask = mycpu->gd_cpumask;
1456
1457         /* Get the mask coresponding to the sysctl configured level */
1458         cpunode = bsd4_pcpu[mycpu->gd_cpuid].cpunode;
1459         level = usched_bsd4_stick_to_level;
1460         while (level) {
1461                 cpunode = cpunode->parent_node;
1462                 level--;
1463         }
1464         /* The cpus which can ellect a process */
1465         siblings = cpunode->members;
1466         checks = 0;
1467
1468 again:
1469         if (rtqbits) {
1470                 pri = bsfl(rtqbits);
1471                 q = &bsd4_rtqueues[pri];
1472                 which = &bsd4_rtqueuebits;
1473                 which2 = &rtqbits;
1474         } else if (tsqbits) {
1475                 pri = bsfl(tsqbits);
1476                 q = &bsd4_queues[pri];
1477                 which = &bsd4_queuebits;
1478                 which2 = &tsqbits;
1479         } else if (idqbits) {
1480                 pri = bsfl(idqbits);
1481                 q = &bsd4_idqueues[pri];
1482                 which = &bsd4_idqueuebits;
1483                 which2 = &idqbits;
1484         } else {
1485                 /*
1486                  * No more left and we didn't reach the checks limit.
1487                  */
1488                 bsd4_kick_helper(min_level_lwp);
1489                 return NULL;
1490         }
1491         lp = TAILQ_FIRST(q);
1492         KASSERT(lp, ("chooseproc: no lwp on busy queue"));
1493
1494         /*
1495          * Limit the number of checks/queue to a configurable value to
1496          * minimize the contention (we are in a locked region
1497          */
1498         while (checks < usched_bsd4_queue_checks) {
1499                 if ((lp->lwp_cpumask & cpumask) == 0 ||
1500                     ((siblings & lp->lwp_thread->td_gd->gd_cpumask) == 0 &&
1501                       (lp->lwp_rebal_ticks == sched_ticks ||
1502                        lp->lwp_rebal_ticks == (int)(sched_ticks - 1)) &&
1503                       bsd4_batchy_looser_pri_test(lp))) {
1504
1505                         KTR_COND_LOG(usched_chooseproc_cc_not_good,
1506                             lp->lwp_proc->p_pid == usched_bsd4_pid_debug,
1507                             lp->lwp_proc->p_pid,
1508                             (unsigned long)lp->lwp_thread->td_gd->gd_cpumask,
1509                             (unsigned long)siblings,
1510                             (unsigned long)cpumask);
1511
1512                         cpunode = bsd4_pcpu[lp->lwp_thread->td_gd->gd_cpuid].cpunode;
1513                         level = 0;
1514                         while (cpunode) {
1515                                 if (cpunode->members & cpumask)
1516                                         break;
1517                                 cpunode = cpunode->parent_node;
1518                                 level++;
1519                         }
1520                         if (level < min_level ||
1521                             (level == min_level && min_level_lwp &&
1522                              lp->lwp_priority < min_level_lwp->lwp_priority)) {
1523                                 bsd4_kick_helper(min_level_lwp);
1524                                 min_level_lwp = lp;
1525                                 min_level = level;
1526                                 min_q = q;
1527                                 min_which = which;
1528                                 min_pri = pri;
1529                         } else {
1530                                 bsd4_kick_helper(lp);
1531                         }
1532                         lp = TAILQ_NEXT(lp, lwp_procq);
1533                         if (lp == NULL) {
1534                                 *which2 &= ~(1 << pri);
1535                                 goto again;
1536                         }
1537                 } else {
1538                         KTR_COND_LOG(usched_chooseproc_cc_elected,
1539                             lp->lwp_proc->p_pid == usched_bsd4_pid_debug,
1540                             lp->lwp_proc->p_pid,
1541                             (unsigned long)lp->lwp_thread->td_gd->gd_cpumask,
1542                             (unsigned long)siblings,
1543                             (unsigned long)cpumask);
1544
1545                         goto found;
1546                 }
1547                 ++checks;
1548         }
1549
1550         /*
1551          * Checks exhausted, we tried to defer too many threads, so schedule
1552          * the best of the worst.
1553          */
1554         lp = min_level_lwp;
1555         q = min_q;
1556         which = min_which;
1557         pri = min_pri;
1558         KASSERT(lp, ("chooseproc: at least the first lp was good"));
1559
1560 found:
1561
1562         /*
1563          * If the passed lwp <chklp> is reasonably close to the selected
1564          * lwp <lp>, return NULL (indicating that <chklp> should be kept).
1565          *
1566          * Note that we must error on the side of <chklp> to avoid bouncing
1567          * between threads in the acquire code.
1568          */
1569         if (chklp) {
1570                 if (chklp->lwp_priority < lp->lwp_priority + PPQ) {
1571                         bsd4_kick_helper(lp);
1572                         return(NULL);
1573                 }
1574         }
1575
1576         KTR_COND_LOG(usched_chooseproc_cc,
1577             lp->lwp_proc->p_pid == usched_bsd4_pid_debug,
1578             lp->lwp_proc->p_pid,
1579             lp->lwp_thread->td_gd->gd_cpuid,
1580             mycpu->gd_cpuid);
1581
1582         TAILQ_REMOVE(q, lp, lwp_procq);
1583         --bsd4_runqcount;
1584         if (TAILQ_EMPTY(q))
1585                 *which &= ~(1 << pri);
1586         KASSERT((lp->lwp_mpflags & LWP_MP_ONRUNQ) != 0, ("not on runq6!"));
1587         atomic_clear_int(&lp->lwp_mpflags, LWP_MP_ONRUNQ);
1588
1589         return lp;
1590 }
1591
1592 /*
1593  * If we aren't willing to schedule a ready process on our cpu, give it's
1594  * target cpu a kick rather than wait for the next tick.
1595  *
1596  * Called with bsd4_spin held.
1597  */
1598 static
1599 void
1600 bsd4_kick_helper(struct lwp *lp)
1601 {
1602         globaldata_t gd;
1603         bsd4_pcpu_t dd;
1604
1605         if (lp == NULL)
1606                 return;
1607         gd = lp->lwp_thread->td_gd;
1608         dd = &bsd4_pcpu[gd->gd_cpuid];
1609         if ((smp_active_mask & usched_global_cpumask &
1610             bsd4_rdyprocmask & gd->gd_cpumask) == 0) {
1611                 return;
1612         }
1613         ++usched_bsd4_kicks;
1614         atomic_clear_cpumask(&bsd4_rdyprocmask, gd->gd_cpumask);
1615         if ((dd->upri & ~PPQMASK) > (lp->lwp_priority & ~PPQMASK)) {
1616                 lwkt_send_ipiq(gd, bsd4_need_user_resched_remote, NULL);
1617         } else {
1618                 wakeup(&dd->helper_thread);
1619         }
1620 }
1621
1622 static
1623 void
1624 bsd4_need_user_resched_remote(void *dummy)
1625 {
1626         globaldata_t gd = mycpu;
1627         bsd4_pcpu_t  dd = &bsd4_pcpu[gd->gd_cpuid];
1628
1629         need_user_resched();
1630
1631         /* Call wakeup_mycpu to avoid sending IPIs to other CPUs */
1632         wakeup_mycpu(&dd->helper_thread);
1633 }
1634
1635 #endif
1636
1637 /*
1638  * bsd4_remrunqueue_locked() removes a given process from the run queue
1639  * that it is on, clearing the queue busy bit if it becomes empty.
1640  *
1641  * Note that user process scheduler is different from the LWKT schedule.
1642  * The user process scheduler only manages user processes but it uses LWKT
1643  * underneath, and a user process operating in the kernel will often be
1644  * 'released' from our management.
1645  *
1646  * MPSAFE - bsd4_spin must be held exclusively on call
1647  */
1648 static void
1649 bsd4_remrunqueue_locked(struct lwp *lp)
1650 {
1651         struct rq *q;
1652         u_int32_t *which;
1653         u_int8_t pri;
1654
1655         KKASSERT(lp->lwp_mpflags & LWP_MP_ONRUNQ);
1656         atomic_clear_int(&lp->lwp_mpflags, LWP_MP_ONRUNQ);
1657         --bsd4_runqcount;
1658         KKASSERT(bsd4_runqcount >= 0);
1659
1660         pri = lp->lwp_rqindex;
1661         switch(lp->lwp_rqtype) {
1662         case RTP_PRIO_NORMAL:
1663                 q = &bsd4_queues[pri];
1664                 which = &bsd4_queuebits;
1665                 break;
1666         case RTP_PRIO_REALTIME:
1667         case RTP_PRIO_FIFO:
1668                 q = &bsd4_rtqueues[pri];
1669                 which = &bsd4_rtqueuebits;
1670                 break;
1671         case RTP_PRIO_IDLE:
1672                 q = &bsd4_idqueues[pri];
1673                 which = &bsd4_idqueuebits;
1674                 break;
1675         default:
1676                 panic("remrunqueue: invalid rtprio type");
1677                 /* NOT REACHED */
1678         }
1679         TAILQ_REMOVE(q, lp, lwp_procq);
1680         if (TAILQ_EMPTY(q)) {
1681                 KASSERT((*which & (1 << pri)) != 0,
1682                         ("remrunqueue: remove from empty queue"));
1683                 *which &= ~(1 << pri);
1684         }
1685 }
1686
1687 /*
1688  * bsd4_setrunqueue_locked()
1689  *
1690  * Add a process whos rqtype and rqindex had previously been calculated
1691  * onto the appropriate run queue.   Determine if the addition requires
1692  * a reschedule on a cpu and return the cpuid or -1.
1693  *
1694  * NOTE: Lower priorities are better priorities.
1695  *
1696  * MPSAFE - bsd4_spin must be held exclusively on call
1697  */
1698 static void
1699 bsd4_setrunqueue_locked(struct lwp *lp)
1700 {
1701         struct rq *q;
1702         u_int32_t *which;
1703         int pri;
1704
1705         KKASSERT((lp->lwp_mpflags & LWP_MP_ONRUNQ) == 0);
1706         atomic_set_int(&lp->lwp_mpflags, LWP_MP_ONRUNQ);
1707         ++bsd4_runqcount;
1708
1709         pri = lp->lwp_rqindex;
1710
1711         switch(lp->lwp_rqtype) {
1712         case RTP_PRIO_NORMAL:
1713                 q = &bsd4_queues[pri];
1714                 which = &bsd4_queuebits;
1715                 break;
1716         case RTP_PRIO_REALTIME:
1717         case RTP_PRIO_FIFO:
1718                 q = &bsd4_rtqueues[pri];
1719                 which = &bsd4_rtqueuebits;
1720                 break;
1721         case RTP_PRIO_IDLE:
1722                 q = &bsd4_idqueues[pri];
1723                 which = &bsd4_idqueuebits;
1724                 break;
1725         default:
1726                 panic("remrunqueue: invalid rtprio type");
1727                 /* NOT REACHED */
1728         }
1729
1730         /*
1731          * Add to the correct queue and set the appropriate bit.  If no
1732          * lower priority (i.e. better) processes are in the queue then
1733          * we want a reschedule, calculate the best cpu for the job.
1734          *
1735          * Always run reschedules on the LWPs original cpu.
1736          */
1737         TAILQ_INSERT_TAIL(q, lp, lwp_procq);
1738         *which |= 1 << pri;
1739 }
1740
1741 #ifdef SMP
1742
1743 /*
1744  * For SMP systems a user scheduler helper thread is created for each
1745  * cpu and is used to allow one cpu to wakeup another for the purposes of
1746  * scheduling userland threads from setrunqueue().
1747  *
1748  * UP systems do not need the helper since there is only one cpu.
1749  *
1750  * We can't use the idle thread for this because we might block.
1751  * Additionally, doing things this way allows us to HLT idle cpus
1752  * on MP systems.
1753  *
1754  * MPSAFE
1755  */
1756 static void
1757 sched_thread(void *dummy)
1758 {
1759     globaldata_t gd;
1760     bsd4_pcpu_t  dd;
1761     bsd4_pcpu_t  tmpdd;
1762     struct lwp *nlp;
1763     cpumask_t mask;
1764     int cpuid;
1765     cpumask_t tmpmask;
1766     int tmpid;
1767
1768     gd = mycpu;
1769     cpuid = gd->gd_cpuid;       /* doesn't change */
1770     mask = gd->gd_cpumask;      /* doesn't change */
1771     dd = &bsd4_pcpu[cpuid];
1772
1773     /*
1774      * Since we are woken up only when no user processes are scheduled
1775      * on a cpu, we can run at an ultra low priority.
1776      */
1777     lwkt_setpri_self(TDPRI_USER_SCHEDULER);
1778
1779     tsleep(&dd->helper_thread, 0, "sched_thread_sleep", 0);
1780
1781     for (;;) {
1782         /*
1783          * We use the LWKT deschedule-interlock trick to avoid racing
1784          * bsd4_rdyprocmask.  This means we cannot block through to the
1785          * manual lwkt_switch() call we make below.
1786          */
1787         crit_enter_gd(gd);
1788         tsleep_interlock(&dd->helper_thread, 0);
1789         spin_lock(&bsd4_spin);
1790         atomic_set_cpumask(&bsd4_rdyprocmask, mask);
1791
1792         clear_user_resched();   /* This satisfied the reschedule request */
1793         dd->rrcount = 0;        /* Reset the round-robin counter */
1794
1795         if ((bsd4_curprocmask & mask) == 0) {
1796                 /*
1797                  * No thread is currently scheduled.
1798                  */
1799                 KKASSERT(dd->uschedcp == NULL);
1800                 if ((nlp = bsd4_chooseproc_locked(NULL)) != NULL) {
1801                         KTR_COND_LOG(usched_sched_thread_no_process,
1802                             nlp->lwp_proc->p_pid == usched_bsd4_pid_debug,
1803                             gd->gd_cpuid,
1804                             nlp->lwp_proc->p_pid,
1805                             nlp->lwp_thread->td_gd->gd_cpuid);
1806
1807                         atomic_set_cpumask(&bsd4_curprocmask, mask);
1808                         dd->upri = nlp->lwp_priority;
1809                         dd->uschedcp = nlp;
1810                         dd->rrcount = 0;        /* reset round robin */
1811                         spin_unlock(&bsd4_spin);
1812                         lwkt_acquire(nlp->lwp_thread);
1813                         lwkt_schedule(nlp->lwp_thread);
1814                 } else {
1815                         spin_unlock(&bsd4_spin);
1816                 }
1817         } else if (bsd4_runqcount) {
1818                 if ((nlp = bsd4_chooseproc_locked(dd->uschedcp)) != NULL) {
1819                         KTR_COND_LOG(usched_sched_thread_process,
1820                             nlp->lwp_proc->p_pid == usched_bsd4_pid_debug,
1821                             gd->gd_cpuid,
1822                             nlp->lwp_proc->p_pid,
1823                             nlp->lwp_thread->td_gd->gd_cpuid);
1824
1825                         dd->upri = nlp->lwp_priority;
1826                         dd->uschedcp = nlp;
1827                         dd->rrcount = 0;        /* reset round robin */
1828                         spin_unlock(&bsd4_spin);
1829                         lwkt_acquire(nlp->lwp_thread);
1830                         lwkt_schedule(nlp->lwp_thread);
1831                 } else {
1832                         /*
1833                          * CHAINING CONDITION TRAIN
1834                          *
1835                          * We could not deal with the scheduler wakeup
1836                          * request on this cpu, locate a ready scheduler
1837                          * with no current lp assignment and chain to it.
1838                          *
1839                          * This ensures that a wakeup race which fails due
1840                          * to priority test does not leave other unscheduled
1841                          * cpus idle when the runqueue is not empty.
1842                          */
1843                         tmpmask = ~bsd4_curprocmask &
1844                                   bsd4_rdyprocmask & smp_active_mask;
1845                         if (tmpmask) {
1846                                 tmpid = BSFCPUMASK(tmpmask);
1847                                 tmpdd = &bsd4_pcpu[tmpid];
1848                                 atomic_clear_cpumask(&bsd4_rdyprocmask,
1849                                                      CPUMASK(tmpid));
1850                                 spin_unlock(&bsd4_spin);
1851                                 wakeup(&tmpdd->helper_thread);
1852                         } else {
1853                                 spin_unlock(&bsd4_spin);
1854                         }
1855
1856                         KTR_LOG(usched_sched_thread_no_process_found,
1857                                 gd->gd_cpuid, (unsigned long)tmpmask);
1858                 }
1859         } else {
1860                 /*
1861                  * The runq is empty.
1862                  */
1863                 spin_unlock(&bsd4_spin);
1864         }
1865
1866         /*
1867          * We're descheduled unless someone scheduled us.  Switch away.
1868          * Exiting the critical section will cause splz() to be called
1869          * for us if interrupts and such are pending.
1870          */
1871         crit_exit_gd(gd);
1872         tsleep(&dd->helper_thread, PINTERLOCKED, "schslp", 0);
1873     }
1874 }
1875
1876 /* sysctl stick_to_level parameter */
1877 static int
1878 sysctl_usched_bsd4_stick_to_level(SYSCTL_HANDLER_ARGS)
1879 {
1880         int error, new_val;
1881
1882         new_val = usched_bsd4_stick_to_level;
1883
1884         error = sysctl_handle_int(oidp, &new_val, 0, req);
1885         if (error != 0 || req->newptr == NULL)
1886                 return (error);
1887         if (new_val > cpu_topology_levels_number - 1 || new_val < 0)
1888                 return (EINVAL);
1889         usched_bsd4_stick_to_level = new_val;
1890         return (0);
1891 }
1892
1893 /*
1894  * Setup our scheduler helpers.  Note that curprocmask bit 0 has already
1895  * been cleared by rqinit() and we should not mess with it further.
1896  */
1897 static void
1898 sched_thread_cpu_init(void)
1899 {
1900         int i;
1901         int cpuid;
1902         int smt_not_supported = 0;
1903         int cache_coherent_not_supported = 0;
1904
1905         if (bootverbose)
1906                 kprintf("Start scheduler helpers on cpus:\n");
1907
1908         sysctl_ctx_init(&usched_bsd4_sysctl_ctx);
1909         usched_bsd4_sysctl_tree =
1910                 SYSCTL_ADD_NODE(&usched_bsd4_sysctl_ctx,
1911                                 SYSCTL_STATIC_CHILDREN(_kern), OID_AUTO,
1912                                 "usched_bsd4", CTLFLAG_RD, 0, "");
1913
1914         for (i = 0; i < ncpus; ++i) {
1915                 bsd4_pcpu_t dd = &bsd4_pcpu[i];
1916                 cpumask_t mask = CPUMASK(i);
1917
1918                 if ((mask & smp_active_mask) == 0)
1919                     continue;
1920
1921                 dd->cpunode = get_cpu_node_by_cpuid(i);
1922
1923                 if (dd->cpunode == NULL) {
1924                         smt_not_supported = 1;
1925                         cache_coherent_not_supported = 1;
1926                         if (bootverbose)
1927                                 kprintf ("\tcpu%d - WARNING: No CPU NODE "
1928                                          "found for cpu\n", i);
1929                 } else {
1930                         switch (dd->cpunode->type) {
1931                         case THREAD_LEVEL:
1932                                 if (bootverbose)
1933                                         kprintf ("\tcpu%d - HyperThreading "
1934                                                  "available. Core siblings: ",
1935                                                  i);
1936                                 break;
1937                         case CORE_LEVEL:
1938                                 smt_not_supported = 1;
1939
1940                                 if (bootverbose)
1941                                         kprintf ("\tcpu%d - No HT available, "
1942                                                  "multi-core/physical "
1943                                                  "cpu. Physical siblings: ",
1944                                                  i);
1945                                 break;
1946                         case CHIP_LEVEL:
1947                                 smt_not_supported = 1;
1948
1949                                 if (bootverbose)
1950                                         kprintf ("\tcpu%d - No HT available, "
1951                                                  "single-core/physical cpu. "
1952                                                  "Package Siblings: ",
1953                                                  i);
1954                                 break;
1955                         default:
1956                                 /* Let's go for safe defaults here */
1957                                 smt_not_supported = 1;
1958                                 cache_coherent_not_supported = 1;
1959                                 if (bootverbose)
1960                                         kprintf ("\tcpu%d - Unknown cpunode->"
1961                                                  "type=%u. Siblings: ",
1962                                                  i,
1963                                                  (u_int)dd->cpunode->type);
1964                                 break;
1965                         }
1966
1967                         if (bootverbose) {
1968                                 if (dd->cpunode->parent_node != NULL) {
1969                                         CPUSET_FOREACH(cpuid, dd->cpunode->parent_node->members)
1970                                                 kprintf("cpu%d ", cpuid);
1971                                         kprintf("\n");
1972                                 } else {
1973                                         kprintf(" no siblings\n");
1974                                 }
1975                         }
1976                 }
1977
1978                 lwkt_create(sched_thread, NULL, NULL, &dd->helper_thread,
1979                             0, i, "usched %d", i);
1980
1981                 /*
1982                  * Allow user scheduling on the target cpu.  cpu #0 has already
1983                  * been enabled in rqinit().
1984                  */
1985                 if (i)
1986                     atomic_clear_cpumask(&bsd4_curprocmask, mask);
1987                 atomic_set_cpumask(&bsd4_rdyprocmask, mask);
1988                 dd->upri = PRIBASE_NULL;
1989
1990         }
1991
1992         /* usched_bsd4 sysctl configurable parameters */
1993
1994         SYSCTL_ADD_INT(&usched_bsd4_sysctl_ctx,
1995                        SYSCTL_CHILDREN(usched_bsd4_sysctl_tree),
1996                        OID_AUTO, "rrinterval", CTLFLAG_RW,
1997                        &usched_bsd4_rrinterval, 0, "");
1998         SYSCTL_ADD_INT(&usched_bsd4_sysctl_ctx,
1999                        SYSCTL_CHILDREN(usched_bsd4_sysctl_tree),
2000                        OID_AUTO, "decay", CTLFLAG_RW,
2001                        &usched_bsd4_decay, 0, "Extra decay when not running");
2002         SYSCTL_ADD_INT(&usched_bsd4_sysctl_ctx,
2003                        SYSCTL_CHILDREN(usched_bsd4_sysctl_tree),
2004                        OID_AUTO, "batch_time", CTLFLAG_RW,
2005                        &usched_bsd4_batch_time, 0, "Min batch counter value");
2006         SYSCTL_ADD_LONG(&usched_bsd4_sysctl_ctx,
2007                        SYSCTL_CHILDREN(usched_bsd4_sysctl_tree),
2008                        OID_AUTO, "kicks", CTLFLAG_RW,
2009                        &usched_bsd4_kicks, "Number of kickstarts");
2010
2011         /* Add enable/disable option for SMT scheduling if supported */
2012         if (smt_not_supported) {
2013                 usched_bsd4_smt = 0;
2014                 SYSCTL_ADD_STRING(&usched_bsd4_sysctl_ctx,
2015                                   SYSCTL_CHILDREN(usched_bsd4_sysctl_tree),
2016                                   OID_AUTO, "smt", CTLFLAG_RD,
2017                                   "NOT SUPPORTED", 0, "SMT NOT SUPPORTED");
2018         } else {
2019                 usched_bsd4_smt = 1;
2020                 SYSCTL_ADD_INT(&usched_bsd4_sysctl_ctx,
2021                                SYSCTL_CHILDREN(usched_bsd4_sysctl_tree),
2022                                OID_AUTO, "smt", CTLFLAG_RW,
2023                                &usched_bsd4_smt, 0, "Enable SMT scheduling");
2024         }
2025
2026         /*
2027          * Add enable/disable option for cache coherent scheduling
2028          * if supported
2029          */
2030         if (cache_coherent_not_supported) {
2031                 usched_bsd4_cache_coherent = 0;
2032                 SYSCTL_ADD_STRING(&usched_bsd4_sysctl_ctx,
2033                                   SYSCTL_CHILDREN(usched_bsd4_sysctl_tree),
2034                                   OID_AUTO, "cache_coherent", CTLFLAG_RD,
2035                                   "NOT SUPPORTED", 0,
2036                                   "Cache coherence NOT SUPPORTED");
2037         } else {
2038                 usched_bsd4_cache_coherent = 1;
2039                 SYSCTL_ADD_INT(&usched_bsd4_sysctl_ctx,
2040                                SYSCTL_CHILDREN(usched_bsd4_sysctl_tree),
2041                                OID_AUTO, "cache_coherent", CTLFLAG_RW,
2042                                &usched_bsd4_cache_coherent, 0,
2043                                "Enable/Disable cache coherent scheduling");
2044
2045                 SYSCTL_ADD_INT(&usched_bsd4_sysctl_ctx,
2046                                SYSCTL_CHILDREN(usched_bsd4_sysctl_tree),
2047                                OID_AUTO, "upri_affinity", CTLFLAG_RW,
2048                                &usched_bsd4_upri_affinity, 1,
2049                                "Number of PPQs in user priority check");
2050
2051                 SYSCTL_ADD_INT(&usched_bsd4_sysctl_ctx,
2052                                SYSCTL_CHILDREN(usched_bsd4_sysctl_tree),
2053                                OID_AUTO, "queue_checks", CTLFLAG_RW,
2054                                &usched_bsd4_queue_checks, 5,
2055                                "LWPs to check from a queue before giving up");
2056
2057                 SYSCTL_ADD_PROC(&usched_bsd4_sysctl_ctx,
2058                                 SYSCTL_CHILDREN(usched_bsd4_sysctl_tree),
2059                                 OID_AUTO, "stick_to_level",
2060                                 CTLTYPE_INT | CTLFLAG_RW,
2061                                 NULL, sizeof usched_bsd4_stick_to_level,
2062                                 sysctl_usched_bsd4_stick_to_level, "I",
2063                                 "Stick a process to this level. See sysctl"
2064                                 "paremter hw.cpu_topology.level_description");
2065         }
2066 }
2067 SYSINIT(uschedtd, SI_BOOT2_USCHED, SI_ORDER_SECOND,
2068         sched_thread_cpu_init, NULL)
2069
2070 #else /* No SMP options - just add the configurable parameters to sysctl */
2071
2072 static void
2073 sched_sysctl_tree_init(void)
2074 {
2075         sysctl_ctx_init(&usched_bsd4_sysctl_ctx);
2076         usched_bsd4_sysctl_tree =
2077                 SYSCTL_ADD_NODE(&usched_bsd4_sysctl_ctx,
2078                                 SYSCTL_STATIC_CHILDREN(_kern), OID_AUTO,
2079                                 "usched_bsd4", CTLFLAG_RD, 0, "");
2080
2081         /* usched_bsd4 sysctl configurable parameters */
2082         SYSCTL_ADD_INT(&usched_bsd4_sysctl_ctx,
2083                        SYSCTL_CHILDREN(usched_bsd4_sysctl_tree),
2084                        OID_AUTO, "rrinterval", CTLFLAG_RW,
2085                        &usched_bsd4_rrinterval, 0, "");
2086         SYSCTL_ADD_INT(&usched_bsd4_sysctl_ctx,
2087                        SYSCTL_CHILDREN(usched_bsd4_sysctl_tree),
2088                        OID_AUTO, "decay", CTLFLAG_RW,
2089                        &usched_bsd4_decay, 0, "Extra decay when not running");
2090         SYSCTL_ADD_INT(&usched_bsd4_sysctl_ctx,
2091                        SYSCTL_CHILDREN(usched_bsd4_sysctl_tree),
2092                        OID_AUTO, "batch_time", CTLFLAG_RW,
2093                        &usched_bsd4_batch_time, 0, "Min batch counter value");
2094 }
2095 SYSINIT(uschedtd, SI_BOOT2_USCHED, SI_ORDER_SECOND,
2096         sched_sysctl_tree_init, NULL)
2097 #endif