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