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