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