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