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