Merge branch 'vendor/GCC47'
[dragonfly.git] / sys / kern / usched_dfly.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  *
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in
18  *    the documentation and/or other materials provided with the
19  *    distribution.
20  * 3. Neither the name of The DragonFly Project nor the names of its
21  *    contributors may be used to endorse or promote products derived
22  *    from this software without specific, prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
27  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
28  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
29  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
30  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
31  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
32  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
33  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
34  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35  * SUCH DAMAGE.
36  */
37 #include <sys/param.h>
38 #include <sys/systm.h>
39 #include <sys/kernel.h>
40 #include <sys/lock.h>
41 #include <sys/queue.h>
42 #include <sys/proc.h>
43 #include <sys/rtprio.h>
44 #include <sys/uio.h>
45 #include <sys/sysctl.h>
46 #include <sys/resourcevar.h>
47 #include <sys/spinlock.h>
48 #include <sys/cpu_topology.h>
49 #include <sys/thread2.h>
50 #include <sys/spinlock2.h>
51 #include <sys/mplock2.h>
52
53 #include <sys/ktr.h>
54
55 #include <machine/cpu.h>
56 #include <machine/smp.h>
57
58 /*
59  * Priorities.  Note that with 32 run queues per scheduler each queue
60  * represents four priority levels.
61  */
62
63 int dfly_rebalanced;
64
65 #define MAXPRI                  128
66 #define PRIMASK                 (MAXPRI - 1)
67 #define PRIBASE_REALTIME        0
68 #define PRIBASE_NORMAL          MAXPRI
69 #define PRIBASE_IDLE            (MAXPRI * 2)
70 #define PRIBASE_THREAD          (MAXPRI * 3)
71 #define PRIBASE_NULL            (MAXPRI * 4)
72
73 #define NQS     32                      /* 32 run queues. */
74 #define PPQ     (MAXPRI / NQS)          /* priorities per queue */
75 #define PPQMASK (PPQ - 1)
76
77 /*
78  * NICEPPQ      - number of nice units per priority queue
79  * ESTCPUPPQ    - number of estcpu units per priority queue
80  * ESTCPUMAX    - number of estcpu units
81  */
82 #define NICEPPQ         2
83 #define ESTCPUPPQ       512
84 #define ESTCPUMAX       (ESTCPUPPQ * NQS)
85 #define BATCHMAX        (ESTCPUFREQ * 30)
86 #define PRIO_RANGE      (PRIO_MAX - PRIO_MIN + 1)
87
88 #define ESTCPULIM(v)    min((v), ESTCPUMAX)
89
90 TAILQ_HEAD(rq, lwp);
91
92 #define lwp_priority    lwp_usdata.dfly.priority
93 #define lwp_forked      lwp_usdata.dfly.forked
94 #define lwp_rqindex     lwp_usdata.dfly.rqindex
95 #define lwp_estcpu      lwp_usdata.dfly.estcpu
96 #define lwp_estfast     lwp_usdata.dfly.estfast
97 #define lwp_uload       lwp_usdata.dfly.uload
98 #define lwp_rqtype      lwp_usdata.dfly.rqtype
99 #define lwp_qcpu        lwp_usdata.dfly.qcpu
100 #define lwp_rrcount     lwp_usdata.dfly.rrcount
101
102 struct usched_dfly_pcpu {
103         struct spinlock spin;
104         struct thread   helper_thread;
105         short           unusde01;
106         short           upri;
107         int             uload;
108         int             ucount;
109         struct lwp      *uschedcp;
110         struct rq       queues[NQS];
111         struct rq       rtqueues[NQS];
112         struct rq       idqueues[NQS];
113         u_int32_t       queuebits;
114         u_int32_t       rtqueuebits;
115         u_int32_t       idqueuebits;
116         int             runqcount;
117         int             cpuid;
118         cpumask_t       cpumask;
119 #ifdef SMP
120         cpu_node_t      *cpunode;
121 #endif
122 };
123
124 typedef struct usched_dfly_pcpu *dfly_pcpu_t;
125
126 static void dfly_acquire_curproc(struct lwp *lp);
127 static void dfly_release_curproc(struct lwp *lp);
128 static void dfly_select_curproc(globaldata_t gd);
129 static void dfly_setrunqueue(struct lwp *lp);
130 static void dfly_setrunqueue_dd(dfly_pcpu_t rdd, struct lwp *lp);
131 static void dfly_schedulerclock(struct lwp *lp, sysclock_t period,
132                                 sysclock_t cpstamp);
133 static void dfly_recalculate_estcpu(struct lwp *lp);
134 static void dfly_resetpriority(struct lwp *lp);
135 static void dfly_forking(struct lwp *plp, struct lwp *lp);
136 static void dfly_exiting(struct lwp *lp, struct proc *);
137 static void dfly_uload_update(struct lwp *lp);
138 static void dfly_yield(struct lwp *lp);
139 #ifdef SMP
140 static void dfly_changeqcpu_locked(struct lwp *lp,
141                                 dfly_pcpu_t dd, dfly_pcpu_t rdd);
142 static dfly_pcpu_t dfly_choose_best_queue(struct lwp *lp);
143 static dfly_pcpu_t dfly_choose_worst_queue(dfly_pcpu_t dd);
144 static dfly_pcpu_t dfly_choose_queue_simple(dfly_pcpu_t dd, struct lwp *lp);
145 #endif
146
147 #ifdef SMP
148 static void dfly_need_user_resched_remote(void *dummy);
149 #endif
150 static struct lwp *dfly_chooseproc_locked(dfly_pcpu_t rdd, dfly_pcpu_t dd,
151                                           struct lwp *chklp, int worst);
152 static void dfly_remrunqueue_locked(dfly_pcpu_t dd, struct lwp *lp);
153 static void dfly_setrunqueue_locked(dfly_pcpu_t dd, struct lwp *lp);
154
155 struct usched usched_dfly = {
156         { NULL },
157         "dfly", "Original DragonFly Scheduler",
158         NULL,                   /* default registration */
159         NULL,                   /* default deregistration */
160         dfly_acquire_curproc,
161         dfly_release_curproc,
162         dfly_setrunqueue,
163         dfly_schedulerclock,
164         dfly_recalculate_estcpu,
165         dfly_resetpriority,
166         dfly_forking,
167         dfly_exiting,
168         dfly_uload_update,
169         NULL,                   /* setcpumask not supported */
170         dfly_yield
171 };
172
173 /*
174  * We have NQS (32) run queues per scheduling class.  For the normal
175  * class, there are 128 priorities scaled onto these 32 queues.  New
176  * processes are added to the last entry in each queue, and processes
177  * are selected for running by taking them from the head and maintaining
178  * a simple FIFO arrangement.  Realtime and Idle priority processes have
179  * and explicit 0-31 priority which maps directly onto their class queue
180  * index.  When a queue has something in it, the corresponding bit is
181  * set in the queuebits variable, allowing a single read to determine
182  * the state of all 32 queues and then a ffs() to find the first busy
183  * queue.
184  */
185 static cpumask_t dfly_curprocmask = -1; /* currently running a user process */
186 static cpumask_t dfly_rdyprocmask;      /* ready to accept a user process */
187 #ifdef SMP
188 static volatile int dfly_scancpu;
189 #endif
190 static volatile int dfly_ucount;        /* total running on whole system */
191 static struct usched_dfly_pcpu dfly_pcpu[MAXCPU];
192 static struct sysctl_ctx_list usched_dfly_sysctl_ctx;
193 static struct sysctl_oid *usched_dfly_sysctl_tree;
194
195 /* Debug info exposed through debug.* sysctl */
196
197 static int usched_dfly_debug = -1;
198 SYSCTL_INT(_debug, OID_AUTO, dfly_scdebug, CTLFLAG_RW,
199            &usched_dfly_debug, 0,
200            "Print debug information for this pid");
201
202 static int usched_dfly_pid_debug = -1;
203 SYSCTL_INT(_debug, OID_AUTO, dfly_pid_debug, CTLFLAG_RW,
204            &usched_dfly_pid_debug, 0,
205            "Print KTR debug information for this pid");
206
207 static int usched_dfly_chooser = 0;
208 SYSCTL_INT(_debug, OID_AUTO, dfly_chooser, CTLFLAG_RW,
209            &usched_dfly_chooser, 0,
210            "Print KTR debug information for this pid");
211
212 /*
213  * Tunning usched_dfly - configurable through kern.usched_dfly.
214  *
215  * weight1 - Tries to keep threads on their current cpu.  If you
216  *           make this value too large the scheduler will not be
217  *           able to load-balance large loads.
218  *
219  * weight2 - If non-zero, detects thread pairs undergoing synchronous
220  *           communications and tries to move them closer together.
221  *           Behavior is adjusted by bit 4 of features (0x10).
222  *
223  *           WARNING!  Weight2 is a ridiculously sensitive parameter,
224  *           a small value is recommended.
225  *
226  * weight3 - Weighting based on the number of recently runnable threads
227  *           on the userland scheduling queue (ignoring their loads).
228  *           A nominal value here prevents high-priority (low-load)
229  *           threads from accumulating on one cpu core when other
230  *           cores are available.
231  *
232  *           This value should be left fairly small relative to weight1
233  *           and weight4.
234  *
235  * weight4 - Weighting based on other cpu queues being available
236  *           or running processes with higher lwp_priority's.
237  *
238  *           This allows a thread to migrate to another nearby cpu if it
239  *           is unable to run on the current cpu based on the other cpu
240  *           being idle or running a lower priority (higher lwp_priority)
241  *           thread.  This value should be large enough to override weight1
242  *
243  * features - These flags can be set or cleared to enable or disable various
244  *            features.
245  *
246  *            0x01      Enable idle-cpu pulling                 (default)
247  *            0x02      Enable proactive pushing                (default)
248  *            0x04      Enable rebalancing rover                (default)
249  *            0x08      Enable more proactive pushing           (default)
250  *            0x10      (flip weight2 limit on same cpu)        (default)
251  *            0x20      choose best cpu for forked process
252  *            0x40      choose current cpu for forked process
253  *            0x80      choose random cpu for forked process    (default)
254  */
255 #ifdef SMP
256 static int usched_dfly_smt = 0;
257 static int usched_dfly_cache_coherent = 0;
258 static int usched_dfly_weight1 = 200;   /* keep thread on current cpu */
259 static int usched_dfly_weight2 = 180;   /* synchronous peer's current cpu */
260 static int usched_dfly_weight3 = 40;    /* number of threads on queue */
261 static int usched_dfly_weight4 = 160;   /* availability of idle cores */
262 static int usched_dfly_fast_resched = 0;/* delta priority / resched */
263 static int usched_dfly_features = 0x8F; /* allow pulls */
264 static int usched_dfly_swmask = ~PPQMASK; /* allow pulls */
265 #endif
266 static int usched_dfly_rrinterval = (ESTCPUFREQ + 9) / 10;
267 static int usched_dfly_decay = 8;
268
269 /* KTR debug printings */
270
271 KTR_INFO_MASTER(usched);
272
273 #if !defined(KTR_USCHED_DFLY)
274 #define KTR_USCHED_DFLY KTR_ALL
275 #endif
276
277 KTR_INFO(KTR_USCHED_DFLY, usched, chooseproc, 0,
278     "USCHED_DFLY(chooseproc: pid %d, old_cpuid %d, curr_cpuid %d)",
279     pid_t pid, int old_cpuid, int curr);
280
281 /*
282  * This function is called when the kernel intends to return to userland.
283  * It is responsible for making the thread the current designated userland
284  * thread for this cpu, blocking if necessary.
285  *
286  * The kernel will not depress our LWKT priority until after we return,
287  * in case we have to shove over to another cpu.
288  *
289  * We must determine our thread's disposition before we switch away.  This
290  * is very sensitive code.
291  *
292  * WARNING! THIS FUNCTION IS ALLOWED TO CAUSE THE CURRENT THREAD TO MIGRATE
293  * TO ANOTHER CPU!  Because most of the kernel assumes that no migration will
294  * occur, this function is called only under very controlled circumstances.
295  */
296 static void
297 dfly_acquire_curproc(struct lwp *lp)
298 {
299         globaldata_t gd;
300         dfly_pcpu_t dd;
301 #ifdef SMP
302         dfly_pcpu_t rdd;
303 #endif
304         thread_t td;
305         int force_resched;
306
307         /*
308          * Make sure we aren't sitting on a tsleep queue.
309          */
310         td = lp->lwp_thread;
311         crit_enter_quick(td);
312         if (td->td_flags & TDF_TSLEEPQ)
313                 tsleep_remove(td);
314         dfly_recalculate_estcpu(lp);
315
316         gd = mycpu;
317         dd = &dfly_pcpu[gd->gd_cpuid];
318
319         /*
320          * Process any pending interrupts/ipi's, then handle reschedule
321          * requests.  dfly_release_curproc() will try to assign a new
322          * uschedcp that isn't us and otherwise NULL it out.
323          */
324         force_resched = 0;
325         if ((td->td_mpflags & TDF_MP_BATCH_DEMARC) &&
326             lp->lwp_rrcount >= usched_dfly_rrinterval / 2) {
327                 force_resched = 1;
328         }
329
330         if (user_resched_wanted()) {
331                 if (dd->uschedcp == lp)
332                         force_resched = 1;
333                 clear_user_resched();
334                 dfly_release_curproc(lp);
335         }
336
337         /*
338          * Loop until we are the current user thread.
339          *
340          * NOTE: dd spinlock not held at top of loop.
341          */
342         if (dd->uschedcp == lp)
343                 lwkt_yield_quick();
344
345         while (dd->uschedcp != lp) {
346                 lwkt_yield_quick();
347
348                 spin_lock(&dd->spin);
349
350                 /*
351                  * We are not or are no longer the current lwp and a forced
352                  * reschedule was requested.  Figure out the best cpu to
353                  * run on (our current cpu will be given significant weight).
354                  *
355                  * (if a reschedule was not requested we want to move this
356                  *  step after the uschedcp tests).
357                  */
358 #ifdef SMP
359                 if (force_resched &&
360                     (usched_dfly_features & 0x08) &&
361                     (rdd = dfly_choose_best_queue(lp)) != dd) {
362                         dfly_changeqcpu_locked(lp, dd, rdd);
363                         spin_unlock(&dd->spin);
364                         lwkt_deschedule(lp->lwp_thread);
365                         dfly_setrunqueue_dd(rdd, lp);
366                         lwkt_switch();
367                         gd = mycpu;
368                         dd = &dfly_pcpu[gd->gd_cpuid];
369                         continue;
370                 }
371 #endif
372
373                 /*
374                  * Either no reschedule was requested or the best queue was
375                  * dd, and no current process has been selected.  We can
376                  * trivially become the current lwp on the current cpu.
377                  */
378                 if (dd->uschedcp == NULL) {
379                         atomic_set_cpumask(&dfly_curprocmask, gd->gd_cpumask);
380                         dd->uschedcp = lp;
381                         dd->upri = lp->lwp_priority;
382                         KKASSERT(lp->lwp_qcpu == dd->cpuid);
383                         spin_unlock(&dd->spin);
384                         break;
385                 }
386
387                 /*
388                  * Can we steal the current designated user thread?
389                  *
390                  * If we do the other thread will stall when it tries to
391                  * return to userland, possibly rescheduling elsewhere.
392                  *
393                  * It is important to do a masked test to avoid the edge
394                  * case where two near-equal-priority threads are constantly
395                  * interrupting each other.
396                  *
397                  * In the exact match case another thread has already gained
398                  * uschedcp and lowered its priority, if we steal it the
399                  * other thread will stay stuck on the LWKT runq and not
400                  * push to another cpu.  So don't steal on equal-priority even
401                  * though it might appear to be more beneficial due to not
402                  * having to switch back to the other thread's context.
403                  *
404                  * usched_dfly_fast_resched requires that two threads be
405                  * significantly far apart in priority in order to interrupt.
406                  *
407                  * If better but not sufficiently far apart, the current
408                  * uschedcp will be interrupted at the next scheduler clock.
409                  */
410                 if (dd->uschedcp &&
411                    (dd->upri & ~PPQMASK) >
412                    (lp->lwp_priority & ~PPQMASK) + usched_dfly_fast_resched) {
413                         dd->uschedcp = lp;
414                         dd->upri = lp->lwp_priority;
415                         KKASSERT(lp->lwp_qcpu == dd->cpuid);
416                         spin_unlock(&dd->spin);
417                         break;
418                 }
419 #ifdef SMP
420                 /*
421                  * We are not the current lwp, figure out the best cpu
422                  * to run on (our current cpu will be given significant
423                  * weight).  Loop on cpu change.
424                  */
425                 if ((usched_dfly_features & 0x02) &&
426                     force_resched == 0 &&
427                     (rdd = dfly_choose_best_queue(lp)) != dd) {
428                         dfly_changeqcpu_locked(lp, dd, rdd);
429                         spin_unlock(&dd->spin);
430                         lwkt_deschedule(lp->lwp_thread);
431                         dfly_setrunqueue_dd(rdd, lp);
432                         lwkt_switch();
433                         gd = mycpu;
434                         dd = &dfly_pcpu[gd->gd_cpuid];
435                         continue;
436                 }
437 #endif
438
439                 /*
440                  * We cannot become the current lwp, place the lp on the
441                  * run-queue of this or another cpu and deschedule ourselves.
442                  *
443                  * When we are reactivated we will have another chance.
444                  *
445                  * Reload after a switch or setrunqueue/switch possibly
446                  * moved us to another cpu.
447                  */
448                 spin_unlock(&dd->spin);
449                 lwkt_deschedule(lp->lwp_thread);
450                 dfly_setrunqueue_dd(dd, lp);
451                 lwkt_switch();
452                 gd = mycpu;
453                 dd = &dfly_pcpu[gd->gd_cpuid];
454         }
455
456         /*
457          * Make sure upri is synchronized, then yield to LWKT threads as
458          * needed before returning.  This could result in another reschedule.
459          * XXX
460          */
461         crit_exit_quick(td);
462
463         KKASSERT((lp->lwp_mpflags & LWP_MP_ONRUNQ) == 0);
464 }
465
466 /*
467  * DFLY_RELEASE_CURPROC
468  *
469  * This routine detaches the current thread from the userland scheduler,
470  * usually because the thread needs to run or block in the kernel (at
471  * kernel priority) for a while.
472  *
473  * This routine is also responsible for selecting a new thread to
474  * make the current thread.
475  *
476  * NOTE: This implementation differs from the dummy example in that
477  * dfly_select_curproc() is able to select the current process, whereas
478  * dummy_select_curproc() is not able to select the current process.
479  * This means we have to NULL out uschedcp.
480  *
481  * Additionally, note that we may already be on a run queue if releasing
482  * via the lwkt_switch() in dfly_setrunqueue().
483  */
484 static void
485 dfly_release_curproc(struct lwp *lp)
486 {
487         globaldata_t gd = mycpu;
488         dfly_pcpu_t dd = &dfly_pcpu[gd->gd_cpuid];
489
490         /*
491          * Make sure td_wakefromcpu is defaulted.  This will be overwritten
492          * by wakeup().
493          */
494         if (dd->uschedcp == lp) {
495                 KKASSERT((lp->lwp_mpflags & LWP_MP_ONRUNQ) == 0);
496                 spin_lock(&dd->spin);
497                 if (dd->uschedcp == lp) {
498                         dd->uschedcp = NULL;    /* don't let lp be selected */
499                         dd->upri = PRIBASE_NULL;
500                         atomic_clear_cpumask(&dfly_curprocmask, gd->gd_cpumask);
501                         spin_unlock(&dd->spin);
502                         dfly_select_curproc(gd);
503                 } else {
504                         spin_unlock(&dd->spin);
505                 }
506         }
507 }
508
509 /*
510  * DFLY_SELECT_CURPROC
511  *
512  * Select a new current process for this cpu and clear any pending user
513  * reschedule request.  The cpu currently has no current process.
514  *
515  * This routine is also responsible for equal-priority round-robining,
516  * typically triggered from dfly_schedulerclock().  In our dummy example
517  * all the 'user' threads are LWKT scheduled all at once and we just
518  * call lwkt_switch().
519  *
520  * The calling process is not on the queue and cannot be selected.
521  */
522 static
523 void
524 dfly_select_curproc(globaldata_t gd)
525 {
526         dfly_pcpu_t dd = &dfly_pcpu[gd->gd_cpuid];
527         struct lwp *nlp;
528         int cpuid = gd->gd_cpuid;
529
530         crit_enter_gd(gd);
531
532         spin_lock(&dd->spin);
533         nlp = dfly_chooseproc_locked(dd, dd, dd->uschedcp, 0);
534
535         if (nlp) {
536                 atomic_set_cpumask(&dfly_curprocmask, CPUMASK(cpuid));
537                 dd->upri = nlp->lwp_priority;
538                 dd->uschedcp = nlp;
539 #if 0
540                 dd->rrcount = 0;                /* reset round robin */
541 #endif
542                 spin_unlock(&dd->spin);
543 #ifdef SMP
544                 lwkt_acquire(nlp->lwp_thread);
545 #endif
546                 lwkt_schedule(nlp->lwp_thread);
547         } else {
548                 spin_unlock(&dd->spin);
549         }
550         crit_exit_gd(gd);
551 }
552
553 /*
554  * Place the specified lwp on the user scheduler's run queue.  This routine
555  * must be called with the thread descheduled.  The lwp must be runnable.
556  * It must not be possible for anyone else to explicitly schedule this thread.
557  *
558  * The thread may be the current thread as a special case.
559  */
560 static void
561 dfly_setrunqueue(struct lwp *lp)
562 {
563         dfly_pcpu_t dd;
564         dfly_pcpu_t rdd;
565
566         /*
567          * First validate the process LWKT state.
568          */
569         KASSERT(lp->lwp_stat == LSRUN, ("setrunqueue: lwp not LSRUN"));
570         KASSERT((lp->lwp_mpflags & LWP_MP_ONRUNQ) == 0,
571             ("lwp %d/%d already on runq! flag %08x/%08x", lp->lwp_proc->p_pid,
572              lp->lwp_tid, lp->lwp_proc->p_flags, lp->lwp_flags));
573         KKASSERT((lp->lwp_thread->td_flags & TDF_RUNQ) == 0);
574
575         /*
576          * NOTE: dd/rdd do not necessarily represent the current cpu.
577          *       Instead they may represent the cpu the thread was last
578          *       scheduled on or inherited by its parent.
579          */
580         dd = &dfly_pcpu[lp->lwp_qcpu];
581         rdd = dd;
582
583         /*
584          * This process is not supposed to be scheduled anywhere or assigned
585          * as the current process anywhere.  Assert the condition.
586          */
587         KKASSERT(rdd->uschedcp != lp);
588
589 #ifndef SMP
590         /*
591          * If we are not SMP we do not have a scheduler helper to kick
592          * and must directly activate the process if none are scheduled.
593          *
594          * This is really only an issue when bootstrapping init since
595          * the caller in all other cases will be a user process, and
596          * even if released (rdd->uschedcp == NULL), that process will
597          * kickstart the scheduler when it returns to user mode from
598          * the kernel.
599          *
600          * NOTE: On SMP we can't just set some other cpu's uschedcp.
601          */
602         if (rdd->uschedcp == NULL) {
603                 spin_lock(&rdd->spin);
604                 if (rdd->uschedcp == NULL) {
605                         atomic_set_cpumask(&dfly_curprocmask, 1);
606                         rdd->uschedcp = lp;
607                         rdd->upri = lp->lwp_priority;
608                         spin_unlock(&rdd->spin);
609                         lwkt_schedule(lp->lwp_thread);
610                         return;
611                 }
612                 spin_unlock(&rdd->spin);
613         }
614 #endif
615
616 #ifdef SMP
617         /*
618          * Ok, we have to setrunqueue some target cpu and request a reschedule
619          * if necessary.
620          *
621          * We have to choose the best target cpu.  It might not be the current
622          * target even if the current cpu has no running user thread (for
623          * example, because the current cpu might be a hyperthread and its
624          * sibling has a thread assigned).
625          *
626          * If we just forked it is most optimal to run the child on the same
627          * cpu just in case the parent decides to wait for it (thus getting
628          * off that cpu).  As long as there is nothing else runnable on the
629          * cpu, that is.  If we did this unconditionally a parent forking
630          * multiple children before waiting (e.g. make -j N) leaves other
631          * cpus idle that could be working.
632          */
633         if (lp->lwp_forked) {
634                 lp->lwp_forked = 0;
635                 if (usched_dfly_features & 0x20)
636                         rdd = dfly_choose_best_queue(lp);
637                 else if (usched_dfly_features & 0x40)
638                         rdd = &dfly_pcpu[lp->lwp_qcpu];
639                 else if (usched_dfly_features & 0x80)
640                         rdd = dfly_choose_queue_simple(rdd, lp);
641                 else if (dfly_pcpu[lp->lwp_qcpu].runqcount)
642                         rdd = dfly_choose_best_queue(lp);
643                 else
644                         rdd = &dfly_pcpu[lp->lwp_qcpu];
645         } else {
646                 rdd = dfly_choose_best_queue(lp);
647                 /* rdd = &dfly_pcpu[lp->lwp_qcpu]; */
648         }
649         if (lp->lwp_qcpu != rdd->cpuid) {
650                 spin_lock(&dd->spin);
651                 dfly_changeqcpu_locked(lp, dd, rdd);
652                 spin_unlock(&dd->spin);
653         }
654 #endif
655         dfly_setrunqueue_dd(rdd, lp);
656 }
657
658 #ifdef SMP
659
660 /*
661  * Change qcpu to rdd->cpuid.  The dd the lp is CURRENTLY on must be
662  * spin-locked on-call.  rdd does not have to be.
663  */
664 static void
665 dfly_changeqcpu_locked(struct lwp *lp, dfly_pcpu_t dd, dfly_pcpu_t rdd)
666 {
667         if (lp->lwp_qcpu != rdd->cpuid) {
668                 if (lp->lwp_mpflags & LWP_MP_ULOAD) {
669                         atomic_clear_int(&lp->lwp_mpflags, LWP_MP_ULOAD);
670                         atomic_add_int(&dd->uload, -lp->lwp_uload);
671                         atomic_add_int(&dd->ucount, -1);
672                         atomic_add_int(&dfly_ucount, -1);
673                 }
674                 lp->lwp_qcpu = rdd->cpuid;
675         }
676 }
677
678 #endif
679
680 /*
681  * Place lp on rdd's runqueue.  Nothing is locked on call.  This function
682  * also performs all necessary ancillary notification actions.
683  */
684 static void
685 dfly_setrunqueue_dd(dfly_pcpu_t rdd, struct lwp *lp)
686 {
687 #ifdef SMP
688         globaldata_t rgd;
689
690         /*
691          * We might be moving the lp to another cpu's run queue, and once
692          * on the runqueue (even if it is our cpu's), another cpu can rip
693          * it away from us.
694          *
695          * TDF_MIGRATING might already be set if this is part of a
696          * remrunqueue+setrunqueue sequence.
697          */
698         if ((lp->lwp_thread->td_flags & TDF_MIGRATING) == 0)
699                 lwkt_giveaway(lp->lwp_thread);
700
701         rgd = globaldata_find(rdd->cpuid);
702
703         /*
704          * We lose control of the lp the moment we release the spinlock
705          * after having placed it on the queue.  i.e. another cpu could pick
706          * it up, or it could exit, or its priority could be further
707          * adjusted, or something like that.
708          *
709          * WARNING! rdd can point to a foreign cpu!
710          */
711         spin_lock(&rdd->spin);
712         dfly_setrunqueue_locked(rdd, lp);
713
714         /*
715          * Potentially interrupt the currently-running thread
716          */
717         if ((rdd->upri & ~PPQMASK) <= (lp->lwp_priority & ~PPQMASK)) {
718                 /*
719                  * Currently running thread is better or same, do not
720                  * interrupt.
721                  */
722                 spin_unlock(&rdd->spin);
723         } else if ((rdd->upri & ~PPQMASK) <= (lp->lwp_priority & ~PPQMASK) +
724                    usched_dfly_fast_resched) {
725                 /*
726                  * Currently running thread is not better, but not so bad
727                  * that we need to interrupt it.  Let it run for one more
728                  * scheduler tick.
729                  */
730                 if (rdd->uschedcp &&
731                     rdd->uschedcp->lwp_rrcount < usched_dfly_rrinterval) {
732                         rdd->uschedcp->lwp_rrcount = usched_dfly_rrinterval - 1;
733                 }
734                 spin_unlock(&rdd->spin);
735         } else if (rgd == mycpu) {
736                 /*
737                  * We should interrupt the currently running thread, which
738                  * is on the current cpu.
739                  */
740                 spin_unlock(&rdd->spin);
741                 if (rdd->uschedcp == NULL) {
742                         wakeup_mycpu(&rdd->helper_thread); /* XXX */
743                         need_user_resched();
744                 } else {
745                         need_user_resched();
746                 }
747         } else {
748                 /*
749                  * We should interrupt the currently running thread, which
750                  * is on a different cpu.
751                  */
752                 spin_unlock(&rdd->spin);
753                 lwkt_send_ipiq(rgd, dfly_need_user_resched_remote, NULL);
754         }
755 #else
756         /*
757          * Request a reschedule if appropriate.
758          */
759         spin_lock(&rdd->spin);
760         dfly_setrunqueue_locked(rdd, lp);
761         spin_unlock(&rdd->spin);
762         if ((rdd->upri & ~PPQMASK) > (lp->lwp_priority & ~PPQMASK)) {
763                 need_user_resched();
764         }
765 #endif
766 }
767
768 /*
769  * This routine is called from a systimer IPI.  It MUST be MP-safe and
770  * the BGL IS NOT HELD ON ENTRY.  This routine is called at ESTCPUFREQ on
771  * each cpu.
772  */
773 static
774 void
775 dfly_schedulerclock(struct lwp *lp, sysclock_t period, sysclock_t cpstamp)
776 {
777         globaldata_t gd = mycpu;
778         dfly_pcpu_t dd = &dfly_pcpu[gd->gd_cpuid];
779
780         /*
781          * Spinlocks also hold a critical section so there should not be
782          * any active.
783          */
784         KKASSERT(gd->gd_spinlocks == 0);
785
786         if (lp == NULL)
787                 return;
788
789         /*
790          * Do we need to round-robin?  We round-robin 10 times a second.
791          * This should only occur for cpu-bound batch processes.
792          */
793         if (++lp->lwp_rrcount >= usched_dfly_rrinterval) {
794                 lp->lwp_thread->td_wakefromcpu = -1;
795                 need_user_resched();
796         }
797
798         /*
799          * Adjust estcpu upward using a real time equivalent calculation,
800          * and recalculate lp's priority.
801          */
802         lp->lwp_estcpu = ESTCPULIM(lp->lwp_estcpu + ESTCPUMAX / ESTCPUFREQ + 1);
803         dfly_resetpriority(lp);
804
805         /*
806          * Rebalance two cpus every 8 ticks, pulling the worst thread
807          * from the worst cpu's queue into a rotating cpu number.
808          *
809          * This mechanic is needed because the push algorithms can
810          * steady-state in an non-optimal configuration.  We need to mix it
811          * up a little, even if it means breaking up a paired thread, so
812          * the push algorithms can rebalance the degenerate conditions.
813          * This portion of the algorithm exists to ensure stability at the
814          * selected weightings.
815          *
816          * Because we might be breaking up optimal conditions we do not want
817          * to execute this too quickly, hence we only rebalance approximately
818          * ~7-8 times per second.  The push's, on the otherhand, are capable
819          * moving threads to other cpus at a much higher rate.
820          *
821          * We choose the most heavily loaded thread from the worst queue
822          * in order to ensure that multiple heavy-weight threads on the same
823          * queue get broken up, and also because these threads are the most
824          * likely to be able to remain in place.  Hopefully then any pairings,
825          * if applicable, migrate to where these threads are.
826          */
827 #ifdef SMP
828         if ((usched_dfly_features & 0x04) &&
829             ((u_int)sched_ticks & 7) == 0 &&
830             (u_int)sched_ticks / 8 % ncpus == gd->gd_cpuid) {
831                 /*
832                  * Our cpu is up.
833                  */
834                 struct lwp *nlp;
835                 dfly_pcpu_t rdd;
836
837                 rdd = dfly_choose_worst_queue(dd);
838                 if (rdd) {
839                         spin_lock(&dd->spin);
840                         if (spin_trylock(&rdd->spin)) {
841                                 nlp = dfly_chooseproc_locked(rdd, dd, NULL, 1);
842                                 spin_unlock(&rdd->spin);
843                                 if (nlp == NULL)
844                                         spin_unlock(&dd->spin);
845                         } else {
846                                 spin_unlock(&dd->spin);
847                                 nlp = NULL;
848                         }
849                 } else {
850                         nlp = NULL;
851                 }
852                 /* dd->spin held if nlp != NULL */
853
854                 /*
855                  * Either schedule it or add it to our queue.
856                  */
857                 if (nlp &&
858                     (nlp->lwp_priority & ~PPQMASK) < (dd->upri & ~PPQMASK)) {
859                         atomic_set_cpumask(&dfly_curprocmask, dd->cpumask);
860                         dd->upri = nlp->lwp_priority;
861                         dd->uschedcp = nlp;
862 #if 0
863                         dd->rrcount = 0;        /* reset round robin */
864 #endif
865                         spin_unlock(&dd->spin);
866                         lwkt_acquire(nlp->lwp_thread);
867                         lwkt_schedule(nlp->lwp_thread);
868                 } else if (nlp) {
869                         dfly_setrunqueue_locked(dd, nlp);
870                         spin_unlock(&dd->spin);
871                 }
872         }
873 #endif
874 }
875
876 /*
877  * Called from acquire and from kern_synch's one-second timer (one of the
878  * callout helper threads) with a critical section held.
879  *
880  * Adjust p_estcpu based on our single-cpu load, p_nice, and compensate for
881  * overall system load.
882  *
883  * Note that no recalculation occurs for a process which sleeps and wakes
884  * up in the same tick.  That is, a system doing thousands of context
885  * switches per second will still only do serious estcpu calculations
886  * ESTCPUFREQ times per second.
887  */
888 static
889 void
890 dfly_recalculate_estcpu(struct lwp *lp)
891 {
892         globaldata_t gd = mycpu;
893         sysclock_t cpbase;
894         sysclock_t ttlticks;
895         int estcpu;
896         int decay_factor;
897         int ucount;
898
899         /*
900          * We have to subtract periodic to get the last schedclock
901          * timeout time, otherwise we would get the upcoming timeout.
902          * Keep in mind that a process can migrate between cpus and
903          * while the scheduler clock should be very close, boundary
904          * conditions could lead to a small negative delta.
905          */
906         cpbase = gd->gd_schedclock.time - gd->gd_schedclock.periodic;
907
908         if (lp->lwp_slptime > 1) {
909                 /*
910                  * Too much time has passed, do a coarse correction.
911                  */
912                 lp->lwp_estcpu = lp->lwp_estcpu >> 1;
913                 dfly_resetpriority(lp);
914                 lp->lwp_cpbase = cpbase;
915                 lp->lwp_cpticks = 0;
916                 lp->lwp_estfast = 0;
917         } else if (lp->lwp_cpbase != cpbase) {
918                 /*
919                  * Adjust estcpu if we are in a different tick.  Don't waste
920                  * time if we are in the same tick.
921                  *
922                  * First calculate the number of ticks in the measurement
923                  * interval.  The ttlticks calculation can wind up 0 due to
924                  * a bug in the handling of lwp_slptime  (as yet not found),
925                  * so make sure we do not get a divide by 0 panic.
926                  */
927                 ttlticks = (cpbase - lp->lwp_cpbase) /
928                            gd->gd_schedclock.periodic;
929                 if (ttlticks < 0) {
930                         ttlticks = 0;
931                         lp->lwp_cpbase = cpbase;
932                 }
933                 if (ttlticks == 0)
934                         return;
935                 updatepcpu(lp, lp->lwp_cpticks, ttlticks);
936
937                 /*
938                  * Calculate the percentage of one cpu being used then
939                  * compensate for any system load in excess of ncpus.
940                  *
941                  * For example, if we have 8 cores and 16 running cpu-bound
942                  * processes then all things being equal each process will
943                  * get 50% of one cpu.  We need to pump this value back
944                  * up to 100% so the estcpu calculation properly adjusts
945                  * the process's dynamic priority.
946                  *
947                  * estcpu is scaled by ESTCPUMAX, pctcpu is scaled by FSCALE.
948                  */
949                 estcpu = (lp->lwp_pctcpu * ESTCPUMAX) >> FSHIFT;
950                 ucount = dfly_ucount;
951                 if (ucount > ncpus) {
952                         estcpu += estcpu * (ucount - ncpus) / ncpus;
953                 }
954
955                 if (usched_dfly_debug == lp->lwp_proc->p_pid) {
956                         kprintf("pid %d lwp %p estcpu %3d %3d cp %d/%d",
957                                 lp->lwp_proc->p_pid, lp,
958                                 estcpu, lp->lwp_estcpu,
959                                 lp->lwp_cpticks, ttlticks);
960                 }
961
962                 /*
963                  * Adjust lp->lwp_esetcpu.  The decay factor determines how
964                  * quickly lwp_estcpu collapses to its realtime calculation.
965                  * A slower collapse gives us a more accurate number over
966                  * the long term but can create problems with bursty threads
967                  * or threads which become cpu hogs.
968                  *
969                  * To solve this problem, newly started lwps and lwps which
970                  * are restarting after having been asleep for a while are
971                  * given a much, much faster decay in order to quickly
972                  * detect whether they become cpu-bound.
973                  *
974                  * NOTE: p_nice is accounted for in dfly_resetpriority(),
975                  *       and not here, but we must still ensure that a
976                  *       cpu-bound nice -20 process does not completely
977                  *       override a cpu-bound nice +20 process.
978                  *
979                  * NOTE: We must use ESTCPULIM() here to deal with any
980                  *       overshoot.
981                  */
982                 decay_factor = usched_dfly_decay;
983                 if (decay_factor < 1)
984                         decay_factor = 1;
985                 if (decay_factor > 1024)
986                         decay_factor = 1024;
987
988                 if (lp->lwp_estfast < usched_dfly_decay) {
989                         ++lp->lwp_estfast;
990                         lp->lwp_estcpu = ESTCPULIM(
991                                 (lp->lwp_estcpu * lp->lwp_estfast + estcpu) /
992                                 (lp->lwp_estfast + 1));
993                 } else {
994                         lp->lwp_estcpu = ESTCPULIM(
995                                 (lp->lwp_estcpu * decay_factor + estcpu) /
996                                 (decay_factor + 1));
997                 }
998
999                 if (usched_dfly_debug == lp->lwp_proc->p_pid)
1000                         kprintf(" finalestcpu %d\n", lp->lwp_estcpu);
1001                 dfly_resetpriority(lp);
1002                 lp->lwp_cpbase += ttlticks * gd->gd_schedclock.periodic;
1003                 lp->lwp_cpticks = 0;
1004         }
1005 }
1006
1007 /*
1008  * Compute the priority of a process when running in user mode.
1009  * Arrange to reschedule if the resulting priority is better
1010  * than that of the current process.
1011  *
1012  * This routine may be called with any process.
1013  *
1014  * This routine is called by fork1() for initial setup with the process
1015  * of the run queue, and also may be called normally with the process on or
1016  * off the run queue.
1017  */
1018 static void
1019 dfly_resetpriority(struct lwp *lp)
1020 {
1021         dfly_pcpu_t rdd;
1022         int newpriority;
1023         u_short newrqtype;
1024         int rcpu;
1025         int checkpri;
1026         int estcpu;
1027         int delta_uload;
1028
1029         crit_enter();
1030
1031         /*
1032          * Lock the scheduler (lp) belongs to.  This can be on a different
1033          * cpu.  Handle races.  This loop breaks out with the appropriate
1034          * rdd locked.
1035          */
1036         for (;;) {
1037                 rcpu = lp->lwp_qcpu;
1038                 cpu_ccfence();
1039                 rdd = &dfly_pcpu[rcpu];
1040                 spin_lock(&rdd->spin);
1041                 if (rcpu == lp->lwp_qcpu)
1042                         break;
1043                 spin_unlock(&rdd->spin);
1044         }
1045
1046         /*
1047          * Calculate the new priority and queue type
1048          */
1049         newrqtype = lp->lwp_rtprio.type;
1050
1051         switch(newrqtype) {
1052         case RTP_PRIO_REALTIME:
1053         case RTP_PRIO_FIFO:
1054                 newpriority = PRIBASE_REALTIME +
1055                              (lp->lwp_rtprio.prio & PRIMASK);
1056                 break;
1057         case RTP_PRIO_NORMAL:
1058                 /*
1059                  *
1060                  */
1061                 estcpu = lp->lwp_estcpu;
1062
1063                 /*
1064                  * p_nice piece         Adds (0-40) * 2         0-80
1065                  * estcpu               Adds 16384  * 4 / 512   0-128
1066                  */
1067                 newpriority = (lp->lwp_proc->p_nice - PRIO_MIN) * PPQ / NICEPPQ;
1068                 newpriority += estcpu * PPQ / ESTCPUPPQ;
1069                 newpriority = newpriority * MAXPRI / (PRIO_RANGE * PPQ /
1070                               NICEPPQ + ESTCPUMAX * PPQ / ESTCPUPPQ);
1071                 newpriority = PRIBASE_NORMAL + (newpriority & PRIMASK);
1072                 break;
1073         case RTP_PRIO_IDLE:
1074                 newpriority = PRIBASE_IDLE + (lp->lwp_rtprio.prio & PRIMASK);
1075                 break;
1076         case RTP_PRIO_THREAD:
1077                 newpriority = PRIBASE_THREAD + (lp->lwp_rtprio.prio & PRIMASK);
1078                 break;
1079         default:
1080                 panic("Bad RTP_PRIO %d", newrqtype);
1081                 /* NOT REACHED */
1082         }
1083
1084         /*
1085          * The LWKT scheduler doesn't dive usched structures, give it a hint
1086          * on the relative priority of user threads running in the kernel.
1087          * The LWKT scheduler will always ensure that a user thread running
1088          * in the kernel will get cpu some time, regardless of its upri,
1089          * but can decide not to instantly switch from one kernel or user
1090          * mode user thread to a kernel-mode user thread when it has a less
1091          * desireable user priority.
1092          *
1093          * td_upri has normal sense (higher values are more desireable), so
1094          * negate it.
1095          */
1096         lp->lwp_thread->td_upri = -(newpriority & usched_dfly_swmask);
1097
1098         /*
1099          * The newpriority incorporates the queue type so do a simple masked
1100          * check to determine if the process has moved to another queue.  If
1101          * it has, and it is currently on a run queue, then move it.
1102          *
1103          * Since uload is ~PPQMASK masked, no modifications are necessary if
1104          * we end up in the same run queue.
1105          */
1106         if ((lp->lwp_priority ^ newpriority) & ~PPQMASK) {
1107                 if (lp->lwp_mpflags & LWP_MP_ONRUNQ) {
1108                         dfly_remrunqueue_locked(rdd, lp);
1109                         lp->lwp_priority = newpriority;
1110                         lp->lwp_rqtype = newrqtype;
1111                         lp->lwp_rqindex = (newpriority & PRIMASK) / PPQ;
1112                         dfly_setrunqueue_locked(rdd, lp);
1113                         checkpri = 1;
1114                 } else {
1115                         lp->lwp_priority = newpriority;
1116                         lp->lwp_rqtype = newrqtype;
1117                         lp->lwp_rqindex = (newpriority & PRIMASK) / PPQ;
1118                         checkpri = 0;
1119                 }
1120         } else {
1121                 /*
1122                  * In the same PPQ, uload cannot change.
1123                  */
1124                 lp->lwp_priority = newpriority;
1125                 checkpri = 1;
1126                 rcpu = -1;
1127         }
1128
1129         /*
1130          * Adjust effective load.
1131          *
1132          * Calculate load then scale up or down geometrically based on p_nice.
1133          * Processes niced up (positive) are less important, and processes
1134          * niced downard (negative) are more important.  The higher the uload,
1135          * the more important the thread.
1136          */
1137         /* 0-511, 0-100% cpu */
1138         delta_uload = lp->lwp_estcpu / NQS;
1139         delta_uload -= delta_uload * lp->lwp_proc->p_nice / (PRIO_MAX + 1);
1140
1141
1142         delta_uload -= lp->lwp_uload;
1143         lp->lwp_uload += delta_uload;
1144         if (lp->lwp_mpflags & LWP_MP_ULOAD)
1145                 atomic_add_int(&dfly_pcpu[lp->lwp_qcpu].uload, delta_uload);
1146
1147         /*
1148          * Determine if we need to reschedule the target cpu.  This only
1149          * occurs if the LWP is already on a scheduler queue, which means
1150          * that idle cpu notification has already occured.  At most we
1151          * need only issue a need_user_resched() on the appropriate cpu.
1152          *
1153          * The LWP may be owned by a CPU different from the current one,
1154          * in which case dd->uschedcp may be modified without an MP lock
1155          * or a spinlock held.  The worst that happens is that the code
1156          * below causes a spurious need_user_resched() on the target CPU
1157          * and dd->pri to be wrong for a short period of time, both of
1158          * which are harmless.
1159          *
1160          * If checkpri is 0 we are adjusting the priority of the current
1161          * process, possibly higher (less desireable), so ignore the upri
1162          * check which will fail in that case.
1163          */
1164         if (rcpu >= 0) {
1165                 if ((dfly_rdyprocmask & CPUMASK(rcpu)) &&
1166                     (checkpri == 0 ||
1167                      (rdd->upri & ~PRIMASK) >
1168                      (lp->lwp_priority & ~PRIMASK))) {
1169 #ifdef SMP
1170                         if (rcpu == mycpu->gd_cpuid) {
1171                                 spin_unlock(&rdd->spin);
1172                                 need_user_resched();
1173                         } else {
1174                                 spin_unlock(&rdd->spin);
1175                                 lwkt_send_ipiq(globaldata_find(rcpu),
1176                                                dfly_need_user_resched_remote,
1177                                                NULL);
1178                         }
1179 #else
1180                         spin_unlock(&rdd->spin);
1181                         need_user_resched();
1182 #endif
1183                 } else {
1184                         spin_unlock(&rdd->spin);
1185                 }
1186         } else {
1187                 spin_unlock(&rdd->spin);
1188         }
1189         crit_exit();
1190 }
1191
1192 static
1193 void
1194 dfly_yield(struct lwp *lp)
1195 {
1196 #if 0
1197         /* FUTURE (or something similar) */
1198         switch(lp->lwp_rqtype) {
1199         case RTP_PRIO_NORMAL:
1200                 lp->lwp_estcpu = ESTCPULIM(lp->lwp_estcpu + ESTCPUINCR);
1201                 break;
1202         default:
1203                 break;
1204         }
1205 #endif
1206         need_user_resched();
1207 }
1208
1209 /*
1210  * Called from fork1() when a new child process is being created.
1211  *
1212  * Give the child process an initial estcpu that is more batch then
1213  * its parent and dock the parent for the fork (but do not
1214  * reschedule the parent).
1215  *
1216  * fast
1217  *
1218  * XXX lwp should be "spawning" instead of "forking"
1219  */
1220 static void
1221 dfly_forking(struct lwp *plp, struct lwp *lp)
1222 {
1223         /*
1224          * Put the child 4 queue slots (out of 32) higher than the parent
1225          * (less desireable than the parent).
1226          */
1227         lp->lwp_estcpu = ESTCPULIM(plp->lwp_estcpu + ESTCPUPPQ * 4);
1228         lp->lwp_forked = 1;
1229         lp->lwp_estfast = 0;
1230
1231         /*
1232          * Dock the parent a cost for the fork, protecting us from fork
1233          * bombs.  If the parent is forking quickly make the child more
1234          * batchy.
1235          */
1236         plp->lwp_estcpu = ESTCPULIM(plp->lwp_estcpu + ESTCPUPPQ / 16);
1237 }
1238
1239 /*
1240  * Called when a lwp is being removed from this scheduler, typically
1241  * during lwp_exit().  We have to clean out any ULOAD accounting before
1242  * we can let the lp go.  The dd->spin lock is not needed for uload
1243  * updates.
1244  *
1245  * Scheduler dequeueing has already occurred, no further action in that
1246  * regard is needed.
1247  */
1248 static void
1249 dfly_exiting(struct lwp *lp, struct proc *child_proc)
1250 {
1251         dfly_pcpu_t dd = &dfly_pcpu[lp->lwp_qcpu];
1252
1253         if (lp->lwp_mpflags & LWP_MP_ULOAD) {
1254                 atomic_clear_int(&lp->lwp_mpflags, LWP_MP_ULOAD);
1255                 atomic_add_int(&dd->uload, -lp->lwp_uload);
1256                 atomic_add_int(&dd->ucount, -1);
1257                 atomic_add_int(&dfly_ucount, -1);
1258         }
1259 }
1260
1261 /*
1262  * This function cannot block in any way, but spinlocks are ok.
1263  *
1264  * Update the uload based on the state of the thread (whether it is going
1265  * to sleep or running again).  The uload is meant to be a longer-term
1266  * load and not an instantanious load.
1267  */
1268 static void
1269 dfly_uload_update(struct lwp *lp)
1270 {
1271         dfly_pcpu_t dd = &dfly_pcpu[lp->lwp_qcpu];
1272
1273         if (lp->lwp_thread->td_flags & TDF_RUNQ) {
1274                 if ((lp->lwp_mpflags & LWP_MP_ULOAD) == 0) {
1275                         spin_lock(&dd->spin);
1276                         if ((lp->lwp_mpflags & LWP_MP_ULOAD) == 0) {
1277                                 atomic_set_int(&lp->lwp_mpflags,
1278                                                LWP_MP_ULOAD);
1279                                 atomic_add_int(&dd->uload, lp->lwp_uload);
1280                                 atomic_add_int(&dd->ucount, 1);
1281                                 atomic_add_int(&dfly_ucount, 1);
1282                         }
1283                         spin_unlock(&dd->spin);
1284                 }
1285         } else if (lp->lwp_slptime > 0) {
1286                 if (lp->lwp_mpflags & LWP_MP_ULOAD) {
1287                         spin_lock(&dd->spin);
1288                         if (lp->lwp_mpflags & LWP_MP_ULOAD) {
1289                                 atomic_clear_int(&lp->lwp_mpflags,
1290                                                  LWP_MP_ULOAD);
1291                                 atomic_add_int(&dd->uload, -lp->lwp_uload);
1292                                 atomic_add_int(&dd->ucount, -1);
1293                                 atomic_add_int(&dfly_ucount, -1);
1294                         }
1295                         spin_unlock(&dd->spin);
1296                 }
1297         }
1298 }
1299
1300 /*
1301  * chooseproc() is called when a cpu needs a user process to LWKT schedule,
1302  * it selects a user process and returns it.  If chklp is non-NULL and chklp
1303  * has a better or equal priority then the process that would otherwise be
1304  * chosen, NULL is returned.
1305  *
1306  * Until we fix the RUNQ code the chklp test has to be strict or we may
1307  * bounce between processes trying to acquire the current process designation.
1308  *
1309  * Must be called with rdd->spin locked.  The spinlock is left intact through
1310  * the entire routine.  dd->spin does not have to be locked.
1311  *
1312  * If worst is non-zero this function finds the worst thread instead of the
1313  * best thread (used by the schedulerclock-based rover).
1314  */
1315 static
1316 struct lwp *
1317 dfly_chooseproc_locked(dfly_pcpu_t rdd, dfly_pcpu_t dd,
1318                        struct lwp *chklp, int worst)
1319 {
1320         struct lwp *lp;
1321         struct rq *q;
1322         u_int32_t *which, *which2;
1323         u_int32_t pri;
1324         u_int32_t rtqbits;
1325         u_int32_t tsqbits;
1326         u_int32_t idqbits;
1327
1328         rtqbits = rdd->rtqueuebits;
1329         tsqbits = rdd->queuebits;
1330         idqbits = rdd->idqueuebits;
1331
1332         if (worst) {
1333                 if (idqbits) {
1334                         pri = bsrl(idqbits);
1335                         q = &rdd->idqueues[pri];
1336                         which = &rdd->idqueuebits;
1337                         which2 = &idqbits;
1338                 } else if (tsqbits) {
1339                         pri = bsrl(tsqbits);
1340                         q = &rdd->queues[pri];
1341                         which = &rdd->queuebits;
1342                         which2 = &tsqbits;
1343                 } else if (rtqbits) {
1344                         pri = bsrl(rtqbits);
1345                         q = &rdd->rtqueues[pri];
1346                         which = &rdd->rtqueuebits;
1347                         which2 = &rtqbits;
1348                 } else {
1349                         return (NULL);
1350                 }
1351                 lp = TAILQ_LAST(q, rq);
1352         } else {
1353                 if (rtqbits) {
1354                         pri = bsfl(rtqbits);
1355                         q = &rdd->rtqueues[pri];
1356                         which = &rdd->rtqueuebits;
1357                         which2 = &rtqbits;
1358                 } else if (tsqbits) {
1359                         pri = bsfl(tsqbits);
1360                         q = &rdd->queues[pri];
1361                         which = &rdd->queuebits;
1362                         which2 = &tsqbits;
1363                 } else if (idqbits) {
1364                         pri = bsfl(idqbits);
1365                         q = &rdd->idqueues[pri];
1366                         which = &rdd->idqueuebits;
1367                         which2 = &idqbits;
1368                 } else {
1369                         return (NULL);
1370                 }
1371                 lp = TAILQ_FIRST(q);
1372         }
1373         KASSERT(lp, ("chooseproc: no lwp on busy queue"));
1374
1375         /*
1376          * If the passed lwp <chklp> is reasonably close to the selected
1377          * lwp <lp>, return NULL (indicating that <chklp> should be kept).
1378          *
1379          * Note that we must error on the side of <chklp> to avoid bouncing
1380          * between threads in the acquire code.
1381          */
1382         if (chklp) {
1383                 if (chklp->lwp_priority < lp->lwp_priority + PPQ)
1384                         return(NULL);
1385         }
1386
1387         KTR_COND_LOG(usched_chooseproc,
1388             lp->lwp_proc->p_pid == usched_dfly_pid_debug,
1389             lp->lwp_proc->p_pid,
1390             lp->lwp_thread->td_gd->gd_cpuid,
1391             mycpu->gd_cpuid);
1392
1393         KASSERT((lp->lwp_mpflags & LWP_MP_ONRUNQ) != 0, ("not on runq6!"));
1394         atomic_clear_int(&lp->lwp_mpflags, LWP_MP_ONRUNQ);
1395         TAILQ_REMOVE(q, lp, lwp_procq);
1396         --rdd->runqcount;
1397         if (TAILQ_EMPTY(q))
1398                 *which &= ~(1 << pri);
1399
1400         /*
1401          * If we are choosing a process from rdd with the intent to
1402          * move it to dd, lwp_qcpu must be adjusted while rdd's spinlock
1403          * is still held.
1404          */
1405         if (rdd != dd) {
1406                 if (lp->lwp_mpflags & LWP_MP_ULOAD) {
1407                         atomic_add_int(&rdd->uload, -lp->lwp_uload);
1408                         atomic_add_int(&rdd->ucount, -1);
1409                         atomic_add_int(&dfly_ucount, -1);
1410                 }
1411                 lp->lwp_qcpu = dd->cpuid;
1412                 atomic_add_int(&dd->uload, lp->lwp_uload);
1413                 atomic_add_int(&dd->ucount, 1);
1414                 atomic_add_int(&dfly_ucount, 1);
1415                 atomic_set_int(&lp->lwp_mpflags, LWP_MP_ULOAD);
1416         }
1417         return lp;
1418 }
1419
1420 #ifdef SMP
1421
1422 /*
1423  * USED TO PUSH RUNNABLE LWPS TO THE LEAST LOADED CPU.
1424  *
1425  * Choose a cpu node to schedule lp on, hopefully nearby its current
1426  * node.
1427  *
1428  * We give the current node a modest advantage for obvious reasons.
1429  *
1430  * We also give the node the thread was woken up FROM a slight advantage
1431  * in order to try to schedule paired threads which synchronize/block waiting
1432  * for each other fairly close to each other.  Similarly in a network setting
1433  * this feature will also attempt to place a user process near the kernel
1434  * protocol thread that is feeding it data.  THIS IS A CRITICAL PART of the
1435  * algorithm as it heuristically groups synchronizing processes for locality
1436  * of reference in multi-socket systems.
1437  *
1438  * We check against running processes and give a big advantage if there
1439  * are none running.
1440  *
1441  * The caller will normally dfly_setrunqueue() lp on the returned queue.
1442  *
1443  * When the topology is known choose a cpu whos group has, in aggregate,
1444  * has the lowest weighted load.
1445  */
1446 static
1447 dfly_pcpu_t
1448 dfly_choose_best_queue(struct lwp *lp)
1449 {
1450         cpumask_t wakemask;
1451         cpumask_t mask;
1452         cpu_node_t *cpup;
1453         cpu_node_t *cpun;
1454         cpu_node_t *cpub;
1455         dfly_pcpu_t dd = &dfly_pcpu[lp->lwp_qcpu];
1456         dfly_pcpu_t rdd;
1457         int wakecpu;
1458         int cpuid;
1459         int n;
1460         int count;
1461         int load;
1462         int lowest_load;
1463
1464         /*
1465          * When the topology is unknown choose a random cpu that is hopefully
1466          * idle.
1467          */
1468         if (dd->cpunode == NULL)
1469                 return (dfly_choose_queue_simple(dd, lp));
1470
1471         /*
1472          * Pairing mask
1473          */
1474         if ((wakecpu = lp->lwp_thread->td_wakefromcpu) >= 0)
1475                 wakemask = dfly_pcpu[wakecpu].cpumask;
1476         else
1477                 wakemask = 0;
1478
1479         /*
1480          * When the topology is known choose a cpu whos group has, in
1481          * aggregate, has the lowest weighted load.
1482          */
1483         cpup = root_cpu_node;
1484         rdd = dd;
1485
1486         while (cpup) {
1487                 /*
1488                  * Degenerate case super-root
1489                  */
1490                 if (cpup->child_node && cpup->child_no == 1) {
1491                         cpup = cpup->child_node;
1492                         continue;
1493                 }
1494
1495                 /*
1496                  * Terminal cpunode
1497                  */
1498                 if (cpup->child_node == NULL) {
1499                         rdd = &dfly_pcpu[BSFCPUMASK(cpup->members)];
1500                         break;
1501                 }
1502
1503                 cpub = NULL;
1504                 lowest_load = 0x7FFFFFFF;
1505
1506                 for (n = 0; n < cpup->child_no; ++n) {
1507                         /*
1508                          * Accumulate load information for all cpus
1509                          * which are members of this node.
1510                          */
1511                         cpun = &cpup->child_node[n];
1512                         mask = cpun->members & usched_global_cpumask &
1513                                smp_active_mask & lp->lwp_cpumask;
1514                         if (mask == 0)
1515                                 continue;
1516
1517                         count = 0;
1518                         load = 0;
1519
1520                         while (mask) {
1521                                 cpuid = BSFCPUMASK(mask);
1522                                 rdd = &dfly_pcpu[cpuid];
1523                                 load += rdd->uload;
1524                                 load += rdd->ucount * usched_dfly_weight3;
1525
1526                                 if (rdd->uschedcp == NULL &&
1527                                     rdd->runqcount == 0 &&
1528                                     globaldata_find(cpuid)->gd_tdrunqcount == 0
1529                                 ) {
1530                                         load -= usched_dfly_weight4;
1531                                 }
1532 #if 0
1533                                 else if (rdd->upri > lp->lwp_priority + PPQ) {
1534                                         load -= usched_dfly_weight4 / 2;
1535                                 }
1536 #endif
1537                                 mask &= ~CPUMASK(cpuid);
1538                                 ++count;
1539                         }
1540
1541                         /*
1542                          * Compensate if the lp is already accounted for in
1543                          * the aggregate uload for this mask set.  We want
1544                          * to calculate the loads as if lp were not present,
1545                          * otherwise the calculation is bogus.
1546                          */
1547                         if ((lp->lwp_mpflags & LWP_MP_ULOAD) &&
1548                             (dd->cpumask & cpun->members)) {
1549                                 load -= lp->lwp_uload;
1550                                 load -= usched_dfly_weight3;
1551                         }
1552
1553                         load /= count;
1554
1555                         /*
1556                          * Advantage the cpu group (lp) is already on.
1557                          */
1558                         if (cpun->members & dd->cpumask)
1559                                 load -= usched_dfly_weight1;
1560
1561                         /*
1562                          * Advantage the cpu group we want to pair (lp) to,
1563                          * but don't let it go to the exact same cpu as
1564                          * the wakecpu target.
1565                          *
1566                          * We do this by checking whether cpun is a
1567                          * terminal node or not.  All cpun's at the same
1568                          * level will either all be terminal or all not
1569                          * terminal.
1570                          *
1571                          * If it is and we match we disadvantage the load.
1572                          * If it is and we don't match we advantage the load.
1573                          *
1574                          * Also note that we are effectively disadvantaging
1575                          * all-but-one by the same amount, so it won't effect
1576                          * the weight1 factor for the all-but-one nodes.
1577                          */
1578                         if (cpun->members & wakemask) {
1579                                 if (cpun->child_node != NULL) {
1580                                         /* advantage */
1581                                         load -= usched_dfly_weight2;
1582                                 } else {
1583                                         if (usched_dfly_features & 0x10)
1584                                                 load += usched_dfly_weight2;
1585                                         else
1586                                                 load -= usched_dfly_weight2;
1587                                 }
1588                         }
1589
1590                         /*
1591                          * Calculate the best load
1592                          */
1593                         if (cpub == NULL || lowest_load > load ||
1594                             (lowest_load == load &&
1595                              (cpun->members & dd->cpumask))
1596                         ) {
1597                                 lowest_load = load;
1598                                 cpub = cpun;
1599                         }
1600                 }
1601                 cpup = cpub;
1602         }
1603         if (usched_dfly_chooser)
1604                 kprintf("lp %02d->%02d %s\n",
1605                         lp->lwp_qcpu, rdd->cpuid, lp->lwp_proc->p_comm);
1606         return (rdd);
1607 }
1608
1609 /*
1610  * USED TO PULL RUNNABLE LWPS FROM THE MOST LOADED CPU.
1611  *
1612  * Choose the worst queue close to dd's cpu node with a non-empty runq
1613  * that is NOT dd.  Also require that the moving of the highest-load thread
1614  * from rdd to dd does not cause the uload's to cross each other.
1615  *
1616  * This is used by the thread chooser when the current cpu's queues are
1617  * empty to steal a thread from another cpu's queue.  We want to offload
1618  * the most heavily-loaded queue.
1619  */
1620 static
1621 dfly_pcpu_t
1622 dfly_choose_worst_queue(dfly_pcpu_t dd)
1623 {
1624         cpumask_t mask;
1625         cpu_node_t *cpup;
1626         cpu_node_t *cpun;
1627         cpu_node_t *cpub;
1628         dfly_pcpu_t rdd;
1629         int cpuid;
1630         int n;
1631         int count;
1632         int load;
1633 #if 0
1634         int pri;
1635         int hpri;
1636 #endif
1637         int highest_load;
1638
1639         /*
1640          * When the topology is unknown choose a random cpu that is hopefully
1641          * idle.
1642          */
1643         if (dd->cpunode == NULL) {
1644                 return (NULL);
1645         }
1646
1647         /*
1648          * When the topology is known choose a cpu whos group has, in
1649          * aggregate, has the lowest weighted load.
1650          */
1651         cpup = root_cpu_node;
1652         rdd = dd;
1653         while (cpup) {
1654                 /*
1655                  * Degenerate case super-root
1656                  */
1657                 if (cpup->child_node && cpup->child_no == 1) {
1658                         cpup = cpup->child_node;
1659                         continue;
1660                 }
1661
1662                 /*
1663                  * Terminal cpunode
1664                  */
1665                 if (cpup->child_node == NULL) {
1666                         rdd = &dfly_pcpu[BSFCPUMASK(cpup->members)];
1667                         break;
1668                 }
1669
1670                 cpub = NULL;
1671                 highest_load = 0;
1672
1673                 for (n = 0; n < cpup->child_no; ++n) {
1674                         /*
1675                          * Accumulate load information for all cpus
1676                          * which are members of this node.
1677                          */
1678                         cpun = &cpup->child_node[n];
1679                         mask = cpun->members & usched_global_cpumask &
1680                                smp_active_mask;
1681                         if (mask == 0)
1682                                 continue;
1683                         count = 0;
1684                         load = 0;
1685
1686                         while (mask) {
1687                                 cpuid = BSFCPUMASK(mask);
1688                                 rdd = &dfly_pcpu[cpuid];
1689                                 load += rdd->uload;
1690                                 load += rdd->ucount * usched_dfly_weight3;
1691                                 if (rdd->uschedcp == NULL &&
1692                                     rdd->runqcount == 0 &&
1693                                     globaldata_find(cpuid)->gd_tdrunqcount == 0
1694                                 ) {
1695                                         load -= usched_dfly_weight4;
1696                                 }
1697 #if 0
1698                                 else if (rdd->upri > dd->upri + PPQ) {
1699                                         load -= usched_dfly_weight4 / 2;
1700                                 }
1701 #endif
1702                                 mask &= ~CPUMASK(cpuid);
1703                                 ++count;
1704                         }
1705                         load /= count;
1706
1707                         /*
1708                          * Prefer candidates which are somewhat closer to
1709                          * our cpu.
1710                          */
1711                         if (dd->cpumask & cpun->members)
1712                                 load += usched_dfly_weight1;
1713
1714                         /*
1715                          * The best candidate is the one with the worst
1716                          * (highest) load.
1717                          */
1718                         if (cpub == NULL || highest_load < load) {
1719                                 highest_load = load;
1720                                 cpub = cpun;
1721                         }
1722                 }
1723                 cpup = cpub;
1724         }
1725
1726         /*
1727          * We never return our own node (dd), and only return a remote
1728          * node if it's load is significantly worse than ours (i.e. where
1729          * stealing a thread would be considered reasonable).
1730          *
1731          * This also helps us avoid breaking paired threads apart which
1732          * can have disastrous effects on performance.
1733          */
1734         if (rdd == dd)
1735                 return(NULL);
1736
1737 #if 0
1738         hpri = 0;
1739         if (rdd->rtqueuebits && hpri < (pri = bsrl(rdd->rtqueuebits)))
1740                 hpri = pri;
1741         if (rdd->queuebits && hpri < (pri = bsrl(rdd->queuebits)))
1742                 hpri = pri;
1743         if (rdd->idqueuebits && hpri < (pri = bsrl(rdd->idqueuebits)))
1744                 hpri = pri;
1745         hpri *= PPQ;
1746         if (rdd->uload - hpri < dd->uload + hpri)
1747                 return(NULL);
1748 #endif
1749         return (rdd);
1750 }
1751
1752 static
1753 dfly_pcpu_t
1754 dfly_choose_queue_simple(dfly_pcpu_t dd, struct lwp *lp)
1755 {
1756         dfly_pcpu_t rdd;
1757         cpumask_t tmpmask;
1758         cpumask_t mask;
1759         int cpuid;
1760
1761         /*
1762          * Fallback to the original heuristic, select random cpu,
1763          * first checking cpus not currently running a user thread.
1764          */
1765         ++dfly_scancpu;
1766         cpuid = (dfly_scancpu & 0xFFFF) % ncpus;
1767         mask = ~dfly_curprocmask & dfly_rdyprocmask & lp->lwp_cpumask &
1768                smp_active_mask & usched_global_cpumask;
1769
1770         while (mask) {
1771                 tmpmask = ~(CPUMASK(cpuid) - 1);
1772                 if (mask & tmpmask)
1773                         cpuid = BSFCPUMASK(mask & tmpmask);
1774                 else
1775                         cpuid = BSFCPUMASK(mask);
1776                 rdd = &dfly_pcpu[cpuid];
1777
1778                 if ((rdd->upri & ~PPQMASK) >= (lp->lwp_priority & ~PPQMASK))
1779                         goto found;
1780                 mask &= ~CPUMASK(cpuid);
1781         }
1782
1783         /*
1784          * Then cpus which might have a currently running lp
1785          */
1786         cpuid = (dfly_scancpu & 0xFFFF) % ncpus;
1787         mask = dfly_curprocmask & dfly_rdyprocmask &
1788                lp->lwp_cpumask & smp_active_mask & usched_global_cpumask;
1789
1790         while (mask) {
1791                 tmpmask = ~(CPUMASK(cpuid) - 1);
1792                 if (mask & tmpmask)
1793                         cpuid = BSFCPUMASK(mask & tmpmask);
1794                 else
1795                         cpuid = BSFCPUMASK(mask);
1796                 rdd = &dfly_pcpu[cpuid];
1797
1798                 if ((rdd->upri & ~PPQMASK) > (lp->lwp_priority & ~PPQMASK))
1799                         goto found;
1800                 mask &= ~CPUMASK(cpuid);
1801         }
1802
1803         /*
1804          * If we cannot find a suitable cpu we reload from dfly_scancpu
1805          * and round-robin.  Other cpus will pickup as they release their
1806          * current lwps or become ready.
1807          *
1808          * Avoid a degenerate system lockup case if usched_global_cpumask
1809          * is set to 0 or otherwise does not cover lwp_cpumask.
1810          *
1811          * We only kick the target helper thread in this case, we do not
1812          * set the user resched flag because
1813          */
1814         cpuid = (dfly_scancpu & 0xFFFF) % ncpus;
1815         if ((CPUMASK(cpuid) & usched_global_cpumask) == 0)
1816                 cpuid = 0;
1817         rdd = &dfly_pcpu[cpuid];
1818 found:
1819         return (rdd);
1820 }
1821
1822 static
1823 void
1824 dfly_need_user_resched_remote(void *dummy)
1825 {
1826         globaldata_t gd = mycpu;
1827         dfly_pcpu_t  dd = &dfly_pcpu[gd->gd_cpuid];
1828
1829         /*
1830          * Flag reschedule needed
1831          */
1832         need_user_resched();
1833
1834         /*
1835          * If no user thread is currently running we need to kick the helper
1836          * on our cpu to recover.  Otherwise the cpu will never schedule
1837          * anything again.
1838          *
1839          * We cannot schedule the process ourselves because this is an
1840          * IPI callback and we cannot acquire spinlocks in an IPI callback.
1841          *
1842          * Call wakeup_mycpu to avoid sending IPIs to other CPUs
1843          */
1844         if (dd->uschedcp == NULL && (dfly_rdyprocmask & gd->gd_cpumask)) {
1845                 atomic_clear_cpumask(&dfly_rdyprocmask, gd->gd_cpumask);
1846                 wakeup_mycpu(&dd->helper_thread);
1847         }
1848 }
1849
1850 #endif
1851
1852 /*
1853  * dfly_remrunqueue_locked() removes a given process from the run queue
1854  * that it is on, clearing the queue busy bit if it becomes empty.
1855  *
1856  * Note that user process scheduler is different from the LWKT schedule.
1857  * The user process scheduler only manages user processes but it uses LWKT
1858  * underneath, and a user process operating in the kernel will often be
1859  * 'released' from our management.
1860  *
1861  * uload is NOT adjusted here.  It is only adjusted if the lwkt_thread goes
1862  * to sleep or the lwp is moved to a different runq.
1863  */
1864 static void
1865 dfly_remrunqueue_locked(dfly_pcpu_t rdd, struct lwp *lp)
1866 {
1867         struct rq *q;
1868         u_int32_t *which;
1869         u_int8_t pri;
1870
1871         KKASSERT(rdd->runqcount >= 0);
1872
1873         pri = lp->lwp_rqindex;
1874
1875         switch(lp->lwp_rqtype) {
1876         case RTP_PRIO_NORMAL:
1877                 q = &rdd->queues[pri];
1878                 which = &rdd->queuebits;
1879                 break;
1880         case RTP_PRIO_REALTIME:
1881         case RTP_PRIO_FIFO:
1882                 q = &rdd->rtqueues[pri];
1883                 which = &rdd->rtqueuebits;
1884                 break;
1885         case RTP_PRIO_IDLE:
1886                 q = &rdd->idqueues[pri];
1887                 which = &rdd->idqueuebits;
1888                 break;
1889         default:
1890                 panic("remrunqueue: invalid rtprio type");
1891                 /* NOT REACHED */
1892         }
1893         KKASSERT(lp->lwp_mpflags & LWP_MP_ONRUNQ);
1894         atomic_clear_int(&lp->lwp_mpflags, LWP_MP_ONRUNQ);
1895         TAILQ_REMOVE(q, lp, lwp_procq);
1896         --rdd->runqcount;
1897         if (TAILQ_EMPTY(q)) {
1898                 KASSERT((*which & (1 << pri)) != 0,
1899                         ("remrunqueue: remove from empty queue"));
1900                 *which &= ~(1 << pri);
1901         }
1902 }
1903
1904 /*
1905  * dfly_setrunqueue_locked()
1906  *
1907  * Add a process whos rqtype and rqindex had previously been calculated
1908  * onto the appropriate run queue.   Determine if the addition requires
1909  * a reschedule on a cpu and return the cpuid or -1.
1910  *
1911  * NOTE:          Lower priorities are better priorities.
1912  *
1913  * NOTE ON ULOAD: This variable specifies the aggregate load on a cpu, the
1914  *                sum of the rough lwp_priority for all running and runnable
1915  *                processes.  Lower priority processes (higher lwp_priority
1916  *                values) actually DO count as more load, not less, because
1917  *                these are the programs which require the most care with
1918  *                regards to cpu selection.
1919  */
1920 static void
1921 dfly_setrunqueue_locked(dfly_pcpu_t rdd, struct lwp *lp)
1922 {
1923         struct rq *q;
1924         u_int32_t *which;
1925         int pri;
1926
1927         KKASSERT(lp->lwp_qcpu == rdd->cpuid);
1928
1929         if ((lp->lwp_mpflags & LWP_MP_ULOAD) == 0) {
1930                 atomic_set_int(&lp->lwp_mpflags, LWP_MP_ULOAD);
1931                 atomic_add_int(&dfly_pcpu[lp->lwp_qcpu].uload, lp->lwp_uload);
1932                 atomic_add_int(&dfly_pcpu[lp->lwp_qcpu].ucount, 1);
1933                 atomic_add_int(&dfly_ucount, 1);
1934         }
1935
1936         pri = lp->lwp_rqindex;
1937
1938         switch(lp->lwp_rqtype) {
1939         case RTP_PRIO_NORMAL:
1940                 q = &rdd->queues[pri];
1941                 which = &rdd->queuebits;
1942                 break;
1943         case RTP_PRIO_REALTIME:
1944         case RTP_PRIO_FIFO:
1945                 q = &rdd->rtqueues[pri];
1946                 which = &rdd->rtqueuebits;
1947                 break;
1948         case RTP_PRIO_IDLE:
1949                 q = &rdd->idqueues[pri];
1950                 which = &rdd->idqueuebits;
1951                 break;
1952         default:
1953                 panic("remrunqueue: invalid rtprio type");
1954                 /* NOT REACHED */
1955         }
1956
1957         /*
1958          * Place us on the selected queue.  Determine if we should be
1959          * placed at the head of the queue or at the end.
1960          *
1961          * We are placed at the tail if our round-robin count has expired,
1962          * or is about to expire and the system thinks its a good place to
1963          * round-robin, or there is already a next thread on the queue
1964          * (it might be trying to pick up where it left off and we don't
1965          * want to interfere).
1966          */
1967         KKASSERT((lp->lwp_mpflags & LWP_MP_ONRUNQ) == 0);
1968         atomic_set_int(&lp->lwp_mpflags, LWP_MP_ONRUNQ);
1969         ++rdd->runqcount;
1970
1971         if (lp->lwp_rrcount >= usched_dfly_rrinterval ||
1972             (lp->lwp_rrcount >= usched_dfly_rrinterval / 2 &&
1973              (lp->lwp_thread->td_mpflags & TDF_MP_BATCH_DEMARC)) ||
1974             !TAILQ_EMPTY(q)
1975         ) {
1976                 atomic_clear_int(&lp->lwp_thread->td_mpflags,
1977                                  TDF_MP_BATCH_DEMARC);
1978                 lp->lwp_rrcount = 0;
1979                 TAILQ_INSERT_TAIL(q, lp, lwp_procq);
1980         } else {
1981                 if (TAILQ_EMPTY(q))
1982                         lp->lwp_rrcount = 0;
1983                 TAILQ_INSERT_HEAD(q, lp, lwp_procq);
1984         }
1985         *which |= 1 << pri;
1986 }
1987
1988 #ifdef SMP
1989
1990 /*
1991  * For SMP systems a user scheduler helper thread is created for each
1992  * cpu and is used to allow one cpu to wakeup another for the purposes of
1993  * scheduling userland threads from setrunqueue().
1994  *
1995  * UP systems do not need the helper since there is only one cpu.
1996  *
1997  * We can't use the idle thread for this because we might block.
1998  * Additionally, doing things this way allows us to HLT idle cpus
1999  * on MP systems.
2000  */
2001 static void
2002 dfly_helper_thread(void *dummy)
2003 {
2004     globaldata_t gd;
2005     dfly_pcpu_t dd;
2006     dfly_pcpu_t rdd;
2007     struct lwp *nlp;
2008     cpumask_t mask;
2009     int cpuid;
2010
2011     gd = mycpu;
2012     cpuid = gd->gd_cpuid;       /* doesn't change */
2013     mask = gd->gd_cpumask;      /* doesn't change */
2014     dd = &dfly_pcpu[cpuid];
2015
2016     /*
2017      * Since we only want to be woken up only when no user processes
2018      * are scheduled on a cpu, run at an ultra low priority.
2019      */
2020     lwkt_setpri_self(TDPRI_USER_SCHEDULER);
2021
2022     tsleep(&dd->helper_thread, 0, "schslp", 0);
2023
2024     for (;;) {
2025         /*
2026          * We use the LWKT deschedule-interlock trick to avoid racing
2027          * dfly_rdyprocmask.  This means we cannot block through to the
2028          * manual lwkt_switch() call we make below.
2029          */
2030         crit_enter_gd(gd);
2031         tsleep_interlock(&dd->helper_thread, 0);
2032
2033         spin_lock(&dd->spin);
2034
2035         atomic_set_cpumask(&dfly_rdyprocmask, mask);
2036         clear_user_resched();   /* This satisfied the reschedule request */
2037 #if 0
2038         dd->rrcount = 0;        /* Reset the round-robin counter */
2039 #endif
2040
2041         if (dd->runqcount || dd->uschedcp != NULL) {
2042                 /*
2043                  * Threads are available.  A thread may or may not be
2044                  * currently scheduled.  Get the best thread already queued
2045                  * to this cpu.
2046                  */
2047                 nlp = dfly_chooseproc_locked(dd, dd, dd->uschedcp, 0);
2048                 if (nlp) {
2049                         atomic_set_cpumask(&dfly_curprocmask, mask);
2050                         dd->upri = nlp->lwp_priority;
2051                         dd->uschedcp = nlp;
2052 #if 0
2053                         dd->rrcount = 0;        /* reset round robin */
2054 #endif
2055                         spin_unlock(&dd->spin);
2056                         lwkt_acquire(nlp->lwp_thread);
2057                         lwkt_schedule(nlp->lwp_thread);
2058                 } else {
2059                         /*
2060                          * This situation should not occur because we had
2061                          * at least one thread available.
2062                          */
2063                         spin_unlock(&dd->spin);
2064                 }
2065         } else if (usched_dfly_features & 0x01) {
2066                 /*
2067                  * This cpu is devoid of runnable threads, steal a thread
2068                  * from another cpu.  Since we're stealing, might as well
2069                  * load balance at the same time.
2070                  *
2071                  * We choose the highest-loaded thread from the worst queue.
2072                  *
2073                  * NOTE! This function only returns a non-NULL rdd when
2074                  *       another cpu's queue is obviously overloaded.  We
2075                  *       do not want to perform the type of rebalancing
2076                  *       the schedclock does here because it would result
2077                  *       in insane process pulling when 'steady' state is
2078                  *       partially unbalanced (e.g. 6 runnables and only
2079                  *       4 cores).
2080                  */
2081                 rdd = dfly_choose_worst_queue(dd);
2082                 if (rdd && spin_trylock(&rdd->spin)) {
2083                         nlp = dfly_chooseproc_locked(rdd, dd, NULL, 1);
2084                         spin_unlock(&rdd->spin);
2085                 } else {
2086                         nlp = NULL;
2087                 }
2088                 if (nlp) {
2089                         atomic_set_cpumask(&dfly_curprocmask, mask);
2090                         dd->upri = nlp->lwp_priority;
2091                         dd->uschedcp = nlp;
2092 #if 0
2093                         dd->rrcount = 0;        /* reset round robin */
2094 #endif
2095                         spin_unlock(&dd->spin);
2096                         lwkt_acquire(nlp->lwp_thread);
2097                         lwkt_schedule(nlp->lwp_thread);
2098                 } else {
2099                         /*
2100                          * Leave the thread on our run queue.  Another
2101                          * scheduler will try to pull it later.
2102                          */
2103                         spin_unlock(&dd->spin);
2104                 }
2105         } else {
2106                 /*
2107                  * devoid of runnable threads and not allowed to steal
2108                  * any.
2109                  */
2110                 spin_unlock(&dd->spin);
2111         }
2112
2113         /*
2114          * We're descheduled unless someone scheduled us.  Switch away.
2115          * Exiting the critical section will cause splz() to be called
2116          * for us if interrupts and such are pending.
2117          */
2118         crit_exit_gd(gd);
2119         tsleep(&dd->helper_thread, PINTERLOCKED, "schslp", 0);
2120     }
2121 }
2122
2123 #if 0
2124 static int
2125 sysctl_usched_dfly_stick_to_level(SYSCTL_HANDLER_ARGS)
2126 {
2127         int error, new_val;
2128
2129         new_val = usched_dfly_stick_to_level;
2130
2131         error = sysctl_handle_int(oidp, &new_val, 0, req);
2132         if (error != 0 || req->newptr == NULL)
2133                 return (error);
2134         if (new_val > cpu_topology_levels_number - 1 || new_val < 0)
2135                 return (EINVAL);
2136         usched_dfly_stick_to_level = new_val;
2137         return (0);
2138 }
2139 #endif
2140
2141 /*
2142  * Setup our scheduler helpers.  Note that curprocmask bit 0 has already
2143  * been cleared by rqinit() and we should not mess with it further.
2144  */
2145 static void
2146 dfly_helper_thread_cpu_init(void)
2147 {
2148         int i;
2149         int j;
2150         int cpuid;
2151         int smt_not_supported = 0;
2152         int cache_coherent_not_supported = 0;
2153
2154         if (bootverbose)
2155                 kprintf("Start scheduler helpers on cpus:\n");
2156
2157         sysctl_ctx_init(&usched_dfly_sysctl_ctx);
2158         usched_dfly_sysctl_tree =
2159                 SYSCTL_ADD_NODE(&usched_dfly_sysctl_ctx,
2160                                 SYSCTL_STATIC_CHILDREN(_kern), OID_AUTO,
2161                                 "usched_dfly", CTLFLAG_RD, 0, "");
2162
2163         for (i = 0; i < ncpus; ++i) {
2164                 dfly_pcpu_t dd = &dfly_pcpu[i];
2165                 cpumask_t mask = CPUMASK(i);
2166
2167                 if ((mask & smp_active_mask) == 0)
2168                     continue;
2169
2170                 spin_init(&dd->spin);
2171                 dd->cpunode = get_cpu_node_by_cpuid(i);
2172                 dd->cpuid = i;
2173                 dd->cpumask = CPUMASK(i);
2174                 for (j = 0; j < NQS; j++) {
2175                         TAILQ_INIT(&dd->queues[j]);
2176                         TAILQ_INIT(&dd->rtqueues[j]);
2177                         TAILQ_INIT(&dd->idqueues[j]);
2178                 }
2179                 atomic_clear_cpumask(&dfly_curprocmask, 1);
2180
2181                 if (dd->cpunode == NULL) {
2182                         smt_not_supported = 1;
2183                         cache_coherent_not_supported = 1;
2184                         if (bootverbose)
2185                                 kprintf ("\tcpu%d - WARNING: No CPU NODE "
2186                                          "found for cpu\n", i);
2187                 } else {
2188                         switch (dd->cpunode->type) {
2189                         case THREAD_LEVEL:
2190                                 if (bootverbose)
2191                                         kprintf ("\tcpu%d - HyperThreading "
2192                                                  "available. Core siblings: ",
2193                                                  i);
2194                                 break;
2195                         case CORE_LEVEL:
2196                                 smt_not_supported = 1;
2197
2198                                 if (bootverbose)
2199                                         kprintf ("\tcpu%d - No HT available, "
2200                                                  "multi-core/physical "
2201                                                  "cpu. Physical siblings: ",
2202                                                  i);
2203                                 break;
2204                         case CHIP_LEVEL:
2205                                 smt_not_supported = 1;
2206
2207                                 if (bootverbose)
2208                                         kprintf ("\tcpu%d - No HT available, "
2209                                                  "single-core/physical cpu. "
2210                                                  "Package Siblings: ",
2211                                                  i);
2212                                 break;
2213                         default:
2214                                 /* Let's go for safe defaults here */
2215                                 smt_not_supported = 1;
2216                                 cache_coherent_not_supported = 1;
2217                                 if (bootverbose)
2218                                         kprintf ("\tcpu%d - Unknown cpunode->"
2219                                                  "type=%u. Siblings: ",
2220                                                  i,
2221                                                  (u_int)dd->cpunode->type);
2222                                 break;
2223                         }
2224
2225                         if (bootverbose) {
2226                                 if (dd->cpunode->parent_node != NULL) {
2227                                         CPUSET_FOREACH(cpuid, dd->cpunode->parent_node->members)
2228                                                 kprintf("cpu%d ", cpuid);
2229                                         kprintf("\n");
2230                                 } else {
2231                                         kprintf(" no siblings\n");
2232                                 }
2233                         }
2234                 }
2235
2236                 lwkt_create(dfly_helper_thread, NULL, NULL, &dd->helper_thread,
2237                             0, i, "usched %d", i);
2238
2239                 /*
2240                  * Allow user scheduling on the target cpu.  cpu #0 has already
2241                  * been enabled in rqinit().
2242                  */
2243                 if (i)
2244                     atomic_clear_cpumask(&dfly_curprocmask, mask);
2245                 atomic_set_cpumask(&dfly_rdyprocmask, mask);
2246                 dd->upri = PRIBASE_NULL;
2247
2248         }
2249
2250         /* usched_dfly sysctl configurable parameters */
2251
2252         SYSCTL_ADD_INT(&usched_dfly_sysctl_ctx,
2253                        SYSCTL_CHILDREN(usched_dfly_sysctl_tree),
2254                        OID_AUTO, "rrinterval", CTLFLAG_RW,
2255                        &usched_dfly_rrinterval, 0, "");
2256         SYSCTL_ADD_INT(&usched_dfly_sysctl_ctx,
2257                        SYSCTL_CHILDREN(usched_dfly_sysctl_tree),
2258                        OID_AUTO, "decay", CTLFLAG_RW,
2259                        &usched_dfly_decay, 0, "Extra decay when not running");
2260
2261         /* Add enable/disable option for SMT scheduling if supported */
2262         if (smt_not_supported) {
2263                 usched_dfly_smt = 0;
2264                 SYSCTL_ADD_STRING(&usched_dfly_sysctl_ctx,
2265                                   SYSCTL_CHILDREN(usched_dfly_sysctl_tree),
2266                                   OID_AUTO, "smt", CTLFLAG_RD,
2267                                   "NOT SUPPORTED", 0, "SMT NOT SUPPORTED");
2268         } else {
2269                 usched_dfly_smt = 1;
2270                 SYSCTL_ADD_INT(&usched_dfly_sysctl_ctx,
2271                                SYSCTL_CHILDREN(usched_dfly_sysctl_tree),
2272                                OID_AUTO, "smt", CTLFLAG_RW,
2273                                &usched_dfly_smt, 0, "Enable SMT scheduling");
2274         }
2275
2276         /*
2277          * Add enable/disable option for cache coherent scheduling
2278          * if supported
2279          */
2280         if (cache_coherent_not_supported) {
2281                 usched_dfly_cache_coherent = 0;
2282                 SYSCTL_ADD_STRING(&usched_dfly_sysctl_ctx,
2283                                   SYSCTL_CHILDREN(usched_dfly_sysctl_tree),
2284                                   OID_AUTO, "cache_coherent", CTLFLAG_RD,
2285                                   "NOT SUPPORTED", 0,
2286                                   "Cache coherence NOT SUPPORTED");
2287         } else {
2288                 usched_dfly_cache_coherent = 1;
2289                 SYSCTL_ADD_INT(&usched_dfly_sysctl_ctx,
2290                                SYSCTL_CHILDREN(usched_dfly_sysctl_tree),
2291                                OID_AUTO, "cache_coherent", CTLFLAG_RW,
2292                                &usched_dfly_cache_coherent, 0,
2293                                "Enable/Disable cache coherent scheduling");
2294
2295                 SYSCTL_ADD_INT(&usched_dfly_sysctl_ctx,
2296                                SYSCTL_CHILDREN(usched_dfly_sysctl_tree),
2297                                OID_AUTO, "weight1", CTLFLAG_RW,
2298                                &usched_dfly_weight1, 200,
2299                                "Weight selection for current cpu");
2300
2301                 SYSCTL_ADD_INT(&usched_dfly_sysctl_ctx,
2302                                SYSCTL_CHILDREN(usched_dfly_sysctl_tree),
2303                                OID_AUTO, "weight2", CTLFLAG_RW,
2304                                &usched_dfly_weight2, 180,
2305                                "Weight selection for wakefrom cpu");
2306
2307                 SYSCTL_ADD_INT(&usched_dfly_sysctl_ctx,
2308                                SYSCTL_CHILDREN(usched_dfly_sysctl_tree),
2309                                OID_AUTO, "weight3", CTLFLAG_RW,
2310                                &usched_dfly_weight3, 40,
2311                                "Weight selection for num threads on queue");
2312
2313                 SYSCTL_ADD_INT(&usched_dfly_sysctl_ctx,
2314                                SYSCTL_CHILDREN(usched_dfly_sysctl_tree),
2315                                OID_AUTO, "weight4", CTLFLAG_RW,
2316                                &usched_dfly_weight4, 160,
2317                                "Availability of other idle cpus");
2318
2319                 SYSCTL_ADD_INT(&usched_dfly_sysctl_ctx,
2320                                SYSCTL_CHILDREN(usched_dfly_sysctl_tree),
2321                                OID_AUTO, "fast_resched", CTLFLAG_RW,
2322                                &usched_dfly_fast_resched, 0,
2323                                "Availability of other idle cpus");
2324
2325                 SYSCTL_ADD_INT(&usched_dfly_sysctl_ctx,
2326                                SYSCTL_CHILDREN(usched_dfly_sysctl_tree),
2327                                OID_AUTO, "features", CTLFLAG_RW,
2328                                &usched_dfly_features, 0x8F,
2329                                "Allow pulls into empty queues");
2330
2331                 SYSCTL_ADD_INT(&usched_dfly_sysctl_ctx,
2332                                SYSCTL_CHILDREN(usched_dfly_sysctl_tree),
2333                                OID_AUTO, "swmask", CTLFLAG_RW,
2334                                &usched_dfly_swmask, ~PPQMASK,
2335                                "Queue mask to force thread switch");
2336
2337
2338 #if 0
2339                 SYSCTL_ADD_PROC(&usched_dfly_sysctl_ctx,
2340                                 SYSCTL_CHILDREN(usched_dfly_sysctl_tree),
2341                                 OID_AUTO, "stick_to_level",
2342                                 CTLTYPE_INT | CTLFLAG_RW,
2343                                 NULL, sizeof usched_dfly_stick_to_level,
2344                                 sysctl_usched_dfly_stick_to_level, "I",
2345                                 "Stick a process to this level. See sysctl"
2346                                 "paremter hw.cpu_topology.level_description");
2347 #endif
2348         }
2349 }
2350 SYSINIT(uschedtd, SI_BOOT2_USCHED, SI_ORDER_SECOND,
2351         dfly_helper_thread_cpu_init, NULL)
2352
2353 #else /* No SMP options - just add the configurable parameters to sysctl */
2354
2355 static void
2356 sched_sysctl_tree_init(void)
2357 {
2358         sysctl_ctx_init(&usched_dfly_sysctl_ctx);
2359         usched_dfly_sysctl_tree =
2360                 SYSCTL_ADD_NODE(&usched_dfly_sysctl_ctx,
2361                                 SYSCTL_STATIC_CHILDREN(_kern), OID_AUTO,
2362                                 "usched_dfly", CTLFLAG_RD, 0, "");
2363
2364         /* usched_dfly sysctl configurable parameters */
2365         SYSCTL_ADD_INT(&usched_dfly_sysctl_ctx,
2366                        SYSCTL_CHILDREN(usched_dfly_sysctl_tree),
2367                        OID_AUTO, "rrinterval", CTLFLAG_RW,
2368                        &usched_dfly_rrinterval, 0, "");
2369         SYSCTL_ADD_INT(&usched_dfly_sysctl_ctx,
2370                        SYSCTL_CHILDREN(usched_dfly_sysctl_tree),
2371                        OID_AUTO, "decay", CTLFLAG_RW,
2372                        &usched_dfly_decay, 0, "Extra decay when not running");
2373 }
2374 SYSINIT(uschedtd, SI_BOOT2_USCHED, SI_ORDER_SECOND,
2375         sched_sysctl_tree_init, NULL)
2376 #endif