]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - sys/kern/sched_ule.c
MFC r232917:
[FreeBSD/stable/9.git] / sys / kern / sched_ule.c
1 /*-
2  * Copyright (c) 2002-2007, Jeffrey Roberson <jeff@freebsd.org>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice unmodified, this list of conditions, and the following
10  *    disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26
27 /*
28  * This file implements the ULE scheduler.  ULE supports independent CPU
29  * run queues and fine grain locking.  It has superior interactive
30  * performance under load even on uni-processor systems.
31  *
32  * etymology:
33  *   ULE is the last three letters in schedule.  It owes its name to a
34  * generic user created for a scheduling system by Paul Mikesell at
35  * Isilon Systems and a general lack of creativity on the part of the author.
36  */
37
38 #include <sys/cdefs.h>
39 __FBSDID("$FreeBSD$");
40
41 #include "opt_hwpmc_hooks.h"
42 #include "opt_kdtrace.h"
43 #include "opt_sched.h"
44
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/kdb.h>
48 #include <sys/kernel.h>
49 #include <sys/ktr.h>
50 #include <sys/lock.h>
51 #include <sys/mutex.h>
52 #include <sys/proc.h>
53 #include <sys/resource.h>
54 #include <sys/resourcevar.h>
55 #include <sys/sched.h>
56 #include <sys/smp.h>
57 #include <sys/sx.h>
58 #include <sys/sysctl.h>
59 #include <sys/sysproto.h>
60 #include <sys/turnstile.h>
61 #include <sys/umtx.h>
62 #include <sys/vmmeter.h>
63 #include <sys/cpuset.h>
64 #include <sys/sbuf.h>
65
66 #ifdef HWPMC_HOOKS
67 #include <sys/pmckern.h>
68 #endif
69
70 #ifdef KDTRACE_HOOKS
71 #include <sys/dtrace_bsd.h>
72 int                             dtrace_vtime_active;
73 dtrace_vtime_switch_func_t      dtrace_vtime_switch_func;
74 #endif
75
76 #include <machine/cpu.h>
77 #include <machine/smp.h>
78
79 #if defined(__powerpc__) && defined(E500)
80 #error "This architecture is not currently compatible with ULE"
81 #endif
82
83 #define KTR_ULE 0
84
85 #define TS_NAME_LEN (MAXCOMLEN + sizeof(" td ") + sizeof(__XSTRING(UINT_MAX)))
86 #define TDQ_NAME_LEN    (sizeof("sched lock ") + sizeof(__XSTRING(MAXCPU)))
87 #define TDQ_LOADNAME_LEN        (sizeof("CPU ") + sizeof(__XSTRING(MAXCPU)) - 1 + sizeof(" load"))
88
89 /*
90  * Thread scheduler specific section.  All fields are protected
91  * by the thread lock.
92  */
93 struct td_sched {       
94         struct runq     *ts_runq;       /* Run-queue we're queued on. */
95         short           ts_flags;       /* TSF_* flags. */
96         u_char          ts_cpu;         /* CPU that we have affinity for. */
97         int             ts_rltick;      /* Real last tick, for affinity. */
98         int             ts_slice;       /* Ticks of slice remaining. */
99         u_int           ts_slptime;     /* Number of ticks we vol. slept */
100         u_int           ts_runtime;     /* Number of ticks we were running */
101         int             ts_ltick;       /* Last tick that we were running on */
102         int             ts_ftick;       /* First tick that we were running on */
103         int             ts_ticks;       /* Tick count */
104 #ifdef KTR
105         char            ts_name[TS_NAME_LEN];
106 #endif
107 };
108 /* flags kept in ts_flags */
109 #define TSF_BOUND       0x0001          /* Thread can not migrate. */
110 #define TSF_XFERABLE    0x0002          /* Thread was added as transferable. */
111
112 static struct td_sched td_sched0;
113
114 #define THREAD_CAN_MIGRATE(td)  ((td)->td_pinned == 0)
115 #define THREAD_CAN_SCHED(td, cpu)       \
116     CPU_ISSET((cpu), &(td)->td_cpuset->cs_mask)
117
118 /*
119  * Priority ranges used for interactive and non-interactive timeshare
120  * threads.  The timeshare priorities are split up into four ranges.
121  * The first range handles interactive threads.  The last three ranges
122  * (NHALF, x, and NHALF) handle non-interactive threads with the outer
123  * ranges supporting nice values.
124  */
125 #define PRI_TIMESHARE_RANGE     (PRI_MAX_TIMESHARE - PRI_MIN_TIMESHARE + 1)
126 #define PRI_INTERACT_RANGE      ((PRI_TIMESHARE_RANGE - SCHED_PRI_NRESV) / 2)
127 #define PRI_BATCH_RANGE         (PRI_TIMESHARE_RANGE - PRI_INTERACT_RANGE)
128
129 #define PRI_MIN_INTERACT        PRI_MIN_TIMESHARE
130 #define PRI_MAX_INTERACT        (PRI_MIN_TIMESHARE + PRI_INTERACT_RANGE - 1)
131 #define PRI_MIN_BATCH           (PRI_MIN_TIMESHARE + PRI_INTERACT_RANGE)
132 #define PRI_MAX_BATCH           PRI_MAX_TIMESHARE
133
134 /*
135  * Cpu percentage computation macros and defines.
136  *
137  * SCHED_TICK_SECS:     Number of seconds to average the cpu usage across.
138  * SCHED_TICK_TARG:     Number of hz ticks to average the cpu usage across.
139  * SCHED_TICK_MAX:      Maximum number of ticks before scaling back.
140  * SCHED_TICK_SHIFT:    Shift factor to avoid rounding away results.
141  * SCHED_TICK_HZ:       Compute the number of hz ticks for a given ticks count.
142  * SCHED_TICK_TOTAL:    Gives the amount of time we've been recording ticks.
143  */
144 #define SCHED_TICK_SECS         10
145 #define SCHED_TICK_TARG         (hz * SCHED_TICK_SECS)
146 #define SCHED_TICK_MAX          (SCHED_TICK_TARG + hz)
147 #define SCHED_TICK_SHIFT        10
148 #define SCHED_TICK_HZ(ts)       ((ts)->ts_ticks >> SCHED_TICK_SHIFT)
149 #define SCHED_TICK_TOTAL(ts)    (max((ts)->ts_ltick - (ts)->ts_ftick, hz))
150
151 /*
152  * These macros determine priorities for non-interactive threads.  They are
153  * assigned a priority based on their recent cpu utilization as expressed
154  * by the ratio of ticks to the tick total.  NHALF priorities at the start
155  * and end of the MIN to MAX timeshare range are only reachable with negative
156  * or positive nice respectively.
157  *
158  * PRI_RANGE:   Priority range for utilization dependent priorities.
159  * PRI_NRESV:   Number of nice values.
160  * PRI_TICKS:   Compute a priority in PRI_RANGE from the ticks count and total.
161  * PRI_NICE:    Determines the part of the priority inherited from nice.
162  */
163 #define SCHED_PRI_NRESV         (PRIO_MAX - PRIO_MIN)
164 #define SCHED_PRI_NHALF         (SCHED_PRI_NRESV / 2)
165 #define SCHED_PRI_MIN           (PRI_MIN_BATCH + SCHED_PRI_NHALF)
166 #define SCHED_PRI_MAX           (PRI_MAX_BATCH - SCHED_PRI_NHALF)
167 #define SCHED_PRI_RANGE         (SCHED_PRI_MAX - SCHED_PRI_MIN + 1)
168 #define SCHED_PRI_TICKS(ts)                                             \
169     (SCHED_TICK_HZ((ts)) /                                              \
170     (roundup(SCHED_TICK_TOTAL((ts)), SCHED_PRI_RANGE) / SCHED_PRI_RANGE))
171 #define SCHED_PRI_NICE(nice)    (nice)
172
173 /*
174  * These determine the interactivity of a process.  Interactivity differs from
175  * cpu utilization in that it expresses the voluntary time slept vs time ran
176  * while cpu utilization includes all time not running.  This more accurately
177  * models the intent of the thread.
178  *
179  * SLP_RUN_MAX: Maximum amount of sleep time + run time we'll accumulate
180  *              before throttling back.
181  * SLP_RUN_FORK:        Maximum slp+run time to inherit at fork time.
182  * INTERACT_MAX:        Maximum interactivity value.  Smaller is better.
183  * INTERACT_THRESH:     Threshold for placement on the current runq.
184  */
185 #define SCHED_SLP_RUN_MAX       ((hz * 5) << SCHED_TICK_SHIFT)
186 #define SCHED_SLP_RUN_FORK      ((hz / 2) << SCHED_TICK_SHIFT)
187 #define SCHED_INTERACT_MAX      (100)
188 #define SCHED_INTERACT_HALF     (SCHED_INTERACT_MAX / 2)
189 #define SCHED_INTERACT_THRESH   (30)
190
191 /*
192  * tickincr:            Converts a stathz tick into a hz domain scaled by
193  *                      the shift factor.  Without the shift the error rate
194  *                      due to rounding would be unacceptably high.
195  * realstathz:          stathz is sometimes 0 and run off of hz.
196  * sched_slice:         Runtime of each thread before rescheduling.
197  * preempt_thresh:      Priority threshold for preemption and remote IPIs.
198  */
199 static int sched_interact = SCHED_INTERACT_THRESH;
200 static int realstathz;
201 static int tickincr;
202 static int sched_slice = 1;
203 #ifdef PREEMPTION
204 #ifdef FULL_PREEMPTION
205 static int preempt_thresh = PRI_MAX_IDLE;
206 #else
207 static int preempt_thresh = PRI_MIN_KERN;
208 #endif
209 #else 
210 static int preempt_thresh = 0;
211 #endif
212 static int static_boost = PRI_MIN_BATCH;
213 static int sched_idlespins = 10000;
214 static int sched_idlespinthresh = 16;
215
216 /*
217  * tdq - per processor runqs and statistics.  All fields are protected by the
218  * tdq_lock.  The load and lowpri may be accessed without to avoid excess
219  * locking in sched_pickcpu();
220  */
221 struct tdq {
222         /* Ordered to improve efficiency of cpu_search() and switch(). */
223         struct mtx      tdq_lock;               /* run queue lock. */
224         struct cpu_group *tdq_cg;               /* Pointer to cpu topology. */
225         volatile int    tdq_load;               /* Aggregate load. */
226         volatile int    tdq_cpu_idle;           /* cpu_idle() is active. */
227         int             tdq_sysload;            /* For loadavg, !ITHD load. */
228         int             tdq_transferable;       /* Transferable thread count. */
229         short           tdq_switchcnt;          /* Switches this tick. */
230         short           tdq_oldswitchcnt;       /* Switches last tick. */
231         u_char          tdq_lowpri;             /* Lowest priority thread. */
232         u_char          tdq_ipipending;         /* IPI pending. */
233         u_char          tdq_idx;                /* Current insert index. */
234         u_char          tdq_ridx;               /* Current removal index. */
235         struct runq     tdq_realtime;           /* real-time run queue. */
236         struct runq     tdq_timeshare;          /* timeshare run queue. */
237         struct runq     tdq_idle;               /* Queue of IDLE threads. */
238         char            tdq_name[TDQ_NAME_LEN];
239 #ifdef KTR
240         char            tdq_loadname[TDQ_LOADNAME_LEN];
241 #endif
242 } __aligned(64);
243
244 /* Idle thread states and config. */
245 #define TDQ_RUNNING     1
246 #define TDQ_IDLE        2
247
248 #ifdef SMP
249 struct cpu_group *cpu_top;              /* CPU topology */
250
251 #define SCHED_AFFINITY_DEFAULT  (max(1, hz / 1000))
252 #define SCHED_AFFINITY(ts, t)   ((ts)->ts_rltick > ticks - ((t) * affinity))
253
254 /*
255  * Run-time tunables.
256  */
257 static int rebalance = 1;
258 static int balance_interval = 128;      /* Default set in sched_initticks(). */
259 static int affinity;
260 static int steal_idle = 1;
261 static int steal_thresh = 2;
262
263 /*
264  * One thread queue per processor.
265  */
266 static struct tdq       tdq_cpu[MAXCPU];
267 static struct tdq       *balance_tdq;
268 static int balance_ticks;
269 static DPCPU_DEFINE(uint32_t, randomval);
270
271 #define TDQ_SELF()      (&tdq_cpu[PCPU_GET(cpuid)])
272 #define TDQ_CPU(x)      (&tdq_cpu[(x)])
273 #define TDQ_ID(x)       ((int)((x) - tdq_cpu))
274 #else   /* !SMP */
275 static struct tdq       tdq_cpu;
276
277 #define TDQ_ID(x)       (0)
278 #define TDQ_SELF()      (&tdq_cpu)
279 #define TDQ_CPU(x)      (&tdq_cpu)
280 #endif
281
282 #define TDQ_LOCK_ASSERT(t, type)        mtx_assert(TDQ_LOCKPTR((t)), (type))
283 #define TDQ_LOCK(t)             mtx_lock_spin(TDQ_LOCKPTR((t)))
284 #define TDQ_LOCK_FLAGS(t, f)    mtx_lock_spin_flags(TDQ_LOCKPTR((t)), (f))
285 #define TDQ_UNLOCK(t)           mtx_unlock_spin(TDQ_LOCKPTR((t)))
286 #define TDQ_LOCKPTR(t)          (&(t)->tdq_lock)
287
288 static void sched_priority(struct thread *);
289 static void sched_thread_priority(struct thread *, u_char);
290 static int sched_interact_score(struct thread *);
291 static void sched_interact_update(struct thread *);
292 static void sched_interact_fork(struct thread *);
293 static void sched_pctcpu_update(struct td_sched *, int);
294
295 /* Operations on per processor queues */
296 static struct thread *tdq_choose(struct tdq *);
297 static void tdq_setup(struct tdq *);
298 static void tdq_load_add(struct tdq *, struct thread *);
299 static void tdq_load_rem(struct tdq *, struct thread *);
300 static __inline void tdq_runq_add(struct tdq *, struct thread *, int);
301 static __inline void tdq_runq_rem(struct tdq *, struct thread *);
302 static inline int sched_shouldpreempt(int, int, int);
303 void tdq_print(int cpu);
304 static void runq_print(struct runq *rq);
305 static void tdq_add(struct tdq *, struct thread *, int);
306 #ifdef SMP
307 static int tdq_move(struct tdq *, struct tdq *);
308 static int tdq_idled(struct tdq *);
309 static void tdq_notify(struct tdq *, struct thread *);
310 static struct thread *tdq_steal(struct tdq *, int);
311 static struct thread *runq_steal(struct runq *, int);
312 static int sched_pickcpu(struct thread *, int);
313 static void sched_balance(void);
314 static int sched_balance_pair(struct tdq *, struct tdq *);
315 static inline struct tdq *sched_setcpu(struct thread *, int, int);
316 static inline void thread_unblock_switch(struct thread *, struct mtx *);
317 static struct mtx *sched_switch_migrate(struct tdq *, struct thread *, int);
318 static int sysctl_kern_sched_topology_spec(SYSCTL_HANDLER_ARGS);
319 static int sysctl_kern_sched_topology_spec_internal(struct sbuf *sb, 
320     struct cpu_group *cg, int indent);
321 #endif
322
323 static void sched_setup(void *dummy);
324 SYSINIT(sched_setup, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, sched_setup, NULL);
325
326 static void sched_initticks(void *dummy);
327 SYSINIT(sched_initticks, SI_SUB_CLOCKS, SI_ORDER_THIRD, sched_initticks,
328     NULL);
329
330 /*
331  * Print the threads waiting on a run-queue.
332  */
333 static void
334 runq_print(struct runq *rq)
335 {
336         struct rqhead *rqh;
337         struct thread *td;
338         int pri;
339         int j;
340         int i;
341
342         for (i = 0; i < RQB_LEN; i++) {
343                 printf("\t\trunq bits %d 0x%zx\n",
344                     i, rq->rq_status.rqb_bits[i]);
345                 for (j = 0; j < RQB_BPW; j++)
346                         if (rq->rq_status.rqb_bits[i] & (1ul << j)) {
347                                 pri = j + (i << RQB_L2BPW);
348                                 rqh = &rq->rq_queues[pri];
349                                 TAILQ_FOREACH(td, rqh, td_runq) {
350                                         printf("\t\t\ttd %p(%s) priority %d rqindex %d pri %d\n",
351                                             td, td->td_name, td->td_priority,
352                                             td->td_rqindex, pri);
353                                 }
354                         }
355         }
356 }
357
358 /*
359  * Print the status of a per-cpu thread queue.  Should be a ddb show cmd.
360  */
361 void
362 tdq_print(int cpu)
363 {
364         struct tdq *tdq;
365
366         tdq = TDQ_CPU(cpu);
367
368         printf("tdq %d:\n", TDQ_ID(tdq));
369         printf("\tlock            %p\n", TDQ_LOCKPTR(tdq));
370         printf("\tLock name:      %s\n", tdq->tdq_name);
371         printf("\tload:           %d\n", tdq->tdq_load);
372         printf("\tswitch cnt:     %d\n", tdq->tdq_switchcnt);
373         printf("\told switch cnt: %d\n", tdq->tdq_oldswitchcnt);
374         printf("\ttimeshare idx:  %d\n", tdq->tdq_idx);
375         printf("\ttimeshare ridx: %d\n", tdq->tdq_ridx);
376         printf("\tload transferable: %d\n", tdq->tdq_transferable);
377         printf("\tlowest priority:   %d\n", tdq->tdq_lowpri);
378         printf("\trealtime runq:\n");
379         runq_print(&tdq->tdq_realtime);
380         printf("\ttimeshare runq:\n");
381         runq_print(&tdq->tdq_timeshare);
382         printf("\tidle runq:\n");
383         runq_print(&tdq->tdq_idle);
384 }
385
386 static inline int
387 sched_shouldpreempt(int pri, int cpri, int remote)
388 {
389         /*
390          * If the new priority is not better than the current priority there is
391          * nothing to do.
392          */
393         if (pri >= cpri)
394                 return (0);
395         /*
396          * Always preempt idle.
397          */
398         if (cpri >= PRI_MIN_IDLE)
399                 return (1);
400         /*
401          * If preemption is disabled don't preempt others.
402          */
403         if (preempt_thresh == 0)
404                 return (0);
405         /*
406          * Preempt if we exceed the threshold.
407          */
408         if (pri <= preempt_thresh)
409                 return (1);
410         /*
411          * If we're interactive or better and there is non-interactive
412          * or worse running preempt only remote processors.
413          */
414         if (remote && pri <= PRI_MAX_INTERACT && cpri > PRI_MAX_INTERACT)
415                 return (1);
416         return (0);
417 }
418
419 /*
420  * Add a thread to the actual run-queue.  Keeps transferable counts up to
421  * date with what is actually on the run-queue.  Selects the correct
422  * queue position for timeshare threads.
423  */
424 static __inline void
425 tdq_runq_add(struct tdq *tdq, struct thread *td, int flags)
426 {
427         struct td_sched *ts;
428         u_char pri;
429
430         TDQ_LOCK_ASSERT(tdq, MA_OWNED);
431         THREAD_LOCK_ASSERT(td, MA_OWNED);
432
433         pri = td->td_priority;
434         ts = td->td_sched;
435         TD_SET_RUNQ(td);
436         if (THREAD_CAN_MIGRATE(td)) {
437                 tdq->tdq_transferable++;
438                 ts->ts_flags |= TSF_XFERABLE;
439         }
440         if (pri < PRI_MIN_BATCH) {
441                 ts->ts_runq = &tdq->tdq_realtime;
442         } else if (pri <= PRI_MAX_BATCH) {
443                 ts->ts_runq = &tdq->tdq_timeshare;
444                 KASSERT(pri <= PRI_MAX_BATCH && pri >= PRI_MIN_BATCH,
445                         ("Invalid priority %d on timeshare runq", pri));
446                 /*
447                  * This queue contains only priorities between MIN and MAX
448                  * realtime.  Use the whole queue to represent these values.
449                  */
450                 if ((flags & (SRQ_BORROWING|SRQ_PREEMPTED)) == 0) {
451                         pri = RQ_NQS * (pri - PRI_MIN_BATCH) / PRI_BATCH_RANGE;
452                         pri = (pri + tdq->tdq_idx) % RQ_NQS;
453                         /*
454                          * This effectively shortens the queue by one so we
455                          * can have a one slot difference between idx and
456                          * ridx while we wait for threads to drain.
457                          */
458                         if (tdq->tdq_ridx != tdq->tdq_idx &&
459                             pri == tdq->tdq_ridx)
460                                 pri = (unsigned char)(pri - 1) % RQ_NQS;
461                 } else
462                         pri = tdq->tdq_ridx;
463                 runq_add_pri(ts->ts_runq, td, pri, flags);
464                 return;
465         } else
466                 ts->ts_runq = &tdq->tdq_idle;
467         runq_add(ts->ts_runq, td, flags);
468 }
469
470 /* 
471  * Remove a thread from a run-queue.  This typically happens when a thread
472  * is selected to run.  Running threads are not on the queue and the
473  * transferable count does not reflect them.
474  */
475 static __inline void
476 tdq_runq_rem(struct tdq *tdq, struct thread *td)
477 {
478         struct td_sched *ts;
479
480         ts = td->td_sched;
481         TDQ_LOCK_ASSERT(tdq, MA_OWNED);
482         KASSERT(ts->ts_runq != NULL,
483             ("tdq_runq_remove: thread %p null ts_runq", td));
484         if (ts->ts_flags & TSF_XFERABLE) {
485                 tdq->tdq_transferable--;
486                 ts->ts_flags &= ~TSF_XFERABLE;
487         }
488         if (ts->ts_runq == &tdq->tdq_timeshare) {
489                 if (tdq->tdq_idx != tdq->tdq_ridx)
490                         runq_remove_idx(ts->ts_runq, td, &tdq->tdq_ridx);
491                 else
492                         runq_remove_idx(ts->ts_runq, td, NULL);
493         } else
494                 runq_remove(ts->ts_runq, td);
495 }
496
497 /*
498  * Load is maintained for all threads RUNNING and ON_RUNQ.  Add the load
499  * for this thread to the referenced thread queue.
500  */
501 static void
502 tdq_load_add(struct tdq *tdq, struct thread *td)
503 {
504
505         TDQ_LOCK_ASSERT(tdq, MA_OWNED);
506         THREAD_LOCK_ASSERT(td, MA_OWNED);
507
508         tdq->tdq_load++;
509         if ((td->td_flags & TDF_NOLOAD) == 0)
510                 tdq->tdq_sysload++;
511         KTR_COUNTER0(KTR_SCHED, "load", tdq->tdq_loadname, tdq->tdq_load);
512 }
513
514 /*
515  * Remove the load from a thread that is transitioning to a sleep state or
516  * exiting.
517  */
518 static void
519 tdq_load_rem(struct tdq *tdq, struct thread *td)
520 {
521
522         THREAD_LOCK_ASSERT(td, MA_OWNED);
523         TDQ_LOCK_ASSERT(tdq, MA_OWNED);
524         KASSERT(tdq->tdq_load != 0,
525             ("tdq_load_rem: Removing with 0 load on queue %d", TDQ_ID(tdq)));
526
527         tdq->tdq_load--;
528         if ((td->td_flags & TDF_NOLOAD) == 0)
529                 tdq->tdq_sysload--;
530         KTR_COUNTER0(KTR_SCHED, "load", tdq->tdq_loadname, tdq->tdq_load);
531 }
532
533 /*
534  * Set lowpri to its exact value by searching the run-queue and
535  * evaluating curthread.  curthread may be passed as an optimization.
536  */
537 static void
538 tdq_setlowpri(struct tdq *tdq, struct thread *ctd)
539 {
540         struct thread *td;
541
542         TDQ_LOCK_ASSERT(tdq, MA_OWNED);
543         if (ctd == NULL)
544                 ctd = pcpu_find(TDQ_ID(tdq))->pc_curthread;
545         td = tdq_choose(tdq);
546         if (td == NULL || td->td_priority > ctd->td_priority)
547                 tdq->tdq_lowpri = ctd->td_priority;
548         else
549                 tdq->tdq_lowpri = td->td_priority;
550 }
551
552 #ifdef SMP
553 struct cpu_search {
554         cpuset_t cs_mask;
555         u_int   cs_prefer;
556         int     cs_pri;         /* Min priority for low. */
557         int     cs_limit;       /* Max load for low, min load for high. */
558         int     cs_cpu;
559         int     cs_load;
560 };
561
562 #define CPU_SEARCH_LOWEST       0x1
563 #define CPU_SEARCH_HIGHEST      0x2
564 #define CPU_SEARCH_BOTH         (CPU_SEARCH_LOWEST|CPU_SEARCH_HIGHEST)
565
566 #define CPUSET_FOREACH(cpu, mask)                               \
567         for ((cpu) = 0; (cpu) <= mp_maxid; (cpu)++)             \
568                 if (CPU_ISSET(cpu, &mask))
569
570 static __inline int cpu_search(const struct cpu_group *cg, struct cpu_search *low,
571     struct cpu_search *high, const int match);
572 int cpu_search_lowest(const struct cpu_group *cg, struct cpu_search *low);
573 int cpu_search_highest(const struct cpu_group *cg, struct cpu_search *high);
574 int cpu_search_both(const struct cpu_group *cg, struct cpu_search *low,
575     struct cpu_search *high);
576
577 /*
578  * Search the tree of cpu_groups for the lowest or highest loaded cpu
579  * according to the match argument.  This routine actually compares the
580  * load on all paths through the tree and finds the least loaded cpu on
581  * the least loaded path, which may differ from the least loaded cpu in
582  * the system.  This balances work among caches and busses.
583  *
584  * This inline is instantiated in three forms below using constants for the
585  * match argument.  It is reduced to the minimum set for each case.  It is
586  * also recursive to the depth of the tree.
587  */
588 static __inline int
589 cpu_search(const struct cpu_group *cg, struct cpu_search *low,
590     struct cpu_search *high, const int match)
591 {
592         struct cpu_search lgroup;
593         struct cpu_search hgroup;
594         cpuset_t cpumask;
595         struct cpu_group *child;
596         struct tdq *tdq;
597         int cpu, i, hload, lload, load, total, rnd;
598
599         total = 0;
600         cpumask = cg->cg_mask;
601         if (match & CPU_SEARCH_LOWEST) {
602                 lload = INT_MAX;
603                 low->cs_load = INT_MAX;
604                 lgroup = *low;
605         }
606         if (match & CPU_SEARCH_HIGHEST) {
607                 hload = -1;
608                 high->cs_load = -1;
609                 hgroup = *high;
610         }
611
612         /* Iterate through the child CPU groups and then remaining CPUs. */
613         for (i = 0, cpu = 0; i <= cg->cg_children; ) {
614                 if (i >= cg->cg_children) {
615                         while (cpu <= mp_maxid && !CPU_ISSET(cpu, &cpumask))
616                                 cpu++;
617                         if (cpu > mp_maxid)
618                                 break;
619                         child = NULL;
620                 } else
621                         child = &cg->cg_child[i];
622
623                 if (child) {                    /* Handle child CPU group. */
624                         CPU_NAND(&cpumask, &child->cg_mask);
625                         switch (match) {
626                         case CPU_SEARCH_LOWEST:
627                                 load = cpu_search_lowest(child, &lgroup);
628                                 break;
629                         case CPU_SEARCH_HIGHEST:
630                                 load = cpu_search_highest(child, &hgroup);
631                                 break;
632                         case CPU_SEARCH_BOTH:
633                                 load = cpu_search_both(child, &lgroup, &hgroup);
634                                 break;
635                         }
636                 } else {                        /* Handle child CPU. */
637                         tdq = TDQ_CPU(cpu);
638                         load = tdq->tdq_load * 256;
639                         rnd = DPCPU_SET(randomval,
640                             DPCPU_GET(randomval) * 69069 + 5) >> 26;
641                         if (match & CPU_SEARCH_LOWEST) {
642                                 if (cpu == low->cs_prefer)
643                                         load -= 64;
644                                 /* If that CPU is allowed and get data. */
645                                 if (CPU_ISSET(cpu, &lgroup.cs_mask) &&
646                                     tdq->tdq_lowpri > lgroup.cs_pri &&
647                                     tdq->tdq_load <= lgroup.cs_limit) {
648                                         lgroup.cs_cpu = cpu;
649                                         lgroup.cs_load = load - rnd;
650                                 }
651                         }
652                         if (match & CPU_SEARCH_HIGHEST)
653                                 if (CPU_ISSET(cpu, &hgroup.cs_mask) &&
654                                     tdq->tdq_load >= hgroup.cs_limit &&
655                                     tdq->tdq_transferable) {
656                                         hgroup.cs_cpu = cpu;
657                                         hgroup.cs_load = load - rnd;
658                                 }
659                 }
660                 total += load;
661
662                 /* We have info about child item. Compare it. */
663                 if (match & CPU_SEARCH_LOWEST) {
664                         if (lgroup.cs_load != INT_MAX &&
665                             (load < lload ||
666                              (load == lload && lgroup.cs_load < low->cs_load))) {
667                                 lload = load;
668                                 low->cs_cpu = lgroup.cs_cpu;
669                                 low->cs_load = lgroup.cs_load;
670                         }
671                 }
672                 if (match & CPU_SEARCH_HIGHEST)
673                         if (hgroup.cs_load >= 0 &&
674                             (load > hload ||
675                              (load == hload && hgroup.cs_load > high->cs_load))) {
676                                 hload = load;
677                                 high->cs_cpu = hgroup.cs_cpu;
678                                 high->cs_load = hgroup.cs_load;
679                         }
680                 if (child)
681                         i++;
682                 else
683                         cpu++;
684         }
685         return (total);
686 }
687
688 /*
689  * cpu_search instantiations must pass constants to maintain the inline
690  * optimization.
691  */
692 int
693 cpu_search_lowest(const struct cpu_group *cg, struct cpu_search *low)
694 {
695         return cpu_search(cg, low, NULL, CPU_SEARCH_LOWEST);
696 }
697
698 int
699 cpu_search_highest(const struct cpu_group *cg, struct cpu_search *high)
700 {
701         return cpu_search(cg, NULL, high, CPU_SEARCH_HIGHEST);
702 }
703
704 int
705 cpu_search_both(const struct cpu_group *cg, struct cpu_search *low,
706     struct cpu_search *high)
707 {
708         return cpu_search(cg, low, high, CPU_SEARCH_BOTH);
709 }
710
711 /*
712  * Find the cpu with the least load via the least loaded path that has a
713  * lowpri greater than pri  pri.  A pri of -1 indicates any priority is
714  * acceptable.
715  */
716 static inline int
717 sched_lowest(const struct cpu_group *cg, cpuset_t mask, int pri, int maxload,
718     int prefer)
719 {
720         struct cpu_search low;
721
722         low.cs_cpu = -1;
723         low.cs_prefer = prefer;
724         low.cs_mask = mask;
725         low.cs_pri = pri;
726         low.cs_limit = maxload;
727         cpu_search_lowest(cg, &low);
728         return low.cs_cpu;
729 }
730
731 /*
732  * Find the cpu with the highest load via the highest loaded path.
733  */
734 static inline int
735 sched_highest(const struct cpu_group *cg, cpuset_t mask, int minload)
736 {
737         struct cpu_search high;
738
739         high.cs_cpu = -1;
740         high.cs_mask = mask;
741         high.cs_limit = minload;
742         cpu_search_highest(cg, &high);
743         return high.cs_cpu;
744 }
745
746 /*
747  * Simultaneously find the highest and lowest loaded cpu reachable via
748  * cg.
749  */
750 static inline void
751 sched_both(const struct cpu_group *cg, cpuset_t mask, int *lowcpu, int *highcpu)
752 {
753         struct cpu_search high;
754         struct cpu_search low;
755
756         low.cs_cpu = -1;
757         low.cs_prefer = -1;
758         low.cs_pri = -1;
759         low.cs_limit = INT_MAX;
760         low.cs_mask = mask;
761         high.cs_cpu = -1;
762         high.cs_limit = -1;
763         high.cs_mask = mask;
764         cpu_search_both(cg, &low, &high);
765         *lowcpu = low.cs_cpu;
766         *highcpu = high.cs_cpu;
767         return;
768 }
769
770 static void
771 sched_balance_group(struct cpu_group *cg)
772 {
773         cpuset_t hmask, lmask;
774         int high, low, anylow;
775
776         CPU_FILL(&hmask);
777         for (;;) {
778                 high = sched_highest(cg, hmask, 1);
779                 /* Stop if there is no more CPU with transferrable threads. */
780                 if (high == -1)
781                         break;
782                 CPU_CLR(high, &hmask);
783                 CPU_COPY(&hmask, &lmask);
784                 /* Stop if there is no more CPU left for low. */
785                 if (CPU_EMPTY(&lmask))
786                         break;
787                 anylow = 1;
788 nextlow:
789                 low = sched_lowest(cg, lmask, -1,
790                     TDQ_CPU(high)->tdq_load - 1, high);
791                 /* Stop if we looked well and found no less loaded CPU. */
792                 if (anylow && low == -1)
793                         break;
794                 /* Go to next high if we found no less loaded CPU. */
795                 if (low == -1)
796                         continue;
797                 /* Transfer thread from high to low. */
798                 if (sched_balance_pair(TDQ_CPU(high), TDQ_CPU(low))) {
799                         /* CPU that got thread can no longer be a donor. */
800                         CPU_CLR(low, &hmask);
801                 } else {
802                         /*
803                          * If failed, then there is no threads on high
804                          * that can run on this low. Drop low from low
805                          * mask and look for different one.
806                          */
807                         CPU_CLR(low, &lmask);
808                         anylow = 0;
809                         goto nextlow;
810                 }
811         }
812 }
813
814 static void
815 sched_balance(void)
816 {
817         struct tdq *tdq;
818
819         /*
820          * Select a random time between .5 * balance_interval and
821          * 1.5 * balance_interval.
822          */
823         balance_ticks = max(balance_interval / 2, 1);
824         balance_ticks += random() % balance_interval;
825         if (smp_started == 0 || rebalance == 0)
826                 return;
827         tdq = TDQ_SELF();
828         TDQ_UNLOCK(tdq);
829         sched_balance_group(cpu_top);
830         TDQ_LOCK(tdq);
831 }
832
833 /*
834  * Lock two thread queues using their address to maintain lock order.
835  */
836 static void
837 tdq_lock_pair(struct tdq *one, struct tdq *two)
838 {
839         if (one < two) {
840                 TDQ_LOCK(one);
841                 TDQ_LOCK_FLAGS(two, MTX_DUPOK);
842         } else {
843                 TDQ_LOCK(two);
844                 TDQ_LOCK_FLAGS(one, MTX_DUPOK);
845         }
846 }
847
848 /*
849  * Unlock two thread queues.  Order is not important here.
850  */
851 static void
852 tdq_unlock_pair(struct tdq *one, struct tdq *two)
853 {
854         TDQ_UNLOCK(one);
855         TDQ_UNLOCK(two);
856 }
857
858 /*
859  * Transfer load between two imbalanced thread queues.
860  */
861 static int
862 sched_balance_pair(struct tdq *high, struct tdq *low)
863 {
864         int moved;
865         int cpu;
866
867         tdq_lock_pair(high, low);
868         moved = 0;
869         /*
870          * Determine what the imbalance is and then adjust that to how many
871          * threads we actually have to give up (transferable).
872          */
873         if (high->tdq_transferable != 0 && high->tdq_load > low->tdq_load &&
874             (moved = tdq_move(high, low)) > 0) {
875                 /*
876                  * In case the target isn't the current cpu IPI it to force a
877                  * reschedule with the new workload.
878                  */
879                 cpu = TDQ_ID(low);
880                 sched_pin();
881                 if (cpu != PCPU_GET(cpuid))
882                         ipi_cpu(cpu, IPI_PREEMPT);
883                 sched_unpin();
884         }
885         tdq_unlock_pair(high, low);
886         return (moved);
887 }
888
889 /*
890  * Move a thread from one thread queue to another.
891  */
892 static int
893 tdq_move(struct tdq *from, struct tdq *to)
894 {
895         struct td_sched *ts;
896         struct thread *td;
897         struct tdq *tdq;
898         int cpu;
899
900         TDQ_LOCK_ASSERT(from, MA_OWNED);
901         TDQ_LOCK_ASSERT(to, MA_OWNED);
902
903         tdq = from;
904         cpu = TDQ_ID(to);
905         td = tdq_steal(tdq, cpu);
906         if (td == NULL)
907                 return (0);
908         ts = td->td_sched;
909         /*
910          * Although the run queue is locked the thread may be blocked.  Lock
911          * it to clear this and acquire the run-queue lock.
912          */
913         thread_lock(td);
914         /* Drop recursive lock on from acquired via thread_lock(). */
915         TDQ_UNLOCK(from);
916         sched_rem(td);
917         ts->ts_cpu = cpu;
918         td->td_lock = TDQ_LOCKPTR(to);
919         tdq_add(to, td, SRQ_YIELDING);
920         return (1);
921 }
922
923 /*
924  * This tdq has idled.  Try to steal a thread from another cpu and switch
925  * to it.
926  */
927 static int
928 tdq_idled(struct tdq *tdq)
929 {
930         struct cpu_group *cg;
931         struct tdq *steal;
932         cpuset_t mask;
933         int thresh;
934         int cpu;
935
936         if (smp_started == 0 || steal_idle == 0)
937                 return (1);
938         CPU_FILL(&mask);
939         CPU_CLR(PCPU_GET(cpuid), &mask);
940         /* We don't want to be preempted while we're iterating. */
941         spinlock_enter();
942         for (cg = tdq->tdq_cg; cg != NULL; ) {
943                 if ((cg->cg_flags & CG_FLAG_THREAD) == 0)
944                         thresh = steal_thresh;
945                 else
946                         thresh = 1;
947                 cpu = sched_highest(cg, mask, thresh);
948                 if (cpu == -1) {
949                         cg = cg->cg_parent;
950                         continue;
951                 }
952                 steal = TDQ_CPU(cpu);
953                 CPU_CLR(cpu, &mask);
954                 tdq_lock_pair(tdq, steal);
955                 if (steal->tdq_load < thresh || steal->tdq_transferable == 0) {
956                         tdq_unlock_pair(tdq, steal);
957                         continue;
958                 }
959                 /*
960                  * If a thread was added while interrupts were disabled don't
961                  * steal one here.  If we fail to acquire one due to affinity
962                  * restrictions loop again with this cpu removed from the
963                  * set.
964                  */
965                 if (tdq->tdq_load == 0 && tdq_move(steal, tdq) == 0) {
966                         tdq_unlock_pair(tdq, steal);
967                         continue;
968                 }
969                 spinlock_exit();
970                 TDQ_UNLOCK(steal);
971                 mi_switch(SW_VOL | SWT_IDLE, NULL);
972                 thread_unlock(curthread);
973
974                 return (0);
975         }
976         spinlock_exit();
977         return (1);
978 }
979
980 /*
981  * Notify a remote cpu of new work.  Sends an IPI if criteria are met.
982  */
983 static void
984 tdq_notify(struct tdq *tdq, struct thread *td)
985 {
986         struct thread *ctd;
987         int pri;
988         int cpu;
989
990         if (tdq->tdq_ipipending)
991                 return;
992         cpu = td->td_sched->ts_cpu;
993         pri = td->td_priority;
994         ctd = pcpu_find(cpu)->pc_curthread;
995         if (!sched_shouldpreempt(pri, ctd->td_priority, 1))
996                 return;
997         if (TD_IS_IDLETHREAD(ctd)) {
998                 /*
999                  * If the MD code has an idle wakeup routine try that before
1000                  * falling back to IPI.
1001                  */
1002                 if (!tdq->tdq_cpu_idle || cpu_idle_wakeup(cpu))
1003                         return;
1004         }
1005         tdq->tdq_ipipending = 1;
1006         ipi_cpu(cpu, IPI_PREEMPT);
1007 }
1008
1009 /*
1010  * Steals load from a timeshare queue.  Honors the rotating queue head
1011  * index.
1012  */
1013 static struct thread *
1014 runq_steal_from(struct runq *rq, int cpu, u_char start)
1015 {
1016         struct rqbits *rqb;
1017         struct rqhead *rqh;
1018         struct thread *td, *first;
1019         int bit;
1020         int pri;
1021         int i;
1022
1023         rqb = &rq->rq_status;
1024         bit = start & (RQB_BPW -1);
1025         pri = 0;
1026         first = NULL;
1027 again:
1028         for (i = RQB_WORD(start); i < RQB_LEN; bit = 0, i++) {
1029                 if (rqb->rqb_bits[i] == 0)
1030                         continue;
1031                 if (bit != 0) {
1032                         for (pri = bit; pri < RQB_BPW; pri++)
1033                                 if (rqb->rqb_bits[i] & (1ul << pri))
1034                                         break;
1035                         if (pri >= RQB_BPW)
1036                                 continue;
1037                 } else
1038                         pri = RQB_FFS(rqb->rqb_bits[i]);
1039                 pri += (i << RQB_L2BPW);
1040                 rqh = &rq->rq_queues[pri];
1041                 TAILQ_FOREACH(td, rqh, td_runq) {
1042                         if (first && THREAD_CAN_MIGRATE(td) &&
1043                             THREAD_CAN_SCHED(td, cpu))
1044                                 return (td);
1045                         first = td;
1046                 }
1047         }
1048         if (start != 0) {
1049                 start = 0;
1050                 goto again;
1051         }
1052
1053         if (first && THREAD_CAN_MIGRATE(first) &&
1054             THREAD_CAN_SCHED(first, cpu))
1055                 return (first);
1056         return (NULL);
1057 }
1058
1059 /*
1060  * Steals load from a standard linear queue.
1061  */
1062 static struct thread *
1063 runq_steal(struct runq *rq, int cpu)
1064 {
1065         struct rqhead *rqh;
1066         struct rqbits *rqb;
1067         struct thread *td;
1068         int word;
1069         int bit;
1070
1071         rqb = &rq->rq_status;
1072         for (word = 0; word < RQB_LEN; word++) {
1073                 if (rqb->rqb_bits[word] == 0)
1074                         continue;
1075                 for (bit = 0; bit < RQB_BPW; bit++) {
1076                         if ((rqb->rqb_bits[word] & (1ul << bit)) == 0)
1077                                 continue;
1078                         rqh = &rq->rq_queues[bit + (word << RQB_L2BPW)];
1079                         TAILQ_FOREACH(td, rqh, td_runq)
1080                                 if (THREAD_CAN_MIGRATE(td) &&
1081                                     THREAD_CAN_SCHED(td, cpu))
1082                                         return (td);
1083                 }
1084         }
1085         return (NULL);
1086 }
1087
1088 /*
1089  * Attempt to steal a thread in priority order from a thread queue.
1090  */
1091 static struct thread *
1092 tdq_steal(struct tdq *tdq, int cpu)
1093 {
1094         struct thread *td;
1095
1096         TDQ_LOCK_ASSERT(tdq, MA_OWNED);
1097         if ((td = runq_steal(&tdq->tdq_realtime, cpu)) != NULL)
1098                 return (td);
1099         if ((td = runq_steal_from(&tdq->tdq_timeshare,
1100             cpu, tdq->tdq_ridx)) != NULL)
1101                 return (td);
1102         return (runq_steal(&tdq->tdq_idle, cpu));
1103 }
1104
1105 /*
1106  * Sets the thread lock and ts_cpu to match the requested cpu.  Unlocks the
1107  * current lock and returns with the assigned queue locked.
1108  */
1109 static inline struct tdq *
1110 sched_setcpu(struct thread *td, int cpu, int flags)
1111 {
1112
1113         struct tdq *tdq;
1114
1115         THREAD_LOCK_ASSERT(td, MA_OWNED);
1116         tdq = TDQ_CPU(cpu);
1117         td->td_sched->ts_cpu = cpu;
1118         /*
1119          * If the lock matches just return the queue.
1120          */
1121         if (td->td_lock == TDQ_LOCKPTR(tdq))
1122                 return (tdq);
1123 #ifdef notyet
1124         /*
1125          * If the thread isn't running its lockptr is a
1126          * turnstile or a sleepqueue.  We can just lock_set without
1127          * blocking.
1128          */
1129         if (TD_CAN_RUN(td)) {
1130                 TDQ_LOCK(tdq);
1131                 thread_lock_set(td, TDQ_LOCKPTR(tdq));
1132                 return (tdq);
1133         }
1134 #endif
1135         /*
1136          * The hard case, migration, we need to block the thread first to
1137          * prevent order reversals with other cpus locks.
1138          */
1139         spinlock_enter();
1140         thread_lock_block(td);
1141         TDQ_LOCK(tdq);
1142         thread_lock_unblock(td, TDQ_LOCKPTR(tdq));
1143         spinlock_exit();
1144         return (tdq);
1145 }
1146
1147 SCHED_STAT_DEFINE(pickcpu_intrbind, "Soft interrupt binding");
1148 SCHED_STAT_DEFINE(pickcpu_idle_affinity, "Picked idle cpu based on affinity");
1149 SCHED_STAT_DEFINE(pickcpu_affinity, "Picked cpu based on affinity");
1150 SCHED_STAT_DEFINE(pickcpu_lowest, "Selected lowest load");
1151 SCHED_STAT_DEFINE(pickcpu_local, "Migrated to current cpu");
1152 SCHED_STAT_DEFINE(pickcpu_migration, "Selection may have caused migration");
1153
1154 static int
1155 sched_pickcpu(struct thread *td, int flags)
1156 {
1157         struct cpu_group *cg, *ccg;
1158         struct td_sched *ts;
1159         struct tdq *tdq;
1160         cpuset_t mask;
1161         int cpu, pri, self;
1162
1163         self = PCPU_GET(cpuid);
1164         ts = td->td_sched;
1165         if (smp_started == 0)
1166                 return (self);
1167         /*
1168          * Don't migrate a running thread from sched_switch().
1169          */
1170         if ((flags & SRQ_OURSELF) || !THREAD_CAN_MIGRATE(td))
1171                 return (ts->ts_cpu);
1172         /*
1173          * Prefer to run interrupt threads on the processors that generate
1174          * the interrupt.
1175          */
1176         pri = td->td_priority;
1177         if (td->td_priority <= PRI_MAX_ITHD && THREAD_CAN_SCHED(td, self) &&
1178             curthread->td_intr_nesting_level && ts->ts_cpu != self) {
1179                 SCHED_STAT_INC(pickcpu_intrbind);
1180                 ts->ts_cpu = self;
1181                 if (TDQ_CPU(self)->tdq_lowpri > pri) {
1182                         SCHED_STAT_INC(pickcpu_affinity);
1183                         return (ts->ts_cpu);
1184                 }
1185         }
1186         /*
1187          * If the thread can run on the last cpu and the affinity has not
1188          * expired or it is idle run it there.
1189          */
1190         tdq = TDQ_CPU(ts->ts_cpu);
1191         cg = tdq->tdq_cg;
1192         if (THREAD_CAN_SCHED(td, ts->ts_cpu) &&
1193             tdq->tdq_lowpri >= PRI_MIN_IDLE &&
1194             SCHED_AFFINITY(ts, CG_SHARE_L2)) {
1195                 if (cg->cg_flags & CG_FLAG_THREAD) {
1196                         CPUSET_FOREACH(cpu, cg->cg_mask) {
1197                                 if (TDQ_CPU(cpu)->tdq_lowpri < PRI_MIN_IDLE)
1198                                         break;
1199                         }
1200                 } else
1201                         cpu = INT_MAX;
1202                 if (cpu > mp_maxid) {
1203                         SCHED_STAT_INC(pickcpu_idle_affinity);
1204                         return (ts->ts_cpu);
1205                 }
1206         }
1207         /*
1208          * Search for the last level cache CPU group in the tree.
1209          * Skip caches with expired affinity time and SMT groups.
1210          * Affinity to higher level caches will be handled less aggressively.
1211          */
1212         for (ccg = NULL; cg != NULL; cg = cg->cg_parent) {
1213                 if (cg->cg_flags & CG_FLAG_THREAD)
1214                         continue;
1215                 if (!SCHED_AFFINITY(ts, cg->cg_level))
1216                         continue;
1217                 ccg = cg;
1218         }
1219         if (ccg != NULL)
1220                 cg = ccg;
1221         cpu = -1;
1222         /* Search the group for the less loaded idle CPU we can run now. */
1223         mask = td->td_cpuset->cs_mask;
1224         if (cg != NULL && cg != cpu_top &&
1225             CPU_CMP(&cg->cg_mask, &cpu_top->cg_mask) != 0)
1226                 cpu = sched_lowest(cg, mask, max(pri, PRI_MAX_TIMESHARE),
1227                     INT_MAX, ts->ts_cpu);
1228         /* Search globally for the less loaded CPU we can run now. */
1229         if (cpu == -1)
1230                 cpu = sched_lowest(cpu_top, mask, pri, INT_MAX, ts->ts_cpu);
1231         /* Search globally for the less loaded CPU. */
1232         if (cpu == -1)
1233                 cpu = sched_lowest(cpu_top, mask, -1, INT_MAX, ts->ts_cpu);
1234         KASSERT(cpu != -1, ("sched_pickcpu: Failed to find a cpu."));
1235         /*
1236          * Compare the lowest loaded cpu to current cpu.
1237          */
1238         if (THREAD_CAN_SCHED(td, self) && TDQ_CPU(self)->tdq_lowpri > pri &&
1239             TDQ_CPU(cpu)->tdq_lowpri < PRI_MIN_IDLE &&
1240             TDQ_CPU(self)->tdq_load <= TDQ_CPU(cpu)->tdq_load + 1) {
1241                 SCHED_STAT_INC(pickcpu_local);
1242                 cpu = self;
1243         } else
1244                 SCHED_STAT_INC(pickcpu_lowest);
1245         if (cpu != ts->ts_cpu)
1246                 SCHED_STAT_INC(pickcpu_migration);
1247         return (cpu);
1248 }
1249 #endif
1250
1251 /*
1252  * Pick the highest priority task we have and return it.
1253  */
1254 static struct thread *
1255 tdq_choose(struct tdq *tdq)
1256 {
1257         struct thread *td;
1258
1259         TDQ_LOCK_ASSERT(tdq, MA_OWNED);
1260         td = runq_choose(&tdq->tdq_realtime);
1261         if (td != NULL)
1262                 return (td);
1263         td = runq_choose_from(&tdq->tdq_timeshare, tdq->tdq_ridx);
1264         if (td != NULL) {
1265                 KASSERT(td->td_priority >= PRI_MIN_BATCH,
1266                     ("tdq_choose: Invalid priority on timeshare queue %d",
1267                     td->td_priority));
1268                 return (td);
1269         }
1270         td = runq_choose(&tdq->tdq_idle);
1271         if (td != NULL) {
1272                 KASSERT(td->td_priority >= PRI_MIN_IDLE,
1273                     ("tdq_choose: Invalid priority on idle queue %d",
1274                     td->td_priority));
1275                 return (td);
1276         }
1277
1278         return (NULL);
1279 }
1280
1281 /*
1282  * Initialize a thread queue.
1283  */
1284 static void
1285 tdq_setup(struct tdq *tdq)
1286 {
1287
1288         if (bootverbose)
1289                 printf("ULE: setup cpu %d\n", TDQ_ID(tdq));
1290         runq_init(&tdq->tdq_realtime);
1291         runq_init(&tdq->tdq_timeshare);
1292         runq_init(&tdq->tdq_idle);
1293         snprintf(tdq->tdq_name, sizeof(tdq->tdq_name),
1294             "sched lock %d", (int)TDQ_ID(tdq));
1295         mtx_init(&tdq->tdq_lock, tdq->tdq_name, "sched lock",
1296             MTX_SPIN | MTX_RECURSE);
1297 #ifdef KTR
1298         snprintf(tdq->tdq_loadname, sizeof(tdq->tdq_loadname),
1299             "CPU %d load", (int)TDQ_ID(tdq));
1300 #endif
1301 }
1302
1303 #ifdef SMP
1304 static void
1305 sched_setup_smp(void)
1306 {
1307         struct tdq *tdq;
1308         int i;
1309
1310         cpu_top = smp_topo();
1311         CPU_FOREACH(i) {
1312                 tdq = TDQ_CPU(i);
1313                 tdq_setup(tdq);
1314                 tdq->tdq_cg = smp_topo_find(cpu_top, i);
1315                 if (tdq->tdq_cg == NULL)
1316                         panic("Can't find cpu group for %d\n", i);
1317         }
1318         balance_tdq = TDQ_SELF();
1319         sched_balance();
1320 }
1321 #endif
1322
1323 /*
1324  * Setup the thread queues and initialize the topology based on MD
1325  * information.
1326  */
1327 static void
1328 sched_setup(void *dummy)
1329 {
1330         struct tdq *tdq;
1331
1332         tdq = TDQ_SELF();
1333 #ifdef SMP
1334         sched_setup_smp();
1335 #else
1336         tdq_setup(tdq);
1337 #endif
1338         /*
1339          * To avoid divide-by-zero, we set realstathz a dummy value
1340          * in case which sched_clock() called before sched_initticks().
1341          */
1342         realstathz = hz;
1343         sched_slice = (realstathz/10);  /* ~100ms */
1344         tickincr = 1 << SCHED_TICK_SHIFT;
1345
1346         /* Add thread0's load since it's running. */
1347         TDQ_LOCK(tdq);
1348         thread0.td_lock = TDQ_LOCKPTR(TDQ_SELF());
1349         tdq_load_add(tdq, &thread0);
1350         tdq->tdq_lowpri = thread0.td_priority;
1351         TDQ_UNLOCK(tdq);
1352 }
1353
1354 /*
1355  * This routine determines the tickincr after stathz and hz are setup.
1356  */
1357 /* ARGSUSED */
1358 static void
1359 sched_initticks(void *dummy)
1360 {
1361         int incr;
1362
1363         realstathz = stathz ? stathz : hz;
1364         sched_slice = (realstathz/10);  /* ~100ms */
1365
1366         /*
1367          * tickincr is shifted out by 10 to avoid rounding errors due to
1368          * hz not being evenly divisible by stathz on all platforms.
1369          */
1370         incr = (hz << SCHED_TICK_SHIFT) / realstathz;
1371         /*
1372          * This does not work for values of stathz that are more than
1373          * 1 << SCHED_TICK_SHIFT * hz.  In practice this does not happen.
1374          */
1375         if (incr == 0)
1376                 incr = 1;
1377         tickincr = incr;
1378 #ifdef SMP
1379         /*
1380          * Set the default balance interval now that we know
1381          * what realstathz is.
1382          */
1383         balance_interval = realstathz;
1384         /*
1385          * Set steal thresh to roughly log2(mp_ncpu) but no greater than 4. 
1386          * This prevents excess thrashing on large machines and excess idle 
1387          * on smaller machines.
1388          */
1389         steal_thresh = min(fls(mp_ncpus) - 1, 3);
1390         affinity = SCHED_AFFINITY_DEFAULT;
1391 #endif
1392 }
1393
1394
1395 /*
1396  * This is the core of the interactivity algorithm.  Determines a score based
1397  * on past behavior.  It is the ratio of sleep time to run time scaled to
1398  * a [0, 100] integer.  This is the voluntary sleep time of a process, which
1399  * differs from the cpu usage because it does not account for time spent
1400  * waiting on a run-queue.  Would be prettier if we had floating point.
1401  */
1402 static int
1403 sched_interact_score(struct thread *td)
1404 {
1405         struct td_sched *ts;
1406         int div;
1407
1408         ts = td->td_sched;
1409         /*
1410          * The score is only needed if this is likely to be an interactive
1411          * task.  Don't go through the expense of computing it if there's
1412          * no chance.
1413          */
1414         if (sched_interact <= SCHED_INTERACT_HALF &&
1415                 ts->ts_runtime >= ts->ts_slptime)
1416                         return (SCHED_INTERACT_HALF);
1417
1418         if (ts->ts_runtime > ts->ts_slptime) {
1419                 div = max(1, ts->ts_runtime / SCHED_INTERACT_HALF);
1420                 return (SCHED_INTERACT_HALF +
1421                     (SCHED_INTERACT_HALF - (ts->ts_slptime / div)));
1422         }
1423         if (ts->ts_slptime > ts->ts_runtime) {
1424                 div = max(1, ts->ts_slptime / SCHED_INTERACT_HALF);
1425                 return (ts->ts_runtime / div);
1426         }
1427         /* runtime == slptime */
1428         if (ts->ts_runtime)
1429                 return (SCHED_INTERACT_HALF);
1430
1431         /*
1432          * This can happen if slptime and runtime are 0.
1433          */
1434         return (0);
1435
1436 }
1437
1438 /*
1439  * Scale the scheduling priority according to the "interactivity" of this
1440  * process.
1441  */
1442 static void
1443 sched_priority(struct thread *td)
1444 {
1445         int score;
1446         int pri;
1447
1448         if (PRI_BASE(td->td_pri_class) != PRI_TIMESHARE)
1449                 return;
1450         /*
1451          * If the score is interactive we place the thread in the realtime
1452          * queue with a priority that is less than kernel and interrupt
1453          * priorities.  These threads are not subject to nice restrictions.
1454          *
1455          * Scores greater than this are placed on the normal timeshare queue
1456          * where the priority is partially decided by the most recent cpu
1457          * utilization and the rest is decided by nice value.
1458          *
1459          * The nice value of the process has a linear effect on the calculated
1460          * score.  Negative nice values make it easier for a thread to be
1461          * considered interactive.
1462          */
1463         score = imax(0, sched_interact_score(td) + td->td_proc->p_nice);
1464         if (score < sched_interact) {
1465                 pri = PRI_MIN_INTERACT;
1466                 pri += ((PRI_MAX_INTERACT - PRI_MIN_INTERACT + 1) /
1467                     sched_interact) * score;
1468                 KASSERT(pri >= PRI_MIN_INTERACT && pri <= PRI_MAX_INTERACT,
1469                     ("sched_priority: invalid interactive priority %d score %d",
1470                     pri, score));
1471         } else {
1472                 pri = SCHED_PRI_MIN;
1473                 if (td->td_sched->ts_ticks)
1474                         pri += min(SCHED_PRI_TICKS(td->td_sched),
1475                             SCHED_PRI_RANGE);
1476                 pri += SCHED_PRI_NICE(td->td_proc->p_nice);
1477                 KASSERT(pri >= PRI_MIN_BATCH && pri <= PRI_MAX_BATCH,
1478                     ("sched_priority: invalid priority %d: nice %d, " 
1479                     "ticks %d ftick %d ltick %d tick pri %d",
1480                     pri, td->td_proc->p_nice, td->td_sched->ts_ticks,
1481                     td->td_sched->ts_ftick, td->td_sched->ts_ltick,
1482                     SCHED_PRI_TICKS(td->td_sched)));
1483         }
1484         sched_user_prio(td, pri);
1485
1486         return;
1487 }
1488
1489 /*
1490  * This routine enforces a maximum limit on the amount of scheduling history
1491  * kept.  It is called after either the slptime or runtime is adjusted.  This
1492  * function is ugly due to integer math.
1493  */
1494 static void
1495 sched_interact_update(struct thread *td)
1496 {
1497         struct td_sched *ts;
1498         u_int sum;
1499
1500         ts = td->td_sched;
1501         sum = ts->ts_runtime + ts->ts_slptime;
1502         if (sum < SCHED_SLP_RUN_MAX)
1503                 return;
1504         /*
1505          * This only happens from two places:
1506          * 1) We have added an unusual amount of run time from fork_exit.
1507          * 2) We have added an unusual amount of sleep time from sched_sleep().
1508          */
1509         if (sum > SCHED_SLP_RUN_MAX * 2) {
1510                 if (ts->ts_runtime > ts->ts_slptime) {
1511                         ts->ts_runtime = SCHED_SLP_RUN_MAX;
1512                         ts->ts_slptime = 1;
1513                 } else {
1514                         ts->ts_slptime = SCHED_SLP_RUN_MAX;
1515                         ts->ts_runtime = 1;
1516                 }
1517                 return;
1518         }
1519         /*
1520          * If we have exceeded by more than 1/5th then the algorithm below
1521          * will not bring us back into range.  Dividing by two here forces
1522          * us into the range of [4/5 * SCHED_INTERACT_MAX, SCHED_INTERACT_MAX]
1523          */
1524         if (sum > (SCHED_SLP_RUN_MAX / 5) * 6) {
1525                 ts->ts_runtime /= 2;
1526                 ts->ts_slptime /= 2;
1527                 return;
1528         }
1529         ts->ts_runtime = (ts->ts_runtime / 5) * 4;
1530         ts->ts_slptime = (ts->ts_slptime / 5) * 4;
1531 }
1532
1533 /*
1534  * Scale back the interactivity history when a child thread is created.  The
1535  * history is inherited from the parent but the thread may behave totally
1536  * differently.  For example, a shell spawning a compiler process.  We want
1537  * to learn that the compiler is behaving badly very quickly.
1538  */
1539 static void
1540 sched_interact_fork(struct thread *td)
1541 {
1542         int ratio;
1543         int sum;
1544
1545         sum = td->td_sched->ts_runtime + td->td_sched->ts_slptime;
1546         if (sum > SCHED_SLP_RUN_FORK) {
1547                 ratio = sum / SCHED_SLP_RUN_FORK;
1548                 td->td_sched->ts_runtime /= ratio;
1549                 td->td_sched->ts_slptime /= ratio;
1550         }
1551 }
1552
1553 /*
1554  * Called from proc0_init() to setup the scheduler fields.
1555  */
1556 void
1557 schedinit(void)
1558 {
1559
1560         /*
1561          * Set up the scheduler specific parts of proc0.
1562          */
1563         proc0.p_sched = NULL; /* XXX */
1564         thread0.td_sched = &td_sched0;
1565         td_sched0.ts_ltick = ticks;
1566         td_sched0.ts_ftick = ticks;
1567         td_sched0.ts_slice = sched_slice;
1568 }
1569
1570 /*
1571  * This is only somewhat accurate since given many processes of the same
1572  * priority they will switch when their slices run out, which will be
1573  * at most sched_slice stathz ticks.
1574  */
1575 int
1576 sched_rr_interval(void)
1577 {
1578
1579         /* Convert sched_slice to hz */
1580         return (hz/(realstathz/sched_slice));
1581 }
1582
1583 /*
1584  * Update the percent cpu tracking information when it is requested or
1585  * the total history exceeds the maximum.  We keep a sliding history of
1586  * tick counts that slowly decays.  This is less precise than the 4BSD
1587  * mechanism since it happens with less regular and frequent events.
1588  */
1589 static void
1590 sched_pctcpu_update(struct td_sched *ts, int run)
1591 {
1592         int t = ticks;
1593
1594         if (t - ts->ts_ltick >= SCHED_TICK_TARG) {
1595                 ts->ts_ticks = 0;
1596                 ts->ts_ftick = t - SCHED_TICK_TARG;
1597         } else if (t - ts->ts_ftick >= SCHED_TICK_MAX) {
1598                 ts->ts_ticks = (ts->ts_ticks / (ts->ts_ltick - ts->ts_ftick)) *
1599                     (ts->ts_ltick - (t - SCHED_TICK_TARG));
1600                 ts->ts_ftick = t - SCHED_TICK_TARG;
1601         }
1602         if (run)
1603                 ts->ts_ticks += (t - ts->ts_ltick) << SCHED_TICK_SHIFT;
1604         ts->ts_ltick = t;
1605 }
1606
1607 /*
1608  * Adjust the priority of a thread.  Move it to the appropriate run-queue
1609  * if necessary.  This is the back-end for several priority related
1610  * functions.
1611  */
1612 static void
1613 sched_thread_priority(struct thread *td, u_char prio)
1614 {
1615         struct td_sched *ts;
1616         struct tdq *tdq;
1617         int oldpri;
1618
1619         KTR_POINT3(KTR_SCHED, "thread", sched_tdname(td), "prio",
1620             "prio:%d", td->td_priority, "new prio:%d", prio,
1621             KTR_ATTR_LINKED, sched_tdname(curthread));
1622         if (td != curthread && prio > td->td_priority) {
1623                 KTR_POINT3(KTR_SCHED, "thread", sched_tdname(curthread),
1624                     "lend prio", "prio:%d", td->td_priority, "new prio:%d",
1625                     prio, KTR_ATTR_LINKED, sched_tdname(td));
1626         } 
1627         ts = td->td_sched;
1628         THREAD_LOCK_ASSERT(td, MA_OWNED);
1629         if (td->td_priority == prio)
1630                 return;
1631         /*
1632          * If the priority has been elevated due to priority
1633          * propagation, we may have to move ourselves to a new
1634          * queue.  This could be optimized to not re-add in some
1635          * cases.
1636          */
1637         if (TD_ON_RUNQ(td) && prio < td->td_priority) {
1638                 sched_rem(td);
1639                 td->td_priority = prio;
1640                 sched_add(td, SRQ_BORROWING);
1641                 return;
1642         }
1643         /*
1644          * If the thread is currently running we may have to adjust the lowpri
1645          * information so other cpus are aware of our current priority.
1646          */
1647         if (TD_IS_RUNNING(td)) {
1648                 tdq = TDQ_CPU(ts->ts_cpu);
1649                 oldpri = td->td_priority;
1650                 td->td_priority = prio;
1651                 if (prio < tdq->tdq_lowpri)
1652                         tdq->tdq_lowpri = prio;
1653                 else if (tdq->tdq_lowpri == oldpri)
1654                         tdq_setlowpri(tdq, td);
1655                 return;
1656         }
1657         td->td_priority = prio;
1658 }
1659
1660 /*
1661  * Update a thread's priority when it is lent another thread's
1662  * priority.
1663  */
1664 void
1665 sched_lend_prio(struct thread *td, u_char prio)
1666 {
1667
1668         td->td_flags |= TDF_BORROWING;
1669         sched_thread_priority(td, prio);
1670 }
1671
1672 /*
1673  * Restore a thread's priority when priority propagation is
1674  * over.  The prio argument is the minimum priority the thread
1675  * needs to have to satisfy other possible priority lending
1676  * requests.  If the thread's regular priority is less
1677  * important than prio, the thread will keep a priority boost
1678  * of prio.
1679  */
1680 void
1681 sched_unlend_prio(struct thread *td, u_char prio)
1682 {
1683         u_char base_pri;
1684
1685         if (td->td_base_pri >= PRI_MIN_TIMESHARE &&
1686             td->td_base_pri <= PRI_MAX_TIMESHARE)
1687                 base_pri = td->td_user_pri;
1688         else
1689                 base_pri = td->td_base_pri;
1690         if (prio >= base_pri) {
1691                 td->td_flags &= ~TDF_BORROWING;
1692                 sched_thread_priority(td, base_pri);
1693         } else
1694                 sched_lend_prio(td, prio);
1695 }
1696
1697 /*
1698  * Standard entry for setting the priority to an absolute value.
1699  */
1700 void
1701 sched_prio(struct thread *td, u_char prio)
1702 {
1703         u_char oldprio;
1704
1705         /* First, update the base priority. */
1706         td->td_base_pri = prio;
1707
1708         /*
1709          * If the thread is borrowing another thread's priority, don't
1710          * ever lower the priority.
1711          */
1712         if (td->td_flags & TDF_BORROWING && td->td_priority < prio)
1713                 return;
1714
1715         /* Change the real priority. */
1716         oldprio = td->td_priority;
1717         sched_thread_priority(td, prio);
1718
1719         /*
1720          * If the thread is on a turnstile, then let the turnstile update
1721          * its state.
1722          */
1723         if (TD_ON_LOCK(td) && oldprio != prio)
1724                 turnstile_adjust(td, oldprio);
1725 }
1726
1727 /*
1728  * Set the base user priority, does not effect current running priority.
1729  */
1730 void
1731 sched_user_prio(struct thread *td, u_char prio)
1732 {
1733
1734         td->td_base_user_pri = prio;
1735         if (td->td_lend_user_pri <= prio)
1736                 return;
1737         td->td_user_pri = prio;
1738 }
1739
1740 void
1741 sched_lend_user_prio(struct thread *td, u_char prio)
1742 {
1743
1744         THREAD_LOCK_ASSERT(td, MA_OWNED);
1745         td->td_lend_user_pri = prio;
1746         td->td_user_pri = min(prio, td->td_base_user_pri);
1747         if (td->td_priority > td->td_user_pri)
1748                 sched_prio(td, td->td_user_pri);
1749         else if (td->td_priority != td->td_user_pri)
1750                 td->td_flags |= TDF_NEEDRESCHED;
1751 }
1752
1753 /*
1754  * Handle migration from sched_switch().  This happens only for
1755  * cpu binding.
1756  */
1757 static struct mtx *
1758 sched_switch_migrate(struct tdq *tdq, struct thread *td, int flags)
1759 {
1760         struct tdq *tdn;
1761
1762         tdn = TDQ_CPU(td->td_sched->ts_cpu);
1763 #ifdef SMP
1764         tdq_load_rem(tdq, td);
1765         /*
1766          * Do the lock dance required to avoid LOR.  We grab an extra
1767          * spinlock nesting to prevent preemption while we're
1768          * not holding either run-queue lock.
1769          */
1770         spinlock_enter();
1771         thread_lock_block(td);  /* This releases the lock on tdq. */
1772
1773         /*
1774          * Acquire both run-queue locks before placing the thread on the new
1775          * run-queue to avoid deadlocks created by placing a thread with a
1776          * blocked lock on the run-queue of a remote processor.  The deadlock
1777          * occurs when a third processor attempts to lock the two queues in
1778          * question while the target processor is spinning with its own
1779          * run-queue lock held while waiting for the blocked lock to clear.
1780          */
1781         tdq_lock_pair(tdn, tdq);
1782         tdq_add(tdn, td, flags);
1783         tdq_notify(tdn, td);
1784         TDQ_UNLOCK(tdn);
1785         spinlock_exit();
1786 #endif
1787         return (TDQ_LOCKPTR(tdn));
1788 }
1789
1790 /*
1791  * Variadic version of thread_lock_unblock() that does not assume td_lock
1792  * is blocked.
1793  */
1794 static inline void
1795 thread_unblock_switch(struct thread *td, struct mtx *mtx)
1796 {
1797         atomic_store_rel_ptr((volatile uintptr_t *)&td->td_lock,
1798             (uintptr_t)mtx);
1799 }
1800
1801 /*
1802  * Switch threads.  This function has to handle threads coming in while
1803  * blocked for some reason, running, or idle.  It also must deal with
1804  * migrating a thread from one queue to another as running threads may
1805  * be assigned elsewhere via binding.
1806  */
1807 void
1808 sched_switch(struct thread *td, struct thread *newtd, int flags)
1809 {
1810         struct tdq *tdq;
1811         struct td_sched *ts;
1812         struct mtx *mtx;
1813         int srqflag;
1814         int cpuid;
1815
1816         THREAD_LOCK_ASSERT(td, MA_OWNED);
1817         KASSERT(newtd == NULL, ("sched_switch: Unsupported newtd argument"));
1818
1819         cpuid = PCPU_GET(cpuid);
1820         tdq = TDQ_CPU(cpuid);
1821         ts = td->td_sched;
1822         mtx = td->td_lock;
1823         sched_pctcpu_update(ts, 1);
1824         ts->ts_rltick = ticks;
1825         td->td_lastcpu = td->td_oncpu;
1826         td->td_oncpu = NOCPU;
1827         if (!(flags & SW_PREEMPT))
1828                 td->td_flags &= ~TDF_NEEDRESCHED;
1829         td->td_owepreempt = 0;
1830         tdq->tdq_switchcnt++;
1831         /*
1832          * The lock pointer in an idle thread should never change.  Reset it
1833          * to CAN_RUN as well.
1834          */
1835         if (TD_IS_IDLETHREAD(td)) {
1836                 MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1837                 TD_SET_CAN_RUN(td);
1838         } else if (TD_IS_RUNNING(td)) {
1839                 MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1840                 srqflag = (flags & SW_PREEMPT) ?
1841                     SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
1842                     SRQ_OURSELF|SRQ_YIELDING;
1843 #ifdef SMP
1844                 if (THREAD_CAN_MIGRATE(td) && !THREAD_CAN_SCHED(td, ts->ts_cpu))
1845                         ts->ts_cpu = sched_pickcpu(td, 0);
1846 #endif
1847                 if (ts->ts_cpu == cpuid)
1848                         tdq_runq_add(tdq, td, srqflag);
1849                 else {
1850                         KASSERT(THREAD_CAN_MIGRATE(td) ||
1851                             (ts->ts_flags & TSF_BOUND) != 0,
1852                             ("Thread %p shouldn't migrate", td));
1853                         mtx = sched_switch_migrate(tdq, td, srqflag);
1854                 }
1855         } else {
1856                 /* This thread must be going to sleep. */
1857                 TDQ_LOCK(tdq);
1858                 mtx = thread_lock_block(td);
1859                 tdq_load_rem(tdq, td);
1860         }
1861         /*
1862          * We enter here with the thread blocked and assigned to the
1863          * appropriate cpu run-queue or sleep-queue and with the current
1864          * thread-queue locked.
1865          */
1866         TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
1867         newtd = choosethread();
1868         /*
1869          * Call the MD code to switch contexts if necessary.
1870          */
1871         if (td != newtd) {
1872 #ifdef  HWPMC_HOOKS
1873                 if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1874                         PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
1875 #endif
1876                 lock_profile_release_lock(&TDQ_LOCKPTR(tdq)->lock_object);
1877                 TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)newtd;
1878                 sched_pctcpu_update(newtd->td_sched, 0);
1879
1880 #ifdef KDTRACE_HOOKS
1881                 /*
1882                  * If DTrace has set the active vtime enum to anything
1883                  * other than INACTIVE (0), then it should have set the
1884                  * function to call.
1885                  */
1886                 if (dtrace_vtime_active)
1887                         (*dtrace_vtime_switch_func)(newtd);
1888 #endif
1889
1890                 cpu_switch(td, newtd, mtx);
1891                 /*
1892                  * We may return from cpu_switch on a different cpu.  However,
1893                  * we always return with td_lock pointing to the current cpu's
1894                  * run queue lock.
1895                  */
1896                 cpuid = PCPU_GET(cpuid);
1897                 tdq = TDQ_CPU(cpuid);
1898                 lock_profile_obtain_lock_success(
1899                     &TDQ_LOCKPTR(tdq)->lock_object, 0, 0, __FILE__, __LINE__);
1900 #ifdef  HWPMC_HOOKS
1901                 if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1902                         PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_IN);
1903 #endif
1904         } else
1905                 thread_unblock_switch(td, mtx);
1906         /*
1907          * Assert that all went well and return.
1908          */
1909         TDQ_LOCK_ASSERT(tdq, MA_OWNED|MA_NOTRECURSED);
1910         MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1911         td->td_oncpu = cpuid;
1912 }
1913
1914 /*
1915  * Adjust thread priorities as a result of a nice request.
1916  */
1917 void
1918 sched_nice(struct proc *p, int nice)
1919 {
1920         struct thread *td;
1921
1922         PROC_LOCK_ASSERT(p, MA_OWNED);
1923
1924         p->p_nice = nice;
1925         FOREACH_THREAD_IN_PROC(p, td) {
1926                 thread_lock(td);
1927                 sched_priority(td);
1928                 sched_prio(td, td->td_base_user_pri);
1929                 thread_unlock(td);
1930         }
1931 }
1932
1933 /*
1934  * Record the sleep time for the interactivity scorer.
1935  */
1936 void
1937 sched_sleep(struct thread *td, int prio)
1938 {
1939
1940         THREAD_LOCK_ASSERT(td, MA_OWNED);
1941
1942         td->td_slptick = ticks;
1943         if (TD_IS_SUSPENDED(td) || prio >= PSOCK)
1944                 td->td_flags |= TDF_CANSWAP;
1945         if (PRI_BASE(td->td_pri_class) != PRI_TIMESHARE)
1946                 return;
1947         if (static_boost == 1 && prio)
1948                 sched_prio(td, prio);
1949         else if (static_boost && td->td_priority > static_boost)
1950                 sched_prio(td, static_boost);
1951 }
1952
1953 /*
1954  * Schedule a thread to resume execution and record how long it voluntarily
1955  * slept.  We also update the pctcpu, interactivity, and priority.
1956  */
1957 void
1958 sched_wakeup(struct thread *td)
1959 {
1960         struct td_sched *ts;
1961         int slptick;
1962
1963         THREAD_LOCK_ASSERT(td, MA_OWNED);
1964         ts = td->td_sched;
1965         td->td_flags &= ~TDF_CANSWAP;
1966         /*
1967          * If we slept for more than a tick update our interactivity and
1968          * priority.
1969          */
1970         slptick = td->td_slptick;
1971         td->td_slptick = 0;
1972         if (slptick && slptick != ticks) {
1973                 ts->ts_slptime += (ticks - slptick) << SCHED_TICK_SHIFT;
1974                 sched_interact_update(td);
1975                 sched_pctcpu_update(ts, 0);
1976         }
1977         /* Reset the slice value after we sleep. */
1978         ts->ts_slice = sched_slice;
1979         sched_add(td, SRQ_BORING);
1980 }
1981
1982 /*
1983  * Penalize the parent for creating a new child and initialize the child's
1984  * priority.
1985  */
1986 void
1987 sched_fork(struct thread *td, struct thread *child)
1988 {
1989         THREAD_LOCK_ASSERT(td, MA_OWNED);
1990         sched_pctcpu_update(td->td_sched, 1);
1991         sched_fork_thread(td, child);
1992         /*
1993          * Penalize the parent and child for forking.
1994          */
1995         sched_interact_fork(child);
1996         sched_priority(child);
1997         td->td_sched->ts_runtime += tickincr;
1998         sched_interact_update(td);
1999         sched_priority(td);
2000 }
2001
2002 /*
2003  * Fork a new thread, may be within the same process.
2004  */
2005 void
2006 sched_fork_thread(struct thread *td, struct thread *child)
2007 {
2008         struct td_sched *ts;
2009         struct td_sched *ts2;
2010
2011         THREAD_LOCK_ASSERT(td, MA_OWNED);
2012         /*
2013          * Initialize child.
2014          */
2015         ts = td->td_sched;
2016         ts2 = child->td_sched;
2017         child->td_lock = TDQ_LOCKPTR(TDQ_SELF());
2018         child->td_cpuset = cpuset_ref(td->td_cpuset);
2019         ts2->ts_cpu = ts->ts_cpu;
2020         ts2->ts_flags = 0;
2021         /*
2022          * Grab our parents cpu estimation information.
2023          */
2024         ts2->ts_ticks = ts->ts_ticks;
2025         ts2->ts_ltick = ts->ts_ltick;
2026         ts2->ts_ftick = ts->ts_ftick;
2027         /*
2028          * Do not inherit any borrowed priority from the parent.
2029          */
2030         child->td_priority = child->td_base_pri;
2031         /*
2032          * And update interactivity score.
2033          */
2034         ts2->ts_slptime = ts->ts_slptime;
2035         ts2->ts_runtime = ts->ts_runtime;
2036         ts2->ts_slice = 1;      /* Attempt to quickly learn interactivity. */
2037 #ifdef KTR
2038         bzero(ts2->ts_name, sizeof(ts2->ts_name));
2039 #endif
2040 }
2041
2042 /*
2043  * Adjust the priority class of a thread.
2044  */
2045 void
2046 sched_class(struct thread *td, int class)
2047 {
2048
2049         THREAD_LOCK_ASSERT(td, MA_OWNED);
2050         if (td->td_pri_class == class)
2051                 return;
2052         td->td_pri_class = class;
2053 }
2054
2055 /*
2056  * Return some of the child's priority and interactivity to the parent.
2057  */
2058 void
2059 sched_exit(struct proc *p, struct thread *child)
2060 {
2061         struct thread *td;
2062
2063         KTR_STATE1(KTR_SCHED, "thread", sched_tdname(child), "proc exit",
2064             "prio:%d", child->td_priority);
2065         PROC_LOCK_ASSERT(p, MA_OWNED);
2066         td = FIRST_THREAD_IN_PROC(p);
2067         sched_exit_thread(td, child);
2068 }
2069
2070 /*
2071  * Penalize another thread for the time spent on this one.  This helps to
2072  * worsen the priority and interactivity of processes which schedule batch
2073  * jobs such as make.  This has little effect on the make process itself but
2074  * causes new processes spawned by it to receive worse scores immediately.
2075  */
2076 void
2077 sched_exit_thread(struct thread *td, struct thread *child)
2078 {
2079
2080         KTR_STATE1(KTR_SCHED, "thread", sched_tdname(child), "thread exit",
2081             "prio:%d", child->td_priority);
2082         /*
2083          * Give the child's runtime to the parent without returning the
2084          * sleep time as a penalty to the parent.  This causes shells that
2085          * launch expensive things to mark their children as expensive.
2086          */
2087         thread_lock(td);
2088         td->td_sched->ts_runtime += child->td_sched->ts_runtime;
2089         sched_interact_update(td);
2090         sched_priority(td);
2091         thread_unlock(td);
2092 }
2093
2094 void
2095 sched_preempt(struct thread *td)
2096 {
2097         struct tdq *tdq;
2098
2099         thread_lock(td);
2100         tdq = TDQ_SELF();
2101         TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2102         tdq->tdq_ipipending = 0;
2103         if (td->td_priority > tdq->tdq_lowpri) {
2104                 int flags;
2105
2106                 flags = SW_INVOL | SW_PREEMPT;
2107                 if (td->td_critnest > 1)
2108                         td->td_owepreempt = 1;
2109                 else if (TD_IS_IDLETHREAD(td))
2110                         mi_switch(flags | SWT_REMOTEWAKEIDLE, NULL);
2111                 else
2112                         mi_switch(flags | SWT_REMOTEPREEMPT, NULL);
2113         }
2114         thread_unlock(td);
2115 }
2116
2117 /*
2118  * Fix priorities on return to user-space.  Priorities may be elevated due
2119  * to static priorities in msleep() or similar.
2120  */
2121 void
2122 sched_userret(struct thread *td)
2123 {
2124         /*
2125          * XXX we cheat slightly on the locking here to avoid locking in  
2126          * the usual case.  Setting td_priority here is essentially an
2127          * incomplete workaround for not setting it properly elsewhere.
2128          * Now that some interrupt handlers are threads, not setting it
2129          * properly elsewhere can clobber it in the window between setting
2130          * it here and returning to user mode, so don't waste time setting
2131          * it perfectly here.
2132          */
2133         KASSERT((td->td_flags & TDF_BORROWING) == 0,
2134             ("thread with borrowed priority returning to userland"));
2135         if (td->td_priority != td->td_user_pri) {
2136                 thread_lock(td);
2137                 td->td_priority = td->td_user_pri;
2138                 td->td_base_pri = td->td_user_pri;
2139                 tdq_setlowpri(TDQ_SELF(), td);
2140                 thread_unlock(td);
2141         }
2142 }
2143
2144 /*
2145  * Handle a stathz tick.  This is really only relevant for timeshare
2146  * threads.
2147  */
2148 void
2149 sched_clock(struct thread *td)
2150 {
2151         struct tdq *tdq;
2152         struct td_sched *ts;
2153
2154         THREAD_LOCK_ASSERT(td, MA_OWNED);
2155         tdq = TDQ_SELF();
2156 #ifdef SMP
2157         /*
2158          * We run the long term load balancer infrequently on the first cpu.
2159          */
2160         if (balance_tdq == tdq) {
2161                 if (balance_ticks && --balance_ticks == 0)
2162                         sched_balance();
2163         }
2164 #endif
2165         /*
2166          * Save the old switch count so we have a record of the last ticks
2167          * activity.   Initialize the new switch count based on our load.
2168          * If there is some activity seed it to reflect that.
2169          */
2170         tdq->tdq_oldswitchcnt = tdq->tdq_switchcnt;
2171         tdq->tdq_switchcnt = tdq->tdq_load;
2172         /*
2173          * Advance the insert index once for each tick to ensure that all
2174          * threads get a chance to run.
2175          */
2176         if (tdq->tdq_idx == tdq->tdq_ridx) {
2177                 tdq->tdq_idx = (tdq->tdq_idx + 1) % RQ_NQS;
2178                 if (TAILQ_EMPTY(&tdq->tdq_timeshare.rq_queues[tdq->tdq_ridx]))
2179                         tdq->tdq_ridx = tdq->tdq_idx;
2180         }
2181         ts = td->td_sched;
2182         sched_pctcpu_update(ts, 1);
2183         if (td->td_pri_class & PRI_FIFO_BIT)
2184                 return;
2185         if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE) {
2186                 /*
2187                  * We used a tick; charge it to the thread so
2188                  * that we can compute our interactivity.
2189                  */
2190                 td->td_sched->ts_runtime += tickincr;
2191                 sched_interact_update(td);
2192                 sched_priority(td);
2193         }
2194         /*
2195          * We used up one time slice.
2196          */
2197         if (--ts->ts_slice > 0)
2198                 return;
2199         /*
2200          * We're out of time, force a requeue at userret().
2201          */
2202         ts->ts_slice = sched_slice;
2203         td->td_flags |= TDF_NEEDRESCHED;
2204 }
2205
2206 /*
2207  * Called once per hz tick.
2208  */
2209 void
2210 sched_tick(int cnt)
2211 {
2212
2213 }
2214
2215 /*
2216  * Return whether the current CPU has runnable tasks.  Used for in-kernel
2217  * cooperative idle threads.
2218  */
2219 int
2220 sched_runnable(void)
2221 {
2222         struct tdq *tdq;
2223         int load;
2224
2225         load = 1;
2226
2227         tdq = TDQ_SELF();
2228         if ((curthread->td_flags & TDF_IDLETD) != 0) {
2229                 if (tdq->tdq_load > 0)
2230                         goto out;
2231         } else
2232                 if (tdq->tdq_load - 1 > 0)
2233                         goto out;
2234         load = 0;
2235 out:
2236         return (load);
2237 }
2238
2239 /*
2240  * Choose the highest priority thread to run.  The thread is removed from
2241  * the run-queue while running however the load remains.  For SMP we set
2242  * the tdq in the global idle bitmask if it idles here.
2243  */
2244 struct thread *
2245 sched_choose(void)
2246 {
2247         struct thread *td;
2248         struct tdq *tdq;
2249
2250         tdq = TDQ_SELF();
2251         TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2252         td = tdq_choose(tdq);
2253         if (td) {
2254                 tdq_runq_rem(tdq, td);
2255                 tdq->tdq_lowpri = td->td_priority;
2256                 return (td);
2257         }
2258         tdq->tdq_lowpri = PRI_MAX_IDLE;
2259         return (PCPU_GET(idlethread));
2260 }
2261
2262 /*
2263  * Set owepreempt if necessary.  Preemption never happens directly in ULE,
2264  * we always request it once we exit a critical section.
2265  */
2266 static inline void
2267 sched_setpreempt(struct thread *td)
2268 {
2269         struct thread *ctd;
2270         int cpri;
2271         int pri;
2272
2273         THREAD_LOCK_ASSERT(curthread, MA_OWNED);
2274
2275         ctd = curthread;
2276         pri = td->td_priority;
2277         cpri = ctd->td_priority;
2278         if (pri < cpri)
2279                 ctd->td_flags |= TDF_NEEDRESCHED;
2280         if (panicstr != NULL || pri >= cpri || cold || TD_IS_INHIBITED(ctd))
2281                 return;
2282         if (!sched_shouldpreempt(pri, cpri, 0))
2283                 return;
2284         ctd->td_owepreempt = 1;
2285 }
2286
2287 /*
2288  * Add a thread to a thread queue.  Select the appropriate runq and add the
2289  * thread to it.  This is the internal function called when the tdq is
2290  * predetermined.
2291  */
2292 void
2293 tdq_add(struct tdq *tdq, struct thread *td, int flags)
2294 {
2295
2296         TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2297         KASSERT((td->td_inhibitors == 0),
2298             ("sched_add: trying to run inhibited thread"));
2299         KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
2300             ("sched_add: bad thread state"));
2301         KASSERT(td->td_flags & TDF_INMEM,
2302             ("sched_add: thread swapped out"));
2303
2304         if (td->td_priority < tdq->tdq_lowpri)
2305                 tdq->tdq_lowpri = td->td_priority;
2306         tdq_runq_add(tdq, td, flags);
2307         tdq_load_add(tdq, td);
2308 }
2309
2310 /*
2311  * Select the target thread queue and add a thread to it.  Request
2312  * preemption or IPI a remote processor if required.
2313  */
2314 void
2315 sched_add(struct thread *td, int flags)
2316 {
2317         struct tdq *tdq;
2318 #ifdef SMP
2319         int cpu;
2320 #endif
2321
2322         KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq add",
2323             "prio:%d", td->td_priority, KTR_ATTR_LINKED,
2324             sched_tdname(curthread));
2325         KTR_POINT1(KTR_SCHED, "thread", sched_tdname(curthread), "wokeup",
2326             KTR_ATTR_LINKED, sched_tdname(td));
2327         THREAD_LOCK_ASSERT(td, MA_OWNED);
2328         /*
2329          * Recalculate the priority before we select the target cpu or
2330          * run-queue.
2331          */
2332         if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE)
2333                 sched_priority(td);
2334 #ifdef SMP
2335         /*
2336          * Pick the destination cpu and if it isn't ours transfer to the
2337          * target cpu.
2338          */
2339         cpu = sched_pickcpu(td, flags);
2340         tdq = sched_setcpu(td, cpu, flags);
2341         tdq_add(tdq, td, flags);
2342         if (cpu != PCPU_GET(cpuid)) {
2343                 tdq_notify(tdq, td);
2344                 return;
2345         }
2346 #else
2347         tdq = TDQ_SELF();
2348         TDQ_LOCK(tdq);
2349         /*
2350          * Now that the thread is moving to the run-queue, set the lock
2351          * to the scheduler's lock.
2352          */
2353         thread_lock_set(td, TDQ_LOCKPTR(tdq));
2354         tdq_add(tdq, td, flags);
2355 #endif
2356         if (!(flags & SRQ_YIELDING))
2357                 sched_setpreempt(td);
2358 }
2359
2360 /*
2361  * Remove a thread from a run-queue without running it.  This is used
2362  * when we're stealing a thread from a remote queue.  Otherwise all threads
2363  * exit by calling sched_exit_thread() and sched_throw() themselves.
2364  */
2365 void
2366 sched_rem(struct thread *td)
2367 {
2368         struct tdq *tdq;
2369
2370         KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "runq rem",
2371             "prio:%d", td->td_priority);
2372         tdq = TDQ_CPU(td->td_sched->ts_cpu);
2373         TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2374         MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2375         KASSERT(TD_ON_RUNQ(td),
2376             ("sched_rem: thread not on run queue"));
2377         tdq_runq_rem(tdq, td);
2378         tdq_load_rem(tdq, td);
2379         TD_SET_CAN_RUN(td);
2380         if (td->td_priority == tdq->tdq_lowpri)
2381                 tdq_setlowpri(tdq, NULL);
2382 }
2383
2384 /*
2385  * Fetch cpu utilization information.  Updates on demand.
2386  */
2387 fixpt_t
2388 sched_pctcpu(struct thread *td)
2389 {
2390         fixpt_t pctcpu;
2391         struct td_sched *ts;
2392
2393         pctcpu = 0;
2394         ts = td->td_sched;
2395         if (ts == NULL)
2396                 return (0);
2397
2398         THREAD_LOCK_ASSERT(td, MA_OWNED);
2399         sched_pctcpu_update(ts, TD_IS_RUNNING(td));
2400         if (ts->ts_ticks) {
2401                 int rtick;
2402
2403                 /* How many rtick per second ? */
2404                 rtick = min(SCHED_TICK_HZ(ts) / SCHED_TICK_SECS, hz);
2405                 pctcpu = (FSCALE * ((FSCALE * rtick)/hz)) >> FSHIFT;
2406         }
2407
2408         return (pctcpu);
2409 }
2410
2411 /*
2412  * Enforce affinity settings for a thread.  Called after adjustments to
2413  * cpumask.
2414  */
2415 void
2416 sched_affinity(struct thread *td)
2417 {
2418 #ifdef SMP
2419         struct td_sched *ts;
2420
2421         THREAD_LOCK_ASSERT(td, MA_OWNED);
2422         ts = td->td_sched;
2423         if (THREAD_CAN_SCHED(td, ts->ts_cpu))
2424                 return;
2425         if (TD_ON_RUNQ(td)) {
2426                 sched_rem(td);
2427                 sched_add(td, SRQ_BORING);
2428                 return;
2429         }
2430         if (!TD_IS_RUNNING(td))
2431                 return;
2432         /*
2433          * Force a switch before returning to userspace.  If the
2434          * target thread is not running locally send an ipi to force
2435          * the issue.
2436          */
2437         td->td_flags |= TDF_NEEDRESCHED;
2438         if (td != curthread)
2439                 ipi_cpu(ts->ts_cpu, IPI_PREEMPT);
2440 #endif
2441 }
2442
2443 /*
2444  * Bind a thread to a target cpu.
2445  */
2446 void
2447 sched_bind(struct thread *td, int cpu)
2448 {
2449         struct td_sched *ts;
2450
2451         THREAD_LOCK_ASSERT(td, MA_OWNED|MA_NOTRECURSED);
2452         KASSERT(td == curthread, ("sched_bind: can only bind curthread"));
2453         ts = td->td_sched;
2454         if (ts->ts_flags & TSF_BOUND)
2455                 sched_unbind(td);
2456         KASSERT(THREAD_CAN_MIGRATE(td), ("%p must be migratable", td));
2457         ts->ts_flags |= TSF_BOUND;
2458         sched_pin();
2459         if (PCPU_GET(cpuid) == cpu)
2460                 return;
2461         ts->ts_cpu = cpu;
2462         /* When we return from mi_switch we'll be on the correct cpu. */
2463         mi_switch(SW_VOL, NULL);
2464 }
2465
2466 /*
2467  * Release a bound thread.
2468  */
2469 void
2470 sched_unbind(struct thread *td)
2471 {
2472         struct td_sched *ts;
2473
2474         THREAD_LOCK_ASSERT(td, MA_OWNED);
2475         KASSERT(td == curthread, ("sched_unbind: can only bind curthread"));
2476         ts = td->td_sched;
2477         if ((ts->ts_flags & TSF_BOUND) == 0)
2478                 return;
2479         ts->ts_flags &= ~TSF_BOUND;
2480         sched_unpin();
2481 }
2482
2483 int
2484 sched_is_bound(struct thread *td)
2485 {
2486         THREAD_LOCK_ASSERT(td, MA_OWNED);
2487         return (td->td_sched->ts_flags & TSF_BOUND);
2488 }
2489
2490 /*
2491  * Basic yield call.
2492  */
2493 void
2494 sched_relinquish(struct thread *td)
2495 {
2496         thread_lock(td);
2497         mi_switch(SW_VOL | SWT_RELINQUISH, NULL);
2498         thread_unlock(td);
2499 }
2500
2501 /*
2502  * Return the total system load.
2503  */
2504 int
2505 sched_load(void)
2506 {
2507 #ifdef SMP
2508         int total;
2509         int i;
2510
2511         total = 0;
2512         CPU_FOREACH(i)
2513                 total += TDQ_CPU(i)->tdq_sysload;
2514         return (total);
2515 #else
2516         return (TDQ_SELF()->tdq_sysload);
2517 #endif
2518 }
2519
2520 int
2521 sched_sizeof_proc(void)
2522 {
2523         return (sizeof(struct proc));
2524 }
2525
2526 int
2527 sched_sizeof_thread(void)
2528 {
2529         return (sizeof(struct thread) + sizeof(struct td_sched));
2530 }
2531
2532 #ifdef SMP
2533 #define TDQ_IDLESPIN(tdq)                                               \
2534     ((tdq)->tdq_cg != NULL && ((tdq)->tdq_cg->cg_flags & CG_FLAG_THREAD) == 0)
2535 #else
2536 #define TDQ_IDLESPIN(tdq)       1
2537 #endif
2538
2539 /*
2540  * The actual idle process.
2541  */
2542 void
2543 sched_idletd(void *dummy)
2544 {
2545         struct thread *td;
2546         struct tdq *tdq;
2547         int switchcnt;
2548         int i;
2549
2550         mtx_assert(&Giant, MA_NOTOWNED);
2551         td = curthread;
2552         tdq = TDQ_SELF();
2553         for (;;) {
2554 #ifdef SMP
2555                 if (tdq_idled(tdq) == 0)
2556                         continue;
2557 #endif
2558                 switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
2559                 /*
2560                  * If we're switching very frequently, spin while checking
2561                  * for load rather than entering a low power state that 
2562                  * may require an IPI.  However, don't do any busy
2563                  * loops while on SMT machines as this simply steals
2564                  * cycles from cores doing useful work.
2565                  */
2566                 if (TDQ_IDLESPIN(tdq) && switchcnt > sched_idlespinthresh) {
2567                         for (i = 0; i < sched_idlespins; i++) {
2568                                 if (tdq->tdq_load)
2569                                         break;
2570                                 cpu_spinwait();
2571                         }
2572                 }
2573                 switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
2574                 if (tdq->tdq_load == 0) {
2575                         tdq->tdq_cpu_idle = 1;
2576                         if (tdq->tdq_load == 0) {
2577                                 cpu_idle(switchcnt > sched_idlespinthresh * 4);
2578                                 tdq->tdq_switchcnt++;
2579                         }
2580                         tdq->tdq_cpu_idle = 0;
2581                 }
2582                 if (tdq->tdq_load) {
2583                         thread_lock(td);
2584                         mi_switch(SW_VOL | SWT_IDLE, NULL);
2585                         thread_unlock(td);
2586                 }
2587         }
2588 }
2589
2590 /*
2591  * A CPU is entering for the first time or a thread is exiting.
2592  */
2593 void
2594 sched_throw(struct thread *td)
2595 {
2596         struct thread *newtd;
2597         struct tdq *tdq;
2598
2599         tdq = TDQ_SELF();
2600         if (td == NULL) {
2601                 /* Correct spinlock nesting and acquire the correct lock. */
2602                 TDQ_LOCK(tdq);
2603                 spinlock_exit();
2604                 PCPU_SET(switchtime, cpu_ticks());
2605                 PCPU_SET(switchticks, ticks);
2606         } else {
2607                 MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2608                 tdq_load_rem(tdq, td);
2609                 lock_profile_release_lock(&TDQ_LOCKPTR(tdq)->lock_object);
2610         }
2611         KASSERT(curthread->td_md.md_spinlock_count == 1, ("invalid count"));
2612         newtd = choosethread();
2613         TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)newtd;
2614         cpu_throw(td, newtd);           /* doesn't return */
2615 }
2616
2617 /*
2618  * This is called from fork_exit().  Just acquire the correct locks and
2619  * let fork do the rest of the work.
2620  */
2621 void
2622 sched_fork_exit(struct thread *td)
2623 {
2624         struct td_sched *ts;
2625         struct tdq *tdq;
2626         int cpuid;
2627
2628         /*
2629          * Finish setting up thread glue so that it begins execution in a
2630          * non-nested critical section with the scheduler lock held.
2631          */
2632         cpuid = PCPU_GET(cpuid);
2633         tdq = TDQ_CPU(cpuid);
2634         ts = td->td_sched;
2635         if (TD_IS_IDLETHREAD(td))
2636                 td->td_lock = TDQ_LOCKPTR(tdq);
2637         MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2638         td->td_oncpu = cpuid;
2639         TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
2640         lock_profile_obtain_lock_success(
2641             &TDQ_LOCKPTR(tdq)->lock_object, 0, 0, __FILE__, __LINE__);
2642 }
2643
2644 /*
2645  * Create on first use to catch odd startup conditons.
2646  */
2647 char *
2648 sched_tdname(struct thread *td)
2649 {
2650 #ifdef KTR
2651         struct td_sched *ts;
2652
2653         ts = td->td_sched;
2654         if (ts->ts_name[0] == '\0')
2655                 snprintf(ts->ts_name, sizeof(ts->ts_name),
2656                     "%s tid %d", td->td_name, td->td_tid);
2657         return (ts->ts_name);
2658 #else
2659         return (td->td_name);
2660 #endif
2661 }
2662
2663 #ifdef KTR
2664 void
2665 sched_clear_tdname(struct thread *td)
2666 {
2667         struct td_sched *ts;
2668
2669         ts = td->td_sched;
2670         ts->ts_name[0] = '\0';
2671 }
2672 #endif
2673
2674 #ifdef SMP
2675
2676 /*
2677  * Build the CPU topology dump string. Is recursively called to collect
2678  * the topology tree.
2679  */
2680 static int
2681 sysctl_kern_sched_topology_spec_internal(struct sbuf *sb, struct cpu_group *cg,
2682     int indent)
2683 {
2684         char cpusetbuf[CPUSETBUFSIZ];
2685         int i, first;
2686
2687         sbuf_printf(sb, "%*s<group level=\"%d\" cache-level=\"%d\">\n", indent,
2688             "", 1 + indent / 2, cg->cg_level);
2689         sbuf_printf(sb, "%*s <cpu count=\"%d\" mask=\"%s\">", indent, "",
2690             cg->cg_count, cpusetobj_strprint(cpusetbuf, &cg->cg_mask));
2691         first = TRUE;
2692         for (i = 0; i < MAXCPU; i++) {
2693                 if (CPU_ISSET(i, &cg->cg_mask)) {
2694                         if (!first)
2695                                 sbuf_printf(sb, ", ");
2696                         else
2697                                 first = FALSE;
2698                         sbuf_printf(sb, "%d", i);
2699                 }
2700         }
2701         sbuf_printf(sb, "</cpu>\n");
2702
2703         if (cg->cg_flags != 0) {
2704                 sbuf_printf(sb, "%*s <flags>", indent, "");
2705                 if ((cg->cg_flags & CG_FLAG_HTT) != 0)
2706                         sbuf_printf(sb, "<flag name=\"HTT\">HTT group</flag>");
2707                 if ((cg->cg_flags & CG_FLAG_THREAD) != 0)
2708                         sbuf_printf(sb, "<flag name=\"THREAD\">THREAD group</flag>");
2709                 if ((cg->cg_flags & CG_FLAG_SMT) != 0)
2710                         sbuf_printf(sb, "<flag name=\"SMT\">SMT group</flag>");
2711                 sbuf_printf(sb, "</flags>\n");
2712         }
2713
2714         if (cg->cg_children > 0) {
2715                 sbuf_printf(sb, "%*s <children>\n", indent, "");
2716                 for (i = 0; i < cg->cg_children; i++)
2717                         sysctl_kern_sched_topology_spec_internal(sb, 
2718                             &cg->cg_child[i], indent+2);
2719                 sbuf_printf(sb, "%*s </children>\n", indent, "");
2720         }
2721         sbuf_printf(sb, "%*s</group>\n", indent, "");
2722         return (0);
2723 }
2724
2725 /*
2726  * Sysctl handler for retrieving topology dump. It's a wrapper for
2727  * the recursive sysctl_kern_smp_topology_spec_internal().
2728  */
2729 static int
2730 sysctl_kern_sched_topology_spec(SYSCTL_HANDLER_ARGS)
2731 {
2732         struct sbuf *topo;
2733         int err;
2734
2735         KASSERT(cpu_top != NULL, ("cpu_top isn't initialized"));
2736
2737         topo = sbuf_new(NULL, NULL, 500, SBUF_AUTOEXTEND);
2738         if (topo == NULL)
2739                 return (ENOMEM);
2740
2741         sbuf_printf(topo, "<groups>\n");
2742         err = sysctl_kern_sched_topology_spec_internal(topo, cpu_top, 1);
2743         sbuf_printf(topo, "</groups>\n");
2744
2745         if (err == 0) {
2746                 sbuf_finish(topo);
2747                 err = SYSCTL_OUT(req, sbuf_data(topo), sbuf_len(topo));
2748         }
2749         sbuf_delete(topo);
2750         return (err);
2751 }
2752
2753 #endif
2754
2755 SYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RW, 0, "Scheduler");
2756 SYSCTL_STRING(_kern_sched, OID_AUTO, name, CTLFLAG_RD, "ULE", 0,
2757     "Scheduler name");
2758 SYSCTL_INT(_kern_sched, OID_AUTO, slice, CTLFLAG_RW, &sched_slice, 0,
2759     "Slice size for timeshare threads");
2760 SYSCTL_INT(_kern_sched, OID_AUTO, interact, CTLFLAG_RW, &sched_interact, 0,
2761      "Interactivity score threshold");
2762 SYSCTL_INT(_kern_sched, OID_AUTO, preempt_thresh, CTLFLAG_RW, &preempt_thresh,
2763      0,"Min priority for preemption, lower priorities have greater precedence");
2764 SYSCTL_INT(_kern_sched, OID_AUTO, static_boost, CTLFLAG_RW, &static_boost,
2765      0,"Controls whether static kernel priorities are assigned to sleeping threads.");
2766 SYSCTL_INT(_kern_sched, OID_AUTO, idlespins, CTLFLAG_RW, &sched_idlespins,
2767      0,"Number of times idle will spin waiting for new work.");
2768 SYSCTL_INT(_kern_sched, OID_AUTO, idlespinthresh, CTLFLAG_RW, &sched_idlespinthresh,
2769      0,"Threshold before we will permit idle spinning.");
2770 #ifdef SMP
2771 SYSCTL_INT(_kern_sched, OID_AUTO, affinity, CTLFLAG_RW, &affinity, 0,
2772     "Number of hz ticks to keep thread affinity for");
2773 SYSCTL_INT(_kern_sched, OID_AUTO, balance, CTLFLAG_RW, &rebalance, 0,
2774     "Enables the long-term load balancer");
2775 SYSCTL_INT(_kern_sched, OID_AUTO, balance_interval, CTLFLAG_RW,
2776     &balance_interval, 0,
2777     "Average frequency in stathz ticks to run the long-term balancer");
2778 SYSCTL_INT(_kern_sched, OID_AUTO, steal_idle, CTLFLAG_RW, &steal_idle, 0,
2779     "Attempts to steal work from other cores before idling");
2780 SYSCTL_INT(_kern_sched, OID_AUTO, steal_thresh, CTLFLAG_RW, &steal_thresh, 0,
2781     "Minimum load on remote cpu before we'll steal");
2782
2783 /* Retrieve SMP topology */
2784 SYSCTL_PROC(_kern_sched, OID_AUTO, topology_spec, CTLTYPE_STRING |
2785     CTLFLAG_RD, NULL, 0, sysctl_kern_sched_topology_spec, "A", 
2786     "XML dump of detected CPU topology");
2787
2788 #endif
2789
2790 /* ps compat.  All cpu percentages from ULE are weighted. */
2791 static int ccpu = 0;
2792 SYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");