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