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