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