]> CyberLeo.Net >> Repos - FreeBSD/stable/8.git/blob - sys/kern/sched_4bsd.c
MFC r240026:
[FreeBSD/stable/8.git] / sys / kern / sched_4bsd.c
1 /*-
2  * Copyright (c) 1982, 1986, 1990, 1991, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  * (c) UNIX System Laboratories, Inc.
5  * All or some portions of this file are derived from material licensed
6  * to the University of California by American Telephone and Telegraph
7  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8  * the permission of UNIX System Laboratories, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 4. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
37
38 #include "opt_hwpmc_hooks.h"
39 #include "opt_sched.h"
40 #include "opt_kdtrace.h"
41
42 #include <sys/param.h>
43 #include <sys/systm.h>
44 #include <sys/cpuset.h>
45 #include <sys/kernel.h>
46 #include <sys/ktr.h>
47 #include <sys/lock.h>
48 #include <sys/kthread.h>
49 #include <sys/mutex.h>
50 #include <sys/proc.h>
51 #include <sys/resourcevar.h>
52 #include <sys/sched.h>
53 #include <sys/sdt.h>
54 #include <sys/smp.h>
55 #include <sys/sysctl.h>
56 #include <sys/sx.h>
57 #include <sys/turnstile.h>
58 #include <sys/umtx.h>
59 #include <machine/pcb.h>
60 #include <machine/smp.h>
61
62 #ifdef HWPMC_HOOKS
63 #include <sys/pmckern.h>
64 #endif
65
66 #ifdef KDTRACE_HOOKS
67 #include <sys/dtrace_bsd.h>
68 int                             dtrace_vtime_active;
69 dtrace_vtime_switch_func_t      dtrace_vtime_switch_func;
70 #endif
71
72 /*
73  * INVERSE_ESTCPU_WEIGHT is only suitable for statclock() frequencies in
74  * the range 100-256 Hz (approximately).
75  */
76 #define ESTCPULIM(e) \
77     min((e), INVERSE_ESTCPU_WEIGHT * (NICE_WEIGHT * (PRIO_MAX - PRIO_MIN) - \
78     RQ_PPQ) + INVERSE_ESTCPU_WEIGHT - 1)
79 #ifdef SMP
80 #define INVERSE_ESTCPU_WEIGHT   (8 * smp_cpus)
81 #else
82 #define INVERSE_ESTCPU_WEIGHT   8       /* 1 / (priorities per estcpu level). */
83 #endif
84 #define NICE_WEIGHT             1       /* Priorities per nice level. */
85
86 #define TS_NAME_LEN (MAXCOMLEN + sizeof(" td ") + sizeof(__XSTRING(UINT_MAX)))
87
88 /*
89  * The schedulable entity that runs a context.
90  * This is  an extension to the thread structure and is tailored to
91  * the requirements of this scheduler
92  */
93 struct td_sched {
94         fixpt_t         ts_pctcpu;      /* (j) %cpu during p_swtime. */
95         int             ts_cpticks;     /* (j) Ticks of cpu time. */
96         int             ts_slptime;     /* (j) Seconds !RUNNING. */
97         int             ts_flags;
98         struct runq     *ts_runq;       /* runq the thread is currently on */
99 #ifdef KTR
100         char            ts_name[TS_NAME_LEN];
101 #endif
102 };
103
104 /* flags kept in td_flags */
105 #define TDF_DIDRUN      TDF_SCHED0      /* thread actually ran. */
106 #define TDF_BOUND       TDF_SCHED1      /* Bound to one CPU. */
107
108 /* flags kept in ts_flags */
109 #define TSF_AFFINITY    0x0001          /* Has a non-"full" CPU set. */
110
111 #define SKE_RUNQ_PCPU(ts)                                               \
112     ((ts)->ts_runq != 0 && (ts)->ts_runq != &runq)
113
114 #define THREAD_CAN_SCHED(td, cpu)       \
115     CPU_ISSET((cpu), &(td)->td_cpuset->cs_mask)
116
117 static struct td_sched td_sched0;
118 struct mtx sched_lock;
119
120 static int      sched_tdcnt;    /* Total runnable threads in the system. */
121 static int      sched_quantum;  /* Roundrobin scheduling quantum in ticks. */
122 #define SCHED_QUANTUM   (hz / 10)       /* Default sched quantum */
123
124 static void     setup_runqs(void);
125 static void     schedcpu(void);
126 static void     schedcpu_thread(void);
127 static void     sched_priority(struct thread *td, u_char prio);
128 static void     sched_setup(void *dummy);
129 static void     maybe_resched(struct thread *td);
130 static void     updatepri(struct thread *td);
131 static void     resetpriority(struct thread *td);
132 static void     resetpriority_thread(struct thread *td);
133 #ifdef SMP
134 static int      sched_pickcpu(struct thread *td);
135 static int      forward_wakeup(int cpunum);
136 static void     kick_other_cpu(int pri, int cpuid);
137 #endif
138
139 static struct kproc_desc sched_kp = {
140         "schedcpu",
141         schedcpu_thread,
142         NULL
143 };
144 SYSINIT(schedcpu, SI_SUB_RUN_SCHEDULER, SI_ORDER_FIRST, kproc_start,
145     &sched_kp);
146 SYSINIT(sched_setup, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, sched_setup, NULL);
147
148 /*
149  * Global run queue.
150  */
151 static struct runq runq;
152
153 #ifdef SMP
154 /*
155  * Per-CPU run queues
156  */
157 static struct runq runq_pcpu[MAXCPU];
158 long runq_length[MAXCPU];
159 #endif
160
161 static void
162 setup_runqs(void)
163 {
164 #ifdef SMP
165         int i;
166
167         for (i = 0; i < MAXCPU; ++i)
168                 runq_init(&runq_pcpu[i]);
169 #endif
170
171         runq_init(&runq);
172 }
173
174 static int
175 sysctl_kern_quantum(SYSCTL_HANDLER_ARGS)
176 {
177         int error, new_val;
178
179         new_val = sched_quantum * tick;
180         error = sysctl_handle_int(oidp, &new_val, 0, req);
181         if (error != 0 || req->newptr == NULL)
182                 return (error);
183         if (new_val < tick)
184                 return (EINVAL);
185         sched_quantum = new_val / tick;
186         hogticks = 2 * sched_quantum;
187         return (0);
188 }
189
190 SYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RD, 0, "Scheduler");
191
192 SYSCTL_STRING(_kern_sched, OID_AUTO, name, CTLFLAG_RD, "4BSD", 0,
193     "Scheduler name");
194
195 SYSCTL_PROC(_kern_sched, OID_AUTO, quantum, CTLTYPE_INT | CTLFLAG_RW,
196     0, sizeof sched_quantum, sysctl_kern_quantum, "I",
197     "Roundrobin scheduling quantum in microseconds");
198
199 #ifdef SMP
200 /* Enable forwarding of wakeups to all other cpus */
201 SYSCTL_NODE(_kern_sched, OID_AUTO, ipiwakeup, CTLFLAG_RD, NULL, "Kernel SMP");
202
203 static int runq_fuzz = 1;
204 SYSCTL_INT(_kern_sched, OID_AUTO, runq_fuzz, CTLFLAG_RW, &runq_fuzz, 0, "");
205
206 static int forward_wakeup_enabled = 1;
207 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, enabled, CTLFLAG_RW,
208            &forward_wakeup_enabled, 0,
209            "Forwarding of wakeup to idle CPUs");
210
211 static int forward_wakeups_requested = 0;
212 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, requested, CTLFLAG_RD,
213            &forward_wakeups_requested, 0,
214            "Requests for Forwarding of wakeup to idle CPUs");
215
216 static int forward_wakeups_delivered = 0;
217 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, delivered, CTLFLAG_RD,
218            &forward_wakeups_delivered, 0,
219            "Completed Forwarding of wakeup to idle CPUs");
220
221 static int forward_wakeup_use_mask = 1;
222 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, usemask, CTLFLAG_RW,
223            &forward_wakeup_use_mask, 0,
224            "Use the mask of idle cpus");
225
226 static int forward_wakeup_use_loop = 0;
227 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, useloop, CTLFLAG_RW,
228            &forward_wakeup_use_loop, 0,
229            "Use a loop to find idle cpus");
230
231 static int forward_wakeup_use_single = 0;
232 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, onecpu, CTLFLAG_RW,
233            &forward_wakeup_use_single, 0,
234            "Only signal one idle cpu");
235
236 static int forward_wakeup_use_htt = 0;
237 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, htt2, CTLFLAG_RW,
238            &forward_wakeup_use_htt, 0,
239            "account for htt");
240
241 #endif
242 #if 0
243 static int sched_followon = 0;
244 SYSCTL_INT(_kern_sched, OID_AUTO, followon, CTLFLAG_RW,
245            &sched_followon, 0,
246            "allow threads to share a quantum");
247 #endif
248
249 SDT_PROVIDER_DEFINE(sched);
250
251 SDT_PROBE_DEFINE3(sched, , , change_pri, change-pri, "struct thread *", 
252     "struct proc *", "uint8_t");
253 SDT_PROBE_DEFINE3(sched, , , dequeue, dequeue, "struct thread *", 
254     "struct proc *", "void *");
255 SDT_PROBE_DEFINE4(sched, , , enqueue, enqueue, "struct thread *", 
256     "struct proc *", "void *", "int");
257 SDT_PROBE_DEFINE4(sched, , , lend_pri, lend-pri, "struct thread *", 
258     "struct proc *", "uint8_t", "struct thread *");
259 SDT_PROBE_DEFINE2(sched, , , load_change, load-change, "int", "int");
260 SDT_PROBE_DEFINE2(sched, , , off_cpu, off-cpu, "struct thread *",
261     "struct proc *");
262 SDT_PROBE_DEFINE(sched, , , on_cpu, on-cpu);
263 SDT_PROBE_DEFINE(sched, , , remain_cpu, remain-cpu);
264 SDT_PROBE_DEFINE2(sched, , , surrender, surrender, "struct thread *",
265     "struct proc *");
266
267 static __inline void
268 sched_load_add(void)
269 {
270
271         sched_tdcnt++;
272         KTR_COUNTER0(KTR_SCHED, "load", "global load", sched_tdcnt);
273         SDT_PROBE2(sched, , , load_change, NOCPU, sched_tdcnt);
274 }
275
276 static __inline void
277 sched_load_rem(void)
278 {
279
280         sched_tdcnt--;
281         KTR_COUNTER0(KTR_SCHED, "load", "global load", sched_tdcnt);
282         SDT_PROBE2(sched, , , load_change, NOCPU, sched_tdcnt);
283 }
284 /*
285  * Arrange to reschedule if necessary, taking the priorities and
286  * schedulers into account.
287  */
288 static void
289 maybe_resched(struct thread *td)
290 {
291
292         THREAD_LOCK_ASSERT(td, MA_OWNED);
293         if (td->td_priority < curthread->td_priority)
294                 curthread->td_flags |= TDF_NEEDRESCHED;
295 }
296
297 /*
298  * This function is called when a thread is about to be put on run queue
299  * because it has been made runnable or its priority has been adjusted.  It
300  * determines if the new thread should be immediately preempted to.  If so,
301  * it switches to it and eventually returns true.  If not, it returns false
302  * so that the caller may place the thread on an appropriate run queue.
303  */
304 int
305 maybe_preempt(struct thread *td)
306 {
307 #ifdef PREEMPTION
308         struct thread *ctd;
309         int cpri, pri;
310
311         /*
312          * The new thread should not preempt the current thread if any of the
313          * following conditions are true:
314          *
315          *  - The kernel is in the throes of crashing (panicstr).
316          *  - The current thread has a higher (numerically lower) or
317          *    equivalent priority.  Note that this prevents curthread from
318          *    trying to preempt to itself.
319          *  - It is too early in the boot for context switches (cold is set).
320          *  - The current thread has an inhibitor set or is in the process of
321          *    exiting.  In this case, the current thread is about to switch
322          *    out anyways, so there's no point in preempting.  If we did,
323          *    the current thread would not be properly resumed as well, so
324          *    just avoid that whole landmine.
325          *  - If the new thread's priority is not a realtime priority and
326          *    the current thread's priority is not an idle priority and
327          *    FULL_PREEMPTION is disabled.
328          *
329          * If all of these conditions are false, but the current thread is in
330          * a nested critical section, then we have to defer the preemption
331          * until we exit the critical section.  Otherwise, switch immediately
332          * to the new thread.
333          */
334         ctd = curthread;
335         THREAD_LOCK_ASSERT(td, MA_OWNED);
336         KASSERT((td->td_inhibitors == 0),
337                         ("maybe_preempt: trying to run inhibited thread"));
338         pri = td->td_priority;
339         cpri = ctd->td_priority;
340         if (panicstr != NULL || pri >= cpri || cold /* || dumping */ ||
341             TD_IS_INHIBITED(ctd))
342                 return (0);
343 #ifndef FULL_PREEMPTION
344         if (pri > PRI_MAX_ITHD && cpri < PRI_MIN_IDLE)
345                 return (0);
346 #endif
347
348         if (ctd->td_critnest > 1) {
349                 CTR1(KTR_PROC, "maybe_preempt: in critical section %d",
350                     ctd->td_critnest);
351                 ctd->td_owepreempt = 1;
352                 return (0);
353         }
354         /*
355          * Thread is runnable but not yet put on system run queue.
356          */
357         MPASS(ctd->td_lock == td->td_lock);
358         MPASS(TD_ON_RUNQ(td));
359         TD_SET_RUNNING(td);
360         CTR3(KTR_PROC, "preempting to thread %p (pid %d, %s)\n", td,
361             td->td_proc->p_pid, td->td_name);
362         mi_switch(SW_INVOL | SW_PREEMPT | SWT_PREEMPT, td);
363         /*
364          * td's lock pointer may have changed.  We have to return with it
365          * locked.
366          */
367         spinlock_enter();
368         thread_unlock(ctd);
369         thread_lock(td);
370         spinlock_exit();
371         return (1);
372 #else
373         return (0);
374 #endif
375 }
376
377 /*
378  * Constants for digital decay and forget:
379  *      90% of (td_estcpu) usage in 5 * loadav time
380  *      95% of (ts_pctcpu) usage in 60 seconds (load insensitive)
381  *          Note that, as ps(1) mentions, this can let percentages
382  *          total over 100% (I've seen 137.9% for 3 processes).
383  *
384  * Note that schedclock() updates td_estcpu and p_cpticks asynchronously.
385  *
386  * We wish to decay away 90% of td_estcpu in (5 * loadavg) seconds.
387  * That is, the system wants to compute a value of decay such
388  * that the following for loop:
389  *      for (i = 0; i < (5 * loadavg); i++)
390  *              td_estcpu *= decay;
391  * will compute
392  *      td_estcpu *= 0.1;
393  * for all values of loadavg:
394  *
395  * Mathematically this loop can be expressed by saying:
396  *      decay ** (5 * loadavg) ~= .1
397  *
398  * The system computes decay as:
399  *      decay = (2 * loadavg) / (2 * loadavg + 1)
400  *
401  * We wish to prove that the system's computation of decay
402  * will always fulfill the equation:
403  *      decay ** (5 * loadavg) ~= .1
404  *
405  * If we compute b as:
406  *      b = 2 * loadavg
407  * then
408  *      decay = b / (b + 1)
409  *
410  * We now need to prove two things:
411  *      1) Given factor ** (5 * loadavg) ~= .1, prove factor == b/(b+1)
412  *      2) Given b/(b+1) ** power ~= .1, prove power == (5 * loadavg)
413  *
414  * Facts:
415  *         For x close to zero, exp(x) =~ 1 + x, since
416  *              exp(x) = 0! + x**1/1! + x**2/2! + ... .
417  *              therefore exp(-1/b) =~ 1 - (1/b) = (b-1)/b.
418  *         For x close to zero, ln(1+x) =~ x, since
419  *              ln(1+x) = x - x**2/2 + x**3/3 - ...     -1 < x < 1
420  *              therefore ln(b/(b+1)) = ln(1 - 1/(b+1)) =~ -1/(b+1).
421  *         ln(.1) =~ -2.30
422  *
423  * Proof of (1):
424  *    Solve (factor)**(power) =~ .1 given power (5*loadav):
425  *      solving for factor,
426  *      ln(factor) =~ (-2.30/5*loadav), or
427  *      factor =~ exp(-1/((5/2.30)*loadav)) =~ exp(-1/(2*loadav)) =
428  *          exp(-1/b) =~ (b-1)/b =~ b/(b+1).                    QED
429  *
430  * Proof of (2):
431  *    Solve (factor)**(power) =~ .1 given factor == (b/(b+1)):
432  *      solving for power,
433  *      power*ln(b/(b+1)) =~ -2.30, or
434  *      power =~ 2.3 * (b + 1) = 4.6*loadav + 2.3 =~ 5*loadav.  QED
435  *
436  * Actual power values for the implemented algorithm are as follows:
437  *      loadav: 1       2       3       4
438  *      power:  5.68    10.32   14.94   19.55
439  */
440
441 /* calculations for digital decay to forget 90% of usage in 5*loadav sec */
442 #define loadfactor(loadav)      (2 * (loadav))
443 #define decay_cpu(loadfac, cpu) (((loadfac) * (cpu)) / ((loadfac) + FSCALE))
444
445 /* decay 95% of `ts_pctcpu' in 60 seconds; see CCPU_SHIFT before changing */
446 static fixpt_t  ccpu = 0.95122942450071400909 * FSCALE; /* exp(-1/20) */
447 SYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
448
449 /*
450  * If `ccpu' is not equal to `exp(-1/20)' and you still want to use the
451  * faster/more-accurate formula, you'll have to estimate CCPU_SHIFT below
452  * and possibly adjust FSHIFT in "param.h" so that (FSHIFT >= CCPU_SHIFT).
453  *
454  * To estimate CCPU_SHIFT for exp(-1/20), the following formula was used:
455  *      1 - exp(-1/20) ~= 0.0487 ~= 0.0488 == 1 (fixed pt, *11* bits).
456  *
457  * If you don't want to bother with the faster/more-accurate formula, you
458  * can set CCPU_SHIFT to (FSHIFT + 1) which will use a slower/less-accurate
459  * (more general) method of calculating the %age of CPU used by a process.
460  */
461 #define CCPU_SHIFT      11
462
463 /*
464  * Recompute process priorities, every hz ticks.
465  * MP-safe, called without the Giant mutex.
466  */
467 /* ARGSUSED */
468 static void
469 schedcpu(void)
470 {
471         register fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
472         struct thread *td;
473         struct proc *p;
474         struct td_sched *ts;
475         int awake, realstathz;
476
477         realstathz = stathz ? stathz : hz;
478         sx_slock(&allproc_lock);
479         FOREACH_PROC_IN_SYSTEM(p) {
480                 PROC_LOCK(p);
481                 if (p->p_state == PRS_NEW) {
482                         PROC_UNLOCK(p);
483                         continue;
484                 }
485                 FOREACH_THREAD_IN_PROC(p, td) {
486                         awake = 0;
487                         thread_lock(td);
488                         ts = td->td_sched;
489                         /*
490                          * Increment sleep time (if sleeping).  We
491                          * ignore overflow, as above.
492                          */
493                         /*
494                          * The td_sched slptimes are not touched in wakeup
495                          * because the thread may not HAVE everything in
496                          * memory? XXX I think this is out of date.
497                          */
498                         if (TD_ON_RUNQ(td)) {
499                                 awake = 1;
500                                 td->td_flags &= ~TDF_DIDRUN;
501                         } else if (TD_IS_RUNNING(td)) {
502                                 awake = 1;
503                                 /* Do not clear TDF_DIDRUN */
504                         } else if (td->td_flags & TDF_DIDRUN) {
505                                 awake = 1;
506                                 td->td_flags &= ~TDF_DIDRUN;
507                         }
508
509                         /*
510                          * ts_pctcpu is only for ps and ttyinfo().
511                          */
512                         ts->ts_pctcpu = (ts->ts_pctcpu * ccpu) >> FSHIFT;
513                         /*
514                          * If the td_sched has been idle the entire second,
515                          * stop recalculating its priority until
516                          * it wakes up.
517                          */
518                         if (ts->ts_cpticks != 0) {
519 #if     (FSHIFT >= CCPU_SHIFT)
520                                 ts->ts_pctcpu += (realstathz == 100)
521                                     ? ((fixpt_t) ts->ts_cpticks) <<
522                                     (FSHIFT - CCPU_SHIFT) :
523                                     100 * (((fixpt_t) ts->ts_cpticks)
524                                     << (FSHIFT - CCPU_SHIFT)) / realstathz;
525 #else
526                                 ts->ts_pctcpu += ((FSCALE - ccpu) *
527                                     (ts->ts_cpticks *
528                                     FSCALE / realstathz)) >> FSHIFT;
529 #endif
530                                 ts->ts_cpticks = 0;
531                         }
532                         /*
533                          * If there are ANY running threads in this process,
534                          * then don't count it as sleeping.
535                          * XXX: this is broken.
536                          */
537                         if (awake) {
538                                 if (ts->ts_slptime > 1) {
539                                         /*
540                                          * In an ideal world, this should not
541                                          * happen, because whoever woke us
542                                          * up from the long sleep should have
543                                          * unwound the slptime and reset our
544                                          * priority before we run at the stale
545                                          * priority.  Should KASSERT at some
546                                          * point when all the cases are fixed.
547                                          */
548                                         updatepri(td);
549                                 }
550                                 ts->ts_slptime = 0;
551                         } else
552                                 ts->ts_slptime++;
553                         if (ts->ts_slptime > 1) {
554                                 thread_unlock(td);
555                                 continue;
556                         }
557                         td->td_estcpu = decay_cpu(loadfac, td->td_estcpu);
558                         resetpriority(td);
559                         resetpriority_thread(td);
560                         thread_unlock(td);
561                 }
562                 PROC_UNLOCK(p);
563         }
564         sx_sunlock(&allproc_lock);
565 }
566
567 /*
568  * Main loop for a kthread that executes schedcpu once a second.
569  */
570 static void
571 schedcpu_thread(void)
572 {
573
574         for (;;) {
575                 schedcpu();
576                 pause("-", hz);
577         }
578 }
579
580 /*
581  * Recalculate the priority of a process after it has slept for a while.
582  * For all load averages >= 1 and max td_estcpu of 255, sleeping for at
583  * least six times the loadfactor will decay td_estcpu to zero.
584  */
585 static void
586 updatepri(struct thread *td)
587 {
588         struct td_sched *ts;
589         fixpt_t loadfac;
590         unsigned int newcpu;
591
592         ts = td->td_sched;
593         loadfac = loadfactor(averunnable.ldavg[0]);
594         if (ts->ts_slptime > 5 * loadfac)
595                 td->td_estcpu = 0;
596         else {
597                 newcpu = td->td_estcpu;
598                 ts->ts_slptime--;       /* was incremented in schedcpu() */
599                 while (newcpu && --ts->ts_slptime)
600                         newcpu = decay_cpu(loadfac, newcpu);
601                 td->td_estcpu = newcpu;
602         }
603 }
604
605 /*
606  * Compute the priority of a process when running in user mode.
607  * Arrange to reschedule if the resulting priority is better
608  * than that of the current process.
609  */
610 static void
611 resetpriority(struct thread *td)
612 {
613         register unsigned int newpriority;
614
615         if (td->td_pri_class == PRI_TIMESHARE) {
616                 newpriority = PUSER + td->td_estcpu / INVERSE_ESTCPU_WEIGHT +
617                     NICE_WEIGHT * (td->td_proc->p_nice - PRIO_MIN);
618                 newpriority = min(max(newpriority, PRI_MIN_TIMESHARE),
619                     PRI_MAX_TIMESHARE);
620                 sched_user_prio(td, newpriority);
621         }
622 }
623
624 /*
625  * Update the thread's priority when the associated process's user
626  * priority changes.
627  */
628 static void
629 resetpriority_thread(struct thread *td)
630 {
631
632         /* Only change threads with a time sharing user priority. */
633         if (td->td_priority < PRI_MIN_TIMESHARE ||
634             td->td_priority > PRI_MAX_TIMESHARE)
635                 return;
636
637         /* XXX the whole needresched thing is broken, but not silly. */
638         maybe_resched(td);
639
640         sched_prio(td, td->td_user_pri);
641 }
642
643 /* ARGSUSED */
644 static void
645 sched_setup(void *dummy)
646 {
647         setup_runqs();
648
649         if (sched_quantum == 0)
650                 sched_quantum = SCHED_QUANTUM;
651         hogticks = 2 * sched_quantum;
652
653         /* Account for thread0. */
654         sched_load_add();
655 }
656
657 /* External interfaces start here */
658
659 /*
660  * Very early in the boot some setup of scheduler-specific
661  * parts of proc0 and of some scheduler resources needs to be done.
662  * Called from:
663  *  proc0_init()
664  */
665 void
666 schedinit(void)
667 {
668         /*
669          * Set up the scheduler specific parts of proc0.
670          */
671         proc0.p_sched = NULL; /* XXX */
672         thread0.td_sched = &td_sched0;
673         thread0.td_lock = &sched_lock;
674         mtx_init(&sched_lock, "sched lock", NULL, MTX_SPIN | MTX_RECURSE);
675 }
676
677 int
678 sched_runnable(void)
679 {
680 #ifdef SMP
681         return runq_check(&runq) + runq_check(&runq_pcpu[PCPU_GET(cpuid)]);
682 #else
683         return runq_check(&runq);
684 #endif
685 }
686
687 int
688 sched_rr_interval(void)
689 {
690         if (sched_quantum == 0)
691                 sched_quantum = SCHED_QUANTUM;
692         return (sched_quantum);
693 }
694
695 /*
696  * We adjust the priority of the current process.  The priority of
697  * a process gets worse as it accumulates CPU time.  The cpu usage
698  * estimator (td_estcpu) is increased here.  resetpriority() will
699  * compute a different priority each time td_estcpu increases by
700  * INVERSE_ESTCPU_WEIGHT
701  * (until MAXPRI is reached).  The cpu usage estimator ramps up
702  * quite quickly when the process is running (linearly), and decays
703  * away exponentially, at a rate which is proportionally slower when
704  * the system is busy.  The basic principle is that the system will
705  * 90% forget that the process used a lot of CPU time in 5 * loadav
706  * seconds.  This causes the system to favor processes which haven't
707  * run much recently, and to round-robin among other processes.
708  */
709 void
710 sched_clock(struct thread *td)
711 {
712         struct td_sched *ts;
713
714         THREAD_LOCK_ASSERT(td, MA_OWNED);
715         ts = td->td_sched;
716
717         ts->ts_cpticks++;
718         td->td_estcpu = ESTCPULIM(td->td_estcpu + 1);
719         if ((td->td_estcpu % INVERSE_ESTCPU_WEIGHT) == 0) {
720                 resetpriority(td);
721                 resetpriority_thread(td);
722         }
723
724         /*
725          * Force a context switch if the current thread has used up a full
726          * quantum (default quantum is 100ms).
727          */
728         if (!TD_IS_IDLETHREAD(td) &&
729             ticks - PCPU_GET(switchticks) >= sched_quantum)
730                 td->td_flags |= TDF_NEEDRESCHED;
731 }
732
733 /*
734  * Charge child's scheduling CPU usage to parent.
735  */
736 void
737 sched_exit(struct proc *p, struct thread *td)
738 {
739
740         KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "proc exit",
741             "prio:%d", td->td_priority);
742
743         PROC_LOCK_ASSERT(p, MA_OWNED);
744         sched_exit_thread(FIRST_THREAD_IN_PROC(p), td);
745 }
746
747 void
748 sched_exit_thread(struct thread *td, struct thread *child)
749 {
750
751         KTR_STATE1(KTR_SCHED, "thread", sched_tdname(child), "exit",
752             "prio:%d", child->td_priority);
753         thread_lock(td);
754         td->td_estcpu = ESTCPULIM(td->td_estcpu + child->td_estcpu);
755         thread_unlock(td);
756         thread_lock(child);
757         if ((child->td_flags & TDF_NOLOAD) == 0)
758                 sched_load_rem();
759         thread_unlock(child);
760 }
761
762 void
763 sched_fork(struct thread *td, struct thread *childtd)
764 {
765         sched_fork_thread(td, childtd);
766 }
767
768 void
769 sched_fork_thread(struct thread *td, struct thread *childtd)
770 {
771         struct td_sched *ts;
772
773         childtd->td_estcpu = td->td_estcpu;
774         childtd->td_lock = &sched_lock;
775         childtd->td_cpuset = cpuset_ref(td->td_cpuset);
776         childtd->td_priority = childtd->td_base_pri;
777         ts = childtd->td_sched;
778         bzero(ts, sizeof(*ts));
779         ts->ts_flags |= (td->td_sched->ts_flags & TSF_AFFINITY);
780 }
781
782 void
783 sched_nice(struct proc *p, int nice)
784 {
785         struct thread *td;
786
787         PROC_LOCK_ASSERT(p, MA_OWNED);
788         p->p_nice = nice;
789         FOREACH_THREAD_IN_PROC(p, td) {
790                 thread_lock(td);
791                 resetpriority(td);
792                 resetpriority_thread(td);
793                 thread_unlock(td);
794         }
795 }
796
797 void
798 sched_class(struct thread *td, int class)
799 {
800         THREAD_LOCK_ASSERT(td, MA_OWNED);
801         td->td_pri_class = class;
802 }
803
804 /*
805  * Adjust the priority of a thread.
806  */
807 static void
808 sched_priority(struct thread *td, u_char prio)
809 {
810
811
812         KTR_POINT3(KTR_SCHED, "thread", sched_tdname(td), "priority change",
813             "prio:%d", td->td_priority, "new prio:%d", prio, KTR_ATTR_LINKED,
814             sched_tdname(curthread));
815         SDT_PROBE3(sched, , , change_pri, td, td->td_proc, prio);
816         if (td != curthread && prio > td->td_priority) {
817                 KTR_POINT3(KTR_SCHED, "thread", sched_tdname(curthread),
818                     "lend prio", "prio:%d", td->td_priority, "new prio:%d",
819                     prio, KTR_ATTR_LINKED, sched_tdname(td));
820                 SDT_PROBE4(sched, , , lend_pri, td, td->td_proc, prio, 
821                     curthread);
822         }
823         THREAD_LOCK_ASSERT(td, MA_OWNED);
824         if (td->td_priority == prio)
825                 return;
826         td->td_priority = prio;
827         if (TD_ON_RUNQ(td) && td->td_rqindex != (prio / RQ_PPQ)) {
828                 sched_rem(td);
829                 sched_add(td, SRQ_BORING);
830         }
831 }
832
833 /*
834  * Update a thread's priority when it is lent another thread's
835  * priority.
836  */
837 void
838 sched_lend_prio(struct thread *td, u_char prio)
839 {
840
841         td->td_flags |= TDF_BORROWING;
842         sched_priority(td, prio);
843 }
844
845 /*
846  * Restore a thread's priority when priority propagation is
847  * over.  The prio argument is the minimum priority the thread
848  * needs to have to satisfy other possible priority lending
849  * requests.  If the thread's regulary priority is less
850  * important than prio the thread will keep a priority boost
851  * of prio.
852  */
853 void
854 sched_unlend_prio(struct thread *td, u_char prio)
855 {
856         u_char base_pri;
857
858         if (td->td_base_pri >= PRI_MIN_TIMESHARE &&
859             td->td_base_pri <= PRI_MAX_TIMESHARE)
860                 base_pri = td->td_user_pri;
861         else
862                 base_pri = td->td_base_pri;
863         if (prio >= base_pri) {
864                 td->td_flags &= ~TDF_BORROWING;
865                 sched_prio(td, base_pri);
866         } else
867                 sched_lend_prio(td, prio);
868 }
869
870 void
871 sched_prio(struct thread *td, u_char prio)
872 {
873         u_char oldprio;
874
875         /* First, update the base priority. */
876         td->td_base_pri = prio;
877
878         /*
879          * If the thread is borrowing another thread's priority, don't ever
880          * lower the priority.
881          */
882         if (td->td_flags & TDF_BORROWING && td->td_priority < prio)
883                 return;
884
885         /* Change the real priority. */
886         oldprio = td->td_priority;
887         sched_priority(td, prio);
888
889         /*
890          * If the thread is on a turnstile, then let the turnstile update
891          * its state.
892          */
893         if (TD_ON_LOCK(td) && oldprio != prio)
894                 turnstile_adjust(td, oldprio);
895 }
896
897 void
898 sched_user_prio(struct thread *td, u_char prio)
899 {
900         u_char oldprio;
901
902         THREAD_LOCK_ASSERT(td, MA_OWNED);
903         td->td_base_user_pri = prio;
904         if (td->td_flags & TDF_UBORROWING && td->td_user_pri <= prio)
905                 return;
906         oldprio = td->td_user_pri;
907         td->td_user_pri = prio;
908 }
909
910 void
911 sched_lend_user_prio(struct thread *td, u_char prio)
912 {
913         u_char oldprio;
914
915         THREAD_LOCK_ASSERT(td, MA_OWNED);
916         td->td_flags |= TDF_UBORROWING;
917         oldprio = td->td_user_pri;
918         td->td_user_pri = prio;
919 }
920
921 void
922 sched_unlend_user_prio(struct thread *td, u_char prio)
923 {
924         u_char base_pri;
925
926         THREAD_LOCK_ASSERT(td, MA_OWNED);
927         base_pri = td->td_base_user_pri;
928         if (prio >= base_pri) {
929                 td->td_flags &= ~TDF_UBORROWING;
930                 sched_user_prio(td, base_pri);
931         } else {
932                 sched_lend_user_prio(td, prio);
933         }
934 }
935
936 void
937 sched_sleep(struct thread *td, int pri)
938 {
939
940         THREAD_LOCK_ASSERT(td, MA_OWNED);
941         td->td_slptick = ticks;
942         td->td_sched->ts_slptime = 0;
943         if (pri)
944                 sched_prio(td, pri);
945         if (TD_IS_SUSPENDED(td) || pri >= PSOCK)
946                 td->td_flags |= TDF_CANSWAP;
947 }
948
949 void
950 sched_switch(struct thread *td, struct thread *newtd, int flags)
951 {
952         struct mtx *tmtx;
953         struct td_sched *ts;
954         struct proc *p;
955
956         tmtx = NULL;
957         ts = td->td_sched;
958         p = td->td_proc;
959
960         THREAD_LOCK_ASSERT(td, MA_OWNED);
961
962         /* 
963          * Switch to the sched lock to fix things up and pick
964          * a new thread.
965          * Block the td_lock in order to avoid breaking the critical path.
966          */
967         if (td->td_lock != &sched_lock) {
968                 mtx_lock_spin(&sched_lock);
969                 tmtx = thread_lock_block(td);
970         }
971
972         if ((td->td_flags & TDF_NOLOAD) == 0)
973                 sched_load_rem();
974
975         td->td_lastcpu = td->td_oncpu;
976         if (!(flags & SW_PREEMPT))
977                 td->td_flags &= ~TDF_NEEDRESCHED;
978         td->td_owepreempt = 0;
979         td->td_oncpu = NOCPU;
980
981         /*
982          * At the last moment, if this thread is still marked RUNNING,
983          * then put it back on the run queue as it has not been suspended
984          * or stopped or any thing else similar.  We never put the idle
985          * threads on the run queue, however.
986          */
987         if (td->td_flags & TDF_IDLETD) {
988                 TD_SET_CAN_RUN(td);
989 #ifdef SMP
990                 idle_cpus_mask &= ~PCPU_GET(cpumask);
991 #endif
992         } else {
993                 if (TD_IS_RUNNING(td)) {
994                         /* Put us back on the run queue. */
995                         sched_add(td, (flags & SW_PREEMPT) ?
996                             SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
997                             SRQ_OURSELF|SRQ_YIELDING);
998                 }
999         }
1000         if (newtd) {
1001                 /*
1002                  * The thread we are about to run needs to be counted
1003                  * as if it had been added to the run queue and selected.
1004                  * It came from:
1005                  * * A preemption
1006                  * * An upcall
1007                  * * A followon
1008                  */
1009                 KASSERT((newtd->td_inhibitors == 0),
1010                         ("trying to run inhibited thread"));
1011                 newtd->td_flags |= TDF_DIDRUN;
1012                 TD_SET_RUNNING(newtd);
1013                 if ((newtd->td_flags & TDF_NOLOAD) == 0)
1014                         sched_load_add();
1015         } else {
1016                 newtd = choosethread();
1017                 MPASS(newtd->td_lock == &sched_lock);
1018         }
1019
1020         if (td != newtd) {
1021 #ifdef  HWPMC_HOOKS
1022                 if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1023                         PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
1024 #endif
1025
1026                 SDT_PROBE2(sched, , , off_cpu, td, td->td_proc);
1027
1028                 /* I feel sleepy */
1029                 lock_profile_release_lock(&sched_lock.lock_object);
1030 #ifdef KDTRACE_HOOKS
1031                 /*
1032                  * If DTrace has set the active vtime enum to anything
1033                  * other than INACTIVE (0), then it should have set the
1034                  * function to call.
1035                  */
1036                 if (dtrace_vtime_active)
1037                         (*dtrace_vtime_switch_func)(newtd);
1038 #endif
1039
1040                 cpu_switch(td, newtd, tmtx != NULL ? tmtx : td->td_lock);
1041                 lock_profile_obtain_lock_success(&sched_lock.lock_object,
1042                     0, 0, __FILE__, __LINE__);
1043                 /*
1044                  * Where am I?  What year is it?
1045                  * We are in the same thread that went to sleep above,
1046                  * but any amount of time may have passed. All our context
1047                  * will still be available as will local variables.
1048                  * PCPU values however may have changed as we may have
1049                  * changed CPU so don't trust cached values of them.
1050                  * New threads will go to fork_exit() instead of here
1051                  * so if you change things here you may need to change
1052                  * things there too.
1053                  *
1054                  * If the thread above was exiting it will never wake
1055                  * up again here, so either it has saved everything it
1056                  * needed to, or the thread_wait() or wait() will
1057                  * need to reap it.
1058                  */
1059
1060                 SDT_PROBE0(sched, , , on_cpu);
1061 #ifdef  HWPMC_HOOKS
1062                 if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1063                         PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_IN);
1064 #endif
1065         } else
1066                 SDT_PROBE0(sched, , , remain_cpu);
1067
1068 #ifdef SMP
1069         if (td->td_flags & TDF_IDLETD)
1070                 idle_cpus_mask |= PCPU_GET(cpumask);
1071 #endif
1072         sched_lock.mtx_lock = (uintptr_t)td;
1073         td->td_oncpu = PCPU_GET(cpuid);
1074         MPASS(td->td_lock == &sched_lock);
1075 }
1076
1077 void
1078 sched_wakeup(struct thread *td)
1079 {
1080         struct td_sched *ts;
1081
1082         THREAD_LOCK_ASSERT(td, MA_OWNED);
1083         ts = td->td_sched;
1084         td->td_flags &= ~TDF_CANSWAP;
1085         if (ts->ts_slptime > 1) {
1086                 updatepri(td);
1087                 resetpriority(td);
1088         }
1089         td->td_slptick = 0;
1090         ts->ts_slptime = 0;
1091         sched_add(td, SRQ_BORING);
1092 }
1093
1094 #ifdef SMP
1095 static int
1096 forward_wakeup(int cpunum)
1097 {
1098         struct pcpu *pc;
1099         cpumask_t dontuse, id, map, map2, map3, me;
1100
1101         mtx_assert(&sched_lock, MA_OWNED);
1102
1103         CTR0(KTR_RUNQ, "forward_wakeup()");
1104
1105         if ((!forward_wakeup_enabled) ||
1106              (forward_wakeup_use_mask == 0 && forward_wakeup_use_loop == 0))
1107                 return (0);
1108         if (!smp_started || cold || panicstr)
1109                 return (0);
1110
1111         forward_wakeups_requested++;
1112
1113         /*
1114          * Check the idle mask we received against what we calculated
1115          * before in the old version.
1116          */
1117         me = PCPU_GET(cpumask);
1118
1119         /* Don't bother if we should be doing it ourself. */
1120         if ((me & idle_cpus_mask) && (cpunum == NOCPU || me == (1 << cpunum)))
1121                 return (0);
1122
1123         dontuse = me | stopped_cpus | hlt_cpus_mask;
1124         map3 = 0;
1125         if (forward_wakeup_use_loop) {
1126                 SLIST_FOREACH(pc, &cpuhead, pc_allcpu) {
1127                         id = pc->pc_cpumask;
1128                         if ((id & dontuse) == 0 &&
1129                             pc->pc_curthread == pc->pc_idlethread) {
1130                                 map3 |= id;
1131                         }
1132                 }
1133         }
1134
1135         if (forward_wakeup_use_mask) {
1136                 map = 0;
1137                 map = idle_cpus_mask & ~dontuse;
1138
1139                 /* If they are both on, compare and use loop if different. */
1140                 if (forward_wakeup_use_loop) {
1141                         if (map != map3) {
1142                                 printf("map (%02X) != map3 (%02X)\n", map,
1143                                     map3);
1144                                 map = map3;
1145                         }
1146                 }
1147         } else {
1148                 map = map3;
1149         }
1150
1151         /* If we only allow a specific CPU, then mask off all the others. */
1152         if (cpunum != NOCPU) {
1153                 KASSERT((cpunum <= mp_maxcpus),("forward_wakeup: bad cpunum."));
1154                 map &= (1 << cpunum);
1155         } else {
1156                 /* Try choose an idle die. */
1157                 if (forward_wakeup_use_htt) {
1158                         map2 =  (map & (map >> 1)) & 0x5555;
1159                         if (map2) {
1160                                 map = map2;
1161                         }
1162                 }
1163
1164                 /* Set only one bit. */
1165                 if (forward_wakeup_use_single) {
1166                         map = map & ((~map) + 1);
1167                 }
1168         }
1169         if (map) {
1170                 forward_wakeups_delivered++;
1171                 ipi_selected(map, IPI_AST);
1172                 return (1);
1173         }
1174         if (cpunum == NOCPU)
1175                 printf("forward_wakeup: Idle processor not found\n");
1176         return (0);
1177 }
1178
1179 static void
1180 kick_other_cpu(int pri, int cpuid)
1181 {
1182         struct pcpu *pcpu;
1183         int cpri;
1184
1185         pcpu = pcpu_find(cpuid);
1186         if (idle_cpus_mask & pcpu->pc_cpumask) {
1187                 forward_wakeups_delivered++;
1188                 ipi_cpu(cpuid, IPI_AST);
1189                 return;
1190         }
1191
1192         cpri = pcpu->pc_curthread->td_priority;
1193         if (pri >= cpri)
1194                 return;
1195
1196 #if defined(IPI_PREEMPTION) && defined(PREEMPTION)
1197 #if !defined(FULL_PREEMPTION)
1198         if (pri <= PRI_MAX_ITHD)
1199 #endif /* ! FULL_PREEMPTION */
1200         {
1201                 ipi_cpu(cpuid, IPI_PREEMPT);
1202                 return;
1203         }
1204 #endif /* defined(IPI_PREEMPTION) && defined(PREEMPTION) */
1205
1206         pcpu->pc_curthread->td_flags |= TDF_NEEDRESCHED;
1207         ipi_cpu(cpuid, IPI_AST);
1208         return;
1209 }
1210 #endif /* SMP */
1211
1212 #ifdef SMP
1213 static int
1214 sched_pickcpu(struct thread *td)
1215 {
1216         int best, cpu;
1217
1218         mtx_assert(&sched_lock, MA_OWNED);
1219
1220         if (THREAD_CAN_SCHED(td, td->td_lastcpu))
1221                 best = td->td_lastcpu;
1222         else
1223                 best = NOCPU;
1224         CPU_FOREACH(cpu) {
1225                 if (!THREAD_CAN_SCHED(td, cpu))
1226                         continue;
1227         
1228                 if (best == NOCPU)
1229                         best = cpu;
1230                 else if (runq_length[cpu] < runq_length[best])
1231                         best = cpu;
1232         }
1233         KASSERT(best != NOCPU, ("no valid CPUs"));
1234
1235         return (best);
1236 }
1237 #endif
1238
1239 void
1240 sched_add(struct thread *td, int flags)
1241 #ifdef SMP
1242 {
1243         struct td_sched *ts;
1244         int forwarded = 0;
1245         int cpu;
1246         int single_cpu = 0;
1247
1248         ts = td->td_sched;
1249         THREAD_LOCK_ASSERT(td, MA_OWNED);
1250         KASSERT((td->td_inhibitors == 0),
1251             ("sched_add: trying to run inhibited thread"));
1252         KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
1253             ("sched_add: bad thread state"));
1254         KASSERT(td->td_flags & TDF_INMEM,
1255             ("sched_add: thread swapped out"));
1256
1257         KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq add",
1258             "prio:%d", td->td_priority, KTR_ATTR_LINKED,
1259             sched_tdname(curthread));
1260         KTR_POINT1(KTR_SCHED, "thread", sched_tdname(curthread), "wokeup",
1261             KTR_ATTR_LINKED, sched_tdname(td));
1262         SDT_PROBE4(sched, , , enqueue, td, td->td_proc, NULL, 
1263             flags & SRQ_PREEMPTED);
1264
1265
1266         /*
1267          * Now that the thread is moving to the run-queue, set the lock
1268          * to the scheduler's lock.
1269          */
1270         if (td->td_lock != &sched_lock) {
1271                 mtx_lock_spin(&sched_lock);
1272                 thread_lock_set(td, &sched_lock);
1273         }
1274         TD_SET_RUNQ(td);
1275
1276         /*
1277          * If SMP is started and the thread is pinned or otherwise limited to
1278          * a specific set of CPUs, queue the thread to a per-CPU run queue.
1279          * Otherwise, queue the thread to the global run queue.
1280          *
1281          * If SMP has not yet been started we must use the global run queue
1282          * as per-CPU state may not be initialized yet and we may crash if we
1283          * try to access the per-CPU run queues.
1284          */
1285         if (smp_started && (td->td_pinned != 0 || td->td_flags & TDF_BOUND ||
1286             ts->ts_flags & TSF_AFFINITY)) {
1287                 if (td->td_pinned != 0)
1288                         cpu = td->td_lastcpu;
1289                 else if (td->td_flags & TDF_BOUND) {
1290                         /* Find CPU from bound runq. */
1291                         KASSERT(SKE_RUNQ_PCPU(ts),
1292                             ("sched_add: bound td_sched not on cpu runq"));
1293                         cpu = ts->ts_runq - &runq_pcpu[0];
1294                 } else
1295                         /* Find a valid CPU for our cpuset */
1296                         cpu = sched_pickcpu(td);
1297                 ts->ts_runq = &runq_pcpu[cpu];
1298                 single_cpu = 1;
1299                 CTR3(KTR_RUNQ,
1300                     "sched_add: Put td_sched:%p(td:%p) on cpu%d runq", ts, td,
1301                     cpu);
1302         } else {
1303                 CTR2(KTR_RUNQ,
1304                     "sched_add: adding td_sched:%p (td:%p) to gbl runq", ts,
1305                     td);
1306                 cpu = NOCPU;
1307                 ts->ts_runq = &runq;
1308         }
1309
1310         if (single_cpu && (cpu != PCPU_GET(cpuid))) {
1311                 kick_other_cpu(td->td_priority, cpu);
1312         } else {
1313                 if (!single_cpu) {
1314                         cpumask_t me = PCPU_GET(cpumask);
1315                         cpumask_t idle = idle_cpus_mask & me;
1316
1317                         if (!idle && ((flags & SRQ_INTR) == 0) &&
1318                             (idle_cpus_mask & ~(hlt_cpus_mask | me)))
1319                                 forwarded = forward_wakeup(cpu);
1320                 }
1321
1322                 if (!forwarded) {
1323                         if ((flags & SRQ_YIELDING) == 0 && maybe_preempt(td))
1324                                 return;
1325                         else
1326                                 maybe_resched(td);
1327                 }
1328         }
1329
1330         if ((td->td_flags & TDF_NOLOAD) == 0)
1331                 sched_load_add();
1332         runq_add(ts->ts_runq, td, flags);
1333         if (cpu != NOCPU)
1334                 runq_length[cpu]++;
1335 }
1336 #else /* SMP */
1337 {
1338         struct td_sched *ts;
1339
1340         ts = td->td_sched;
1341         THREAD_LOCK_ASSERT(td, MA_OWNED);
1342         KASSERT((td->td_inhibitors == 0),
1343             ("sched_add: trying to run inhibited thread"));
1344         KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
1345             ("sched_add: bad thread state"));
1346         KASSERT(td->td_flags & TDF_INMEM,
1347             ("sched_add: thread swapped out"));
1348         KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq add",
1349             "prio:%d", td->td_priority, KTR_ATTR_LINKED,
1350             sched_tdname(curthread));
1351         KTR_POINT1(KTR_SCHED, "thread", sched_tdname(curthread), "wokeup",
1352             KTR_ATTR_LINKED, sched_tdname(td));
1353         SDT_PROBE4(sched, , , enqueue, td, td->td_proc, NULL, 
1354             flags & SRQ_PREEMPTED);
1355
1356         /*
1357          * Now that the thread is moving to the run-queue, set the lock
1358          * to the scheduler's lock.
1359          */
1360         if (td->td_lock != &sched_lock) {
1361                 mtx_lock_spin(&sched_lock);
1362                 thread_lock_set(td, &sched_lock);
1363         }
1364         TD_SET_RUNQ(td);
1365         CTR2(KTR_RUNQ, "sched_add: adding td_sched:%p (td:%p) to runq", ts, td);
1366         ts->ts_runq = &runq;
1367
1368         /*
1369          * If we are yielding (on the way out anyhow) or the thread
1370          * being saved is US, then don't try be smart about preemption
1371          * or kicking off another CPU as it won't help and may hinder.
1372          * In the YIEDLING case, we are about to run whoever is being
1373          * put in the queue anyhow, and in the OURSELF case, we are
1374          * puting ourself on the run queue which also only happens
1375          * when we are about to yield.
1376          */
1377         if ((flags & SRQ_YIELDING) == 0) {
1378                 if (maybe_preempt(td))
1379                         return;
1380         }
1381         if ((td->td_flags & TDF_NOLOAD) == 0)
1382                 sched_load_add();
1383         runq_add(ts->ts_runq, td, flags);
1384         maybe_resched(td);
1385 }
1386 #endif /* SMP */
1387
1388 void
1389 sched_rem(struct thread *td)
1390 {
1391         struct td_sched *ts;
1392
1393         ts = td->td_sched;
1394         KASSERT(td->td_flags & TDF_INMEM,
1395             ("sched_rem: thread swapped out"));
1396         KASSERT(TD_ON_RUNQ(td),
1397             ("sched_rem: thread not on run queue"));
1398         mtx_assert(&sched_lock, MA_OWNED);
1399         KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq rem",
1400             "prio:%d", td->td_priority, KTR_ATTR_LINKED,
1401             sched_tdname(curthread));
1402         SDT_PROBE3(sched, , , dequeue, td, td->td_proc, NULL);
1403
1404         if ((td->td_flags & TDF_NOLOAD) == 0)
1405                 sched_load_rem();
1406 #ifdef SMP
1407         if (ts->ts_runq != &runq)
1408                 runq_length[ts->ts_runq - runq_pcpu]--;
1409 #endif
1410         runq_remove(ts->ts_runq, td);
1411         TD_SET_CAN_RUN(td);
1412 }
1413
1414 /*
1415  * Select threads to run.  Note that running threads still consume a
1416  * slot.
1417  */
1418 struct thread *
1419 sched_choose(void)
1420 {
1421         struct thread *td;
1422         struct runq *rq;
1423
1424         mtx_assert(&sched_lock,  MA_OWNED);
1425 #ifdef SMP
1426         struct thread *tdcpu;
1427
1428         rq = &runq;
1429         td = runq_choose_fuzz(&runq, runq_fuzz);
1430         tdcpu = runq_choose(&runq_pcpu[PCPU_GET(cpuid)]);
1431
1432         if (td == NULL ||
1433             (tdcpu != NULL &&
1434              tdcpu->td_priority < td->td_priority)) {
1435                 CTR2(KTR_RUNQ, "choosing td %p from pcpu runq %d", tdcpu,
1436                      PCPU_GET(cpuid));
1437                 td = tdcpu;
1438                 rq = &runq_pcpu[PCPU_GET(cpuid)];
1439         } else {
1440                 CTR1(KTR_RUNQ, "choosing td_sched %p from main runq", td);
1441         }
1442
1443 #else
1444         rq = &runq;
1445         td = runq_choose(&runq);
1446 #endif
1447
1448         if (td) {
1449 #ifdef SMP
1450                 if (td == tdcpu)
1451                         runq_length[PCPU_GET(cpuid)]--;
1452 #endif
1453                 runq_remove(rq, td);
1454                 td->td_flags |= TDF_DIDRUN;
1455
1456                 KASSERT(td->td_flags & TDF_INMEM,
1457                     ("sched_choose: thread swapped out"));
1458                 return (td);
1459         }
1460         return (PCPU_GET(idlethread));
1461 }
1462
1463 void
1464 sched_preempt(struct thread *td)
1465 {
1466
1467         SDT_PROBE2(sched, , , surrender, td, td->td_proc);
1468         thread_lock(td);
1469         if (td->td_critnest > 1)
1470                 td->td_owepreempt = 1;
1471         else
1472                 mi_switch(SW_INVOL | SW_PREEMPT | SWT_PREEMPT, NULL);
1473         thread_unlock(td);
1474 }
1475
1476 void
1477 sched_userret(struct thread *td)
1478 {
1479         /*
1480          * XXX we cheat slightly on the locking here to avoid locking in
1481          * the usual case.  Setting td_priority here is essentially an
1482          * incomplete workaround for not setting it properly elsewhere.
1483          * Now that some interrupt handlers are threads, not setting it
1484          * properly elsewhere can clobber it in the window between setting
1485          * it here and returning to user mode, so don't waste time setting
1486          * it perfectly here.
1487          */
1488         KASSERT((td->td_flags & TDF_BORROWING) == 0,
1489             ("thread with borrowed priority returning to userland"));
1490         if (td->td_priority != td->td_user_pri) {
1491                 thread_lock(td);
1492                 td->td_priority = td->td_user_pri;
1493                 td->td_base_pri = td->td_user_pri;
1494                 thread_unlock(td);
1495         }
1496 }
1497
1498 void
1499 sched_bind(struct thread *td, int cpu)
1500 {
1501         struct td_sched *ts;
1502
1503         THREAD_LOCK_ASSERT(td, MA_OWNED|MA_NOTRECURSED);
1504         KASSERT(td == curthread, ("sched_bind: can only bind curthread"));
1505
1506         ts = td->td_sched;
1507
1508         td->td_flags |= TDF_BOUND;
1509 #ifdef SMP
1510         ts->ts_runq = &runq_pcpu[cpu];
1511         if (PCPU_GET(cpuid) == cpu)
1512                 return;
1513
1514         mi_switch(SW_VOL, NULL);
1515 #endif
1516 }
1517
1518 void
1519 sched_unbind(struct thread* td)
1520 {
1521         THREAD_LOCK_ASSERT(td, MA_OWNED);
1522         KASSERT(td == curthread, ("sched_unbind: can only bind curthread"));
1523         td->td_flags &= ~TDF_BOUND;
1524 }
1525
1526 int
1527 sched_is_bound(struct thread *td)
1528 {
1529         THREAD_LOCK_ASSERT(td, MA_OWNED);
1530         return (td->td_flags & TDF_BOUND);
1531 }
1532
1533 void
1534 sched_relinquish(struct thread *td)
1535 {
1536         thread_lock(td);
1537         mi_switch(SW_VOL | SWT_RELINQUISH, NULL);
1538         thread_unlock(td);
1539 }
1540
1541 int
1542 sched_load(void)
1543 {
1544         return (sched_tdcnt);
1545 }
1546
1547 int
1548 sched_sizeof_proc(void)
1549 {
1550         return (sizeof(struct proc));
1551 }
1552
1553 int
1554 sched_sizeof_thread(void)
1555 {
1556         return (sizeof(struct thread) + sizeof(struct td_sched));
1557 }
1558
1559 fixpt_t
1560 sched_pctcpu(struct thread *td)
1561 {
1562         struct td_sched *ts;
1563
1564         THREAD_LOCK_ASSERT(td, MA_OWNED);
1565         ts = td->td_sched;
1566         return (ts->ts_pctcpu);
1567 }
1568
1569 void
1570 sched_tick(void)
1571 {
1572 }
1573
1574 /*
1575  * The actual idle process.
1576  */
1577 void
1578 sched_idletd(void *dummy)
1579 {
1580
1581         for (;;) {
1582                 mtx_assert(&Giant, MA_NOTOWNED);
1583
1584                 while (sched_runnable() == 0)
1585                         cpu_idle(0);
1586
1587                 mtx_lock_spin(&sched_lock);
1588                 mi_switch(SW_VOL | SWT_IDLE, NULL);
1589                 mtx_unlock_spin(&sched_lock);
1590         }
1591 }
1592
1593 /*
1594  * A CPU is entering for the first time or a thread is exiting.
1595  */
1596 void
1597 sched_throw(struct thread *td)
1598 {
1599         /*
1600          * Correct spinlock nesting.  The idle thread context that we are
1601          * borrowing was created so that it would start out with a single
1602          * spin lock (sched_lock) held in fork_trampoline().  Since we've
1603          * explicitly acquired locks in this function, the nesting count
1604          * is now 2 rather than 1.  Since we are nested, calling
1605          * spinlock_exit() will simply adjust the counts without allowing
1606          * spin lock using code to interrupt us.
1607          */
1608         if (td == NULL) {
1609                 mtx_lock_spin(&sched_lock);
1610                 spinlock_exit();
1611                 PCPU_SET(switchtime, cpu_ticks());
1612                 PCPU_SET(switchticks, ticks);
1613         } else {
1614                 lock_profile_release_lock(&sched_lock.lock_object);
1615                 MPASS(td->td_lock == &sched_lock);
1616         }
1617         mtx_assert(&sched_lock, MA_OWNED);
1618         KASSERT(curthread->td_md.md_spinlock_count == 1, ("invalid count"));
1619         cpu_throw(td, choosethread());  /* doesn't return */
1620 }
1621
1622 void
1623 sched_fork_exit(struct thread *td)
1624 {
1625
1626         /*
1627          * Finish setting up thread glue so that it begins execution in a
1628          * non-nested critical section with sched_lock held but not recursed.
1629          */
1630         td->td_oncpu = PCPU_GET(cpuid);
1631         sched_lock.mtx_lock = (uintptr_t)td;
1632         lock_profile_obtain_lock_success(&sched_lock.lock_object,
1633             0, 0, __FILE__, __LINE__);
1634         THREAD_LOCK_ASSERT(td, MA_OWNED | MA_NOTRECURSED);
1635 }
1636
1637 char *
1638 sched_tdname(struct thread *td)
1639 {
1640 #ifdef KTR
1641         struct td_sched *ts;
1642
1643         ts = td->td_sched;
1644         if (ts->ts_name[0] == '\0')
1645                 snprintf(ts->ts_name, sizeof(ts->ts_name),
1646                     "%s tid %d", td->td_name, td->td_tid);
1647         return (ts->ts_name);
1648 #else   
1649         return (td->td_name);
1650 #endif
1651 }
1652
1653 #ifdef KTR
1654 void
1655 sched_clear_tdname(struct thread *td)
1656 {
1657         struct td_sched *ts;
1658
1659         ts = td->td_sched;
1660         ts->ts_name[0] = '\0';
1661 }
1662 #endif
1663
1664 void
1665 sched_affinity(struct thread *td)
1666 {
1667 #ifdef SMP
1668         struct td_sched *ts;
1669         int cpu;
1670
1671         THREAD_LOCK_ASSERT(td, MA_OWNED);       
1672
1673         /*
1674          * Set the TSF_AFFINITY flag if there is at least one CPU this
1675          * thread can't run on.
1676          */
1677         ts = td->td_sched;
1678         ts->ts_flags &= ~TSF_AFFINITY;
1679         CPU_FOREACH(cpu) {
1680                 if (!THREAD_CAN_SCHED(td, cpu)) {
1681                         ts->ts_flags |= TSF_AFFINITY;
1682                         break;
1683                 }
1684         }
1685
1686         /*
1687          * If this thread can run on all CPUs, nothing else to do.
1688          */
1689         if (!(ts->ts_flags & TSF_AFFINITY))
1690                 return;
1691
1692         /* Pinned threads and bound threads should be left alone. */
1693         if (td->td_pinned != 0 || td->td_flags & TDF_BOUND)
1694                 return;
1695
1696         switch (td->td_state) {
1697         case TDS_RUNQ:
1698                 /*
1699                  * If we are on a per-CPU runqueue that is in the set,
1700                  * then nothing needs to be done.
1701                  */
1702                 if (ts->ts_runq != &runq &&
1703                     THREAD_CAN_SCHED(td, ts->ts_runq - runq_pcpu))
1704                         return;
1705
1706                 /* Put this thread on a valid per-CPU runqueue. */
1707                 sched_rem(td);
1708                 sched_add(td, SRQ_BORING);
1709                 break;
1710         case TDS_RUNNING:
1711                 /*
1712                  * See if our current CPU is in the set.  If not, force a
1713                  * context switch.
1714                  */
1715                 if (THREAD_CAN_SCHED(td, td->td_oncpu))
1716                         return;
1717
1718                 td->td_flags |= TDF_NEEDRESCHED;
1719                 if (td != curthread)
1720                         ipi_cpu(cpu, IPI_AST);
1721                 break;
1722         default:
1723                 break;
1724         }
1725 #endif
1726 }