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