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