xref: /dflybsd-src/sys/kern/kern_synch.c (revision c9fbf0d3b1d54097180190816f8fa4f5d415b174)
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  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *	This product includes software developed by the University of
21  *	California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  *	@(#)kern_synch.c	8.9 (Berkeley) 5/19/95
39  * $FreeBSD: src/sys/kern/kern_synch.c,v 1.87.2.6 2002/10/13 07:29:53 kbyanc Exp $
40  * $DragonFly: src/sys/kern/kern_synch.c,v 1.52 2005/11/09 03:39:15 dillon Exp $
41  */
42 
43 #include "opt_ktrace.h"
44 
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/proc.h>
48 #include <sys/kernel.h>
49 #include <sys/signalvar.h>
50 #include <sys/resourcevar.h>
51 #include <sys/vmmeter.h>
52 #include <sys/sysctl.h>
53 #include <sys/thread2.h>
54 #ifdef KTRACE
55 #include <sys/uio.h>
56 #include <sys/ktrace.h>
57 #endif
58 #include <sys/xwait.h>
59 
60 #include <machine/cpu.h>
61 #include <machine/ipl.h>
62 #include <machine/smp.h>
63 
64 TAILQ_HEAD(tslpque, thread);
65 
66 static void sched_setup (void *dummy);
67 SYSINIT(sched_setup, SI_SUB_KICK_SCHEDULER, SI_ORDER_FIRST, sched_setup, NULL)
68 
69 int	hogticks;
70 int	lbolt;
71 int	sched_quantum;		/* Roundrobin scheduling quantum in ticks. */
72 int	ncpus;
73 int	ncpus2, ncpus2_shift, ncpus2_mask;
74 int	safepri;
75 
76 static struct callout loadav_callout;
77 static struct callout schedcpu_callout;
78 MALLOC_DEFINE(M_TSLEEP, "tslpque", "tsleep queues");
79 
80 struct loadavg averunnable =
81 	{ {0, 0, 0}, FSCALE };	/* load average, of runnable procs */
82 /*
83  * Constants for averages over 1, 5, and 15 minutes
84  * when sampling at 5 second intervals.
85  */
86 static fixpt_t cexp[3] = {
87 	0.9200444146293232 * FSCALE,	/* exp(-1/12) */
88 	0.9834714538216174 * FSCALE,	/* exp(-1/60) */
89 	0.9944598480048967 * FSCALE,	/* exp(-1/180) */
90 };
91 
92 static void	endtsleep (void *);
93 static void	loadav (void *arg);
94 static void	schedcpu (void *arg);
95 
96 /*
97  * Adjust the scheduler quantum.  The quantum is specified in microseconds.
98  * Note that 'tick' is in microseconds per tick.
99  */
100 static int
101 sysctl_kern_quantum(SYSCTL_HANDLER_ARGS)
102 {
103 	int error, new_val;
104 
105 	new_val = sched_quantum * tick;
106 	error = sysctl_handle_int(oidp, &new_val, 0, req);
107         if (error != 0 || req->newptr == NULL)
108 		return (error);
109 	if (new_val < tick)
110 		return (EINVAL);
111 	sched_quantum = new_val / tick;
112 	hogticks = 2 * sched_quantum;
113 	return (0);
114 }
115 
116 SYSCTL_PROC(_kern, OID_AUTO, quantum, CTLTYPE_INT|CTLFLAG_RW,
117 	0, sizeof sched_quantum, sysctl_kern_quantum, "I", "");
118 
119 /*
120  * If `ccpu' is not equal to `exp(-1/20)' and you still want to use the
121  * faster/more-accurate formula, you'll have to estimate CCPU_SHIFT below
122  * and possibly adjust FSHIFT in "param.h" so that (FSHIFT >= CCPU_SHIFT).
123  *
124  * To estimate CCPU_SHIFT for exp(-1/20), the following formula was used:
125  *     1 - exp(-1/20) ~= 0.0487 ~= 0.0488 == 1 (fixed pt, *11* bits).
126  *
127  * If you don't want to bother with the faster/more-accurate formula, you
128  * can set CCPU_SHIFT to (FSHIFT + 1) which will use a slower/less-accurate
129  * (more general) method of calculating the %age of CPU used by a process.
130  *
131  * decay 95% of `p_pctcpu' in 60 seconds; see CCPU_SHIFT before changing
132  */
133 #define CCPU_SHIFT	11
134 
135 static fixpt_t ccpu = 0.95122942450071400909 * FSCALE; /* exp(-1/20) */
136 SYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
137 
138 /*
139  * kernel uses `FSCALE', userland (SHOULD) use kern.fscale
140  */
141 static int     fscale __unused = FSCALE;
142 SYSCTL_INT(_kern, OID_AUTO, fscale, CTLFLAG_RD, 0, FSCALE, "");
143 
144 /*
145  * Recompute process priorities, once a second.
146  *
147  * Since the userland schedulers are typically event oriented, if the
148  * estcpu calculation at wakeup() time is not sufficient to make a
149  * process runnable relative to other processes in the system we have
150  * a 1-second recalc to help out.
151  *
152  * This code also allows us to store sysclock_t data in the process structure
153  * without fear of an overrun, since sysclock_t are guarenteed to hold
154  * several seconds worth of count.
155  */
156 /* ARGSUSED */
157 static void
158 schedcpu(void *arg)
159 {
160 	struct proc *p;
161 
162 	FOREACH_PROC_IN_SYSTEM(p) {
163 		/*
164 		 * Increment time in/out of memory and sleep time
165 		 * (if sleeping).  We ignore overflow; with 16-bit int's
166 		 * (remember them?) overflow takes 45 days.
167 		 */
168 		crit_enter();
169 		p->p_swtime++;
170 		if (p->p_stat == SSLEEP || p->p_stat == SSTOP)
171 			p->p_slptime++;
172 
173 		/*
174 		 * Only recalculate processes that are active or have slept
175 		 * less then 2 seconds.  The schedulers understand this.
176 		 */
177 		if (p->p_slptime <= 1) {
178 			p->p_usched->recalculate(&p->p_lwp);
179 		} else {
180 			p->p_pctcpu = (p->p_pctcpu * ccpu) >> FSHIFT;
181 		}
182 		crit_exit();
183 	}
184 	wakeup((caddr_t)&lbolt);
185 	callout_reset(&schedcpu_callout, hz, schedcpu, NULL);
186 }
187 
188 /*
189  * This is only used by ps.  Generate a cpu percentage use over
190  * a period of one second.
191  */
192 void
193 updatepcpu(struct lwp *lp, int cpticks, int ttlticks)
194 {
195 	fixpt_t acc;
196 	int remticks;
197 
198 	acc = (cpticks << FSHIFT) / ttlticks;
199 	if (ttlticks >= ESTCPUFREQ) {
200 		lp->lwp_pctcpu = acc;
201 	} else {
202 		remticks = ESTCPUFREQ - ttlticks;
203 		lp->lwp_pctcpu = (acc * ttlticks + lp->lwp_pctcpu * remticks) /
204 				ESTCPUFREQ;
205 	}
206 }
207 
208 /*
209  * We're only looking at 7 bits of the address; everything is
210  * aligned to 4, lots of things are aligned to greater powers
211  * of 2.  Shift right by 8, i.e. drop the bottom 256 worth.
212  */
213 #define TABLESIZE	128
214 #define LOOKUP(x)	(((intptr_t)(x) >> 8) & (TABLESIZE - 1))
215 
216 static cpumask_t slpque_cpumasks[TABLESIZE];
217 
218 /*
219  * General scheduler initialization.  We force a reschedule 25 times
220  * a second by default.  Note that cpu0 is initialized in early boot and
221  * cannot make any high level calls.
222  *
223  * Each cpu has its own sleep queue.
224  */
225 void
226 sleep_gdinit(globaldata_t gd)
227 {
228 	static struct tslpque slpque_cpu0[TABLESIZE];
229 	int i;
230 
231 	if (gd->gd_cpuid == 0) {
232 		sched_quantum = (hz + 24) / 25;
233 		hogticks = 2 * sched_quantum;
234 
235 		gd->gd_tsleep_hash = slpque_cpu0;
236 	} else {
237 #if 0
238 		gd->gd_tsleep_hash = malloc(sizeof(slpque_cpu0),
239 					    M_TSLEEP, M_WAITOK | M_ZERO);
240 #endif
241 		gd->gd_tsleep_hash = slpque_cpu0;
242 	}
243 	for (i = 0; i < TABLESIZE; ++i)
244 		TAILQ_INIT(&gd->gd_tsleep_hash[i]);
245 }
246 
247 /*
248  * General sleep call.  Suspends the current process until a wakeup is
249  * performed on the specified identifier.  The process will then be made
250  * runnable with the specified priority.  Sleeps at most timo/hz seconds
251  * (0 means no timeout).  If flags includes PCATCH flag, signals are checked
252  * before and after sleeping, else signals are not checked.  Returns 0 if
253  * awakened, EWOULDBLOCK if the timeout expires.  If PCATCH is set and a
254  * signal needs to be delivered, ERESTART is returned if the current system
255  * call should be restarted if possible, and EINTR is returned if the system
256  * call should be interrupted by the signal (return EINTR).
257  *
258  * Note that if we are a process, we release_curproc() before messing with
259  * the LWKT scheduler.
260  *
261  * During autoconfiguration or after a panic, a sleep will simply
262  * lower the priority briefly to allow interrupts, then return.
263  */
264 int
265 tsleep(void *ident, int flags, const char *wmesg, int timo)
266 {
267 	struct thread *td = curthread;
268 	struct proc *p = td->td_proc;		/* may be NULL */
269 	globaldata_t gd;
270 	int sig = 0, catch = flags & PCATCH;
271 	int id = LOOKUP(ident);
272 	int oldpri;
273 	struct callout thandle;
274 
275 	/*
276 	 * NOTE: removed KTRPOINT, it could cause races due to blocking
277 	 * even in stable.  Just scrap it for now.
278 	 */
279 	if (cold || panicstr) {
280 		/*
281 		 * After a panic, or during autoconfiguration,
282 		 * just give interrupts a chance, then just return;
283 		 * don't run any other procs or panic below,
284 		 * in case this is the idle process and already asleep.
285 		 */
286 		splz();
287 		oldpri = td->td_pri & TDPRI_MASK;
288 		lwkt_setpri_self(safepri);
289 		lwkt_switch();
290 		lwkt_setpri_self(oldpri);
291 		return (0);
292 	}
293 	gd = td->td_gd;
294 	KKASSERT(td != &gd->gd_idlethread);	/* you must be kidding! */
295 	crit_enter_quick(td);
296 	KASSERT(ident != NULL, ("tsleep: no ident"));
297 	KASSERT(p == NULL || p->p_stat == SRUN, ("tsleep %p %s %d",
298 		ident, wmesg, p->p_stat));
299 
300 	td->td_wchan = ident;
301 	td->td_wmesg = wmesg;
302 	td->td_wdomain = flags & PDOMAIN_MASK;
303 	if (p) {
304 		if (flags & PNORESCHED)
305 			td->td_flags |= TDF_NORESCHED;
306 		p->p_usched->release_curproc(&p->p_lwp);
307 		p->p_slptime = 0;
308 	}
309 
310 	/*
311 	 * note: all of this occurs on the current cpu, including any
312 	 * callout-based wakeups, so a critical section is a sufficient
313 	 * interlock.
314 	 */
315 	lwkt_deschedule_self(td);
316 	TAILQ_INSERT_TAIL(&gd->gd_tsleep_hash[id], td, td_threadq);
317 	atomic_set_int(&slpque_cpumasks[id], gd->gd_cpumask);
318 	if (timo) {
319 		callout_init(&thandle);
320 		callout_reset(&thandle, timo, endtsleep, td);
321 	}
322 	/*
323 	 * We put ourselves on the sleep queue and start our timeout
324 	 * before calling CURSIG, as we could stop there, and a wakeup
325 	 * or a SIGCONT (or both) could occur while we were stopped.
326 	 * A SIGCONT would cause us to be marked as SSLEEP
327 	 * without resuming us, thus we must be ready for sleep
328 	 * when CURSIG is called.  If the wakeup happens while we're
329 	 * stopped, td->td_wchan will be 0 upon return from CURSIG.
330 	 */
331 	if (p) {
332 		if (catch) {
333 			p->p_flag |= P_SINTR;
334 			if ((sig = CURSIG(p))) {
335 				if (td->td_wchan) {
336 					unsleep(td);
337 					lwkt_schedule_self(td);
338 				}
339 				p->p_stat = SRUN;
340 				goto resume;
341 			}
342 			if (td->td_wchan == NULL) {
343 				catch = 0;
344 				goto resume;
345 			}
346 		} else {
347 			sig = 0;
348 		}
349 
350 		/*
351 		 * If we are not the current process we have to remove ourself
352 		 * from the run queue.
353 		 */
354 		KASSERT(p->p_stat == SRUN, ("PSTAT NOT SRUN %d %d", p->p_pid, p->p_stat));
355 		/*
356 		 * If this is the current 'user' process schedule another one.
357 		 */
358 		clrrunnable(p, SSLEEP);
359 		p->p_stats->p_ru.ru_nvcsw++;
360 		mi_switch(p);
361 		KASSERT(p->p_stat == SRUN, ("tsleep: stat not srun"));
362 	} else {
363 		lwkt_switch();
364 	}
365 	/*
366 	 * Make sure we haven't switched cpus while we were asleep.  It's
367 	 * not supposed to happen.
368 	 */
369 	KKASSERT(gd == td->td_gd);
370 resume:
371 	if (p)
372 		p->p_flag &= ~P_SINTR;
373 	crit_exit_quick(td);
374 	td->td_flags &= ~TDF_NORESCHED;
375 	if (td->td_flags & TDF_TIMEOUT) {
376 		td->td_flags &= ~TDF_TIMEOUT;
377 		if (sig == 0)
378 			return (EWOULDBLOCK);
379 	} else if (timo) {
380 		callout_stop(&thandle);
381 	} else if (td->td_wmesg) {
382 		/*
383 		 * This can happen if a thread is woken up directly.  Clear
384 		 * wmesg to avoid debugging confusion.
385 		 */
386 		td->td_wmesg = NULL;
387 	}
388 	/* inline of iscaught() */
389 	if (p) {
390 		if (catch && (sig != 0 || (sig = CURSIG(p)))) {
391 			if (SIGISMEMBER(p->p_sigacts->ps_sigintr, sig))
392 				return (EINTR);
393 			return (ERESTART);
394 		}
395 	}
396 	return (0);
397 }
398 
399 /*
400  * Implement the timeout for tsleep.  We interlock against
401  * wchan when setting TDF_TIMEOUT.  For processes we remove
402  * the sleep if the process is stopped rather then sleeping,
403  * so it remains stopped.
404  *
405  * This type of callout timeout had better be scheduled on the same
406  * cpu the process is sleeping on.
407  */
408 static void
409 endtsleep(void *arg)
410 {
411 	thread_t td = arg;
412 	struct proc *p;
413 
414 	crit_enter();
415 	if (td->td_wchan) {
416 		td->td_flags |= TDF_TIMEOUT;
417 		if ((p = td->td_proc) != NULL) {
418 			if (p->p_stat == SSLEEP)
419 				setrunnable(p);
420 			else
421 				unsleep(td);
422 		} else {
423 			unsleep(td);
424 			lwkt_schedule(td);
425 		}
426 	}
427 	crit_exit();
428 }
429 
430 /*
431  * Remove a process from its wait queue
432  *
433  * XXX not MP safe until called only on the cpu holding the sleeping
434  * process.
435  */
436 void
437 unsleep(struct thread *td)
438 {
439 	int id;
440 
441 	crit_enter();
442 	id = LOOKUP(td->td_wchan);
443 	if (td->td_wchan) {
444 		TAILQ_REMOVE(&td->td_gd->gd_tsleep_hash[id], td, td_threadq);
445 		if (TAILQ_FIRST(&td->td_gd->gd_tsleep_hash[id]) == NULL)
446 			atomic_clear_int(&slpque_cpumasks[id], td->td_gd->gd_cpumask);
447 		td->td_wchan = NULL;
448 	}
449 	crit_exit();
450 }
451 
452 /*
453  * Make all processes sleeping on the specified identifier runnable.
454  * count may be zero or one only.
455  *
456  * The domain encodes the sleep/wakeup domain AND the first cpu to check
457  * (which is always the current cpu).  As we iterate across cpus
458  */
459 static void
460 _wakeup(void *ident, int domain)
461 {
462 	struct tslpque *qp;
463 	struct thread *td;
464 	struct thread *ntd;
465 	globaldata_t gd;
466 	struct proc *p;
467 #if 0
468 #ifdef SMP
469 	cpumask_t mask;
470 	cpumask_t tmask;
471 	int startcpu;
472 	int nextcpu;
473 #endif
474 #endif
475 	int id;
476 
477 	crit_enter();
478 	gd = mycpu;
479 	id = LOOKUP(ident);
480 	qp = &gd->gd_tsleep_hash[id];
481 restart:
482 	for (td = TAILQ_FIRST(qp); td != NULL; td = ntd) {
483 		ntd = TAILQ_NEXT(td, td_threadq);
484 		if (td->td_wchan == ident &&
485 		    td->td_wdomain == (domain & PDOMAIN_MASK)
486 		) {
487 			TAILQ_REMOVE(qp, td, td_threadq);
488 			if (TAILQ_FIRST(qp) == NULL) {
489 				atomic_clear_int(&slpque_cpumasks[id],
490 						 gd->gd_cpumask);
491 			}
492 			td->td_wchan = NULL;
493 			if ((p = td->td_proc) != NULL && p->p_stat == SSLEEP) {
494 				p->p_stat = SRUN;
495 				if (p->p_flag & P_INMEM) {
496 					/*
497 					 * LWKT scheduled now, there is no
498 					 * userland runq interaction until
499 					 * the thread tries to return to user
500 					 * mode.  We do NOT call setrunqueue().
501 					 */
502 					lwkt_schedule(td);
503 				} else {
504 					p->p_flag |= P_SWAPINREQ;
505 					wakeup((caddr_t)&proc0);
506 				}
507 				/* END INLINE EXPANSION */
508 			} else if (p == NULL) {
509 				lwkt_schedule(td);
510 			}
511 			if (domain & PWAKEUP_ONE)
512 				goto done;
513 			goto restart;
514 		}
515 	}
516 
517 #if 0
518 #ifdef SMP
519 	/*
520 	 * We finished checking the current cpu but there still may be
521 	 * more work to do.  Either wakeup_one was requested and no matching
522 	 * thread was found, or a normal wakeup was requested and we have
523 	 * to continue checking cpus.
524 	 *
525 	 * The cpu that started the wakeup sequence is encoded in the domain.
526 	 * We use this information to determine which cpus still need to be
527 	 * checked, locate a candidate cpu, and chain the wakeup
528 	 * asynchronously with an IPI message.
529 	 *
530 	 * It should be noted that this scheme is actually less expensive then
531 	 * the old scheme when waking up multiple threads, since we send
532 	 * only one IPI message per target candidate which may then schedule
533 	 * multiple threads.  Before we could have wound up sending an IPI
534 	 * message for each thread on the target cpu (!= current cpu) that
535 	 * needed to be woken up.
536 	 *
537 	 * NOTE: Wakeups occuring on remote cpus are asynchronous.  This
538 	 * should be ok since we are passing idents in the IPI rather then
539 	 * thread pointers.
540 	 */
541 	if ((mask = slpque_cpumasks[id]) != 0) {
542 		/*
543 		 * Look for a cpu that might have work to do.  Mask out cpus
544 		 * which have already been processed.
545 		 *
546 		 * 31xxxxxxxxxxxxxxxxxxxxxxxxxxxxx0
547 		 *        ^        ^           ^
548 		 *      start   currentcpu    start
549 		 *      case2                 case1
550 		 *        *        *           *
551 		 * 11111111111111110000000000000111	case1
552 		 * 00000000111111110000000000000000	case2
553 		 *
554 		 * case1:  We started at start_case1 and processed through
555 		 *  	   to the current cpu.  We have to check any bits
556 		 *	   after the current cpu, then check bits before
557 		 *         the starting cpu.
558 		 *
559 		 * case2:  We have already checked all the bits from
560 		 *         start_case2 to the end, and from 0 to the current
561 		 *         cpu.  We just have the bits from the current cpu
562 		 *         to start_case2 left to check.
563 		 */
564 		startcpu = PWAKEUP_DECODE(domain);
565 		if (gd->gd_cpuid >= startcpu) {
566 			/*
567 			 * CASE1
568 			 */
569 			tmask = mask & ~((gd->gd_cpumask << 1) - 1);
570 			if (mask & tmask) {
571 				nextcpu = bsfl(mask & tmask);
572 				lwkt_send_ipiq2(globaldata_find(nextcpu),
573 						_wakeup, ident, domain);
574 			} else {
575 				tmask = (1 << startcpu) - 1;
576 				if (mask & tmask) {
577 					nextcpu = bsfl(mask & tmask);
578 					lwkt_send_ipiq2(
579 						    globaldata_find(nextcpu),
580 						    _wakeup, ident, domain);
581 				}
582 			}
583 		} else {
584 			/*
585 			 * CASE2
586 			 */
587 			tmask = ~((gd->gd_cpumask << 1) - 1) &
588 				 ((1 << startcpu) - 1);
589 			if (mask & tmask) {
590 				nextcpu = bsfl(mask & tmask);
591 				lwkt_send_ipiq2(globaldata_find(nextcpu),
592 						_wakeup, ident, domain);
593 			}
594 		}
595 	}
596 #endif
597 #endif
598 done:
599 	crit_exit();
600 }
601 
602 void
603 wakeup(void *ident)
604 {
605     _wakeup(ident, PWAKEUP_ENCODE(0, mycpu->gd_cpuid));
606 }
607 
608 void
609 wakeup_one(void *ident)
610 {
611     /* XXX potentially round-robin the first responding cpu */
612     _wakeup(ident, PWAKEUP_ENCODE(0, mycpu->gd_cpuid) | PWAKEUP_ONE);
613 }
614 
615 void
616 wakeup_domain(void *ident, int domain)
617 {
618     _wakeup(ident, PWAKEUP_ENCODE(domain, mycpu->gd_cpuid));
619 }
620 
621 void
622 wakeup_domain_one(void *ident, int domain)
623 {
624     /* XXX potentially round-robin the first responding cpu */
625     _wakeup(ident, PWAKEUP_ENCODE(domain, mycpu->gd_cpuid) | PWAKEUP_ONE);
626 }
627 
628 /*
629  * The machine independent parts of mi_switch().
630  *
631  * 'p' must be the current process.
632  */
633 void
634 mi_switch(struct proc *p)
635 {
636 	thread_t td = p->p_thread;
637 	struct rlimit *rlim;
638 	u_int64_t ttime;
639 
640 	KKASSERT(td == mycpu->gd_curthread);
641 
642 	crit_enter_quick(td);
643 
644 	/*
645 	 * Check if the process exceeds its cpu resource allocation.
646 	 * If over max, kill it.  Time spent in interrupts is not
647 	 * included.  YYY 64 bit match is expensive.  Ick.
648 	 *
649 	 * XXX move to the once-a-second process scan
650 	 */
651 	ttime = td->td_sticks + td->td_uticks;
652 	if (p->p_stat != SZOMB && p->p_limit->p_cpulimit != RLIM_INFINITY &&
653 	    ttime > p->p_limit->p_cpulimit) {
654 		rlim = &p->p_rlimit[RLIMIT_CPU];
655 		if (ttime / (rlim_t)1000000 >= rlim->rlim_max) {
656 			killproc(p, "exceeded maximum CPU limit");
657 		} else {
658 			psignal(p, SIGXCPU);
659 			if (rlim->rlim_cur < rlim->rlim_max) {
660 				/* XXX: we should make a private copy */
661 				rlim->rlim_cur += 5;
662 			}
663 		}
664 	}
665 
666 	/*
667 	 * If we are in a SSTOPped state we deschedule ourselves.
668 	 * YYY this needs to be cleaned up, remember that LWKTs stay on
669 	 * their run queue which works differently then the user scheduler
670 	 * which removes the process from the runq when it runs it.
671 	 */
672 	mycpu->gd_cnt.v_swtch++;
673 	if (p->p_stat == SSTOP)
674 		lwkt_deschedule_self(td);
675 	lwkt_switch();
676 	crit_exit_quick(td);
677 }
678 
679 /*
680  * Change process state to be runnable, placing it on the run queue if it
681  * is in memory, and awakening the swapper if it isn't in memory.
682  *
683  * This operation MUST OCCUR on the cpu that the thread is sleeping on.
684  */
685 void
686 setrunnable(struct proc *p)
687 {
688 	crit_enter();
689 
690 	switch (p->p_stat) {
691 	case 0:
692 	case SRUN:
693 	case SZOMB:
694 	default:
695 		panic("setrunnable");
696 	case SSTOP:
697 	case SSLEEP:
698 		unsleep(p->p_thread);	/* e.g. when sending signals */
699 		break;
700 
701 	case SIDL:
702 		break;
703 	}
704 	p->p_stat = SRUN;
705 
706 	/*
707 	 * The process is controlled by LWKT at this point, we do not mess
708 	 * around with the userland scheduler until the thread tries to
709 	 * return to user mode.  We do not clear p_slptime or call
710 	 * setrunqueue().
711 	 */
712 	if (p->p_flag & P_INMEM) {
713 		lwkt_schedule(p->p_thread);
714 	} else {
715 		p->p_flag |= P_SWAPINREQ;
716 		wakeup((caddr_t)&proc0);
717 	}
718 	crit_exit();
719 }
720 
721 /*
722  * Yield / synchronous reschedule.  This is a bit tricky because the trap
723  * code might have set a lazy release on the switch function.   Setting
724  * P_PASSIVE_ACQ will ensure that the lazy release executes when we call
725  * switch, and that we are given a greater chance of affinity with our
726  * current cpu.
727  *
728  * We call lwkt_setpri_self() to rotate our thread to the end of the lwkt
729  * run queue.  lwkt_switch() will also execute any assigned passive release
730  * (which usually calls release_curproc()), allowing a same/higher priority
731  * process to be designated as the current process.
732  *
733  * While it is possible for a lower priority process to be designated,
734  * it's call to lwkt_maybe_switch() in acquire_curproc() will likely
735  * round-robin back to us and we will be able to re-acquire the current
736  * process designation.
737  */
738 void
739 uio_yield(void)
740 {
741 	struct thread *td = curthread;
742 	struct proc *p = td->td_proc;
743 
744 	lwkt_setpri_self(td->td_pri & TDPRI_MASK);
745 	if (p) {
746 		p->p_flag |= P_PASSIVE_ACQ;
747 		lwkt_switch();
748 		p->p_flag &= ~P_PASSIVE_ACQ;
749 	} else {
750 		lwkt_switch();
751 	}
752 }
753 
754 /*
755  * Change the process state to NOT be runnable, removing it from the run
756  * queue.
757  */
758 void
759 clrrunnable(struct proc *p, int stat)
760 {
761 	crit_enter_quick(p->p_thread);
762 	if (p->p_stat == SRUN && (p->p_flag & P_ONRUNQ))
763 		p->p_usched->remrunqueue(&p->p_lwp);
764 	p->p_stat = stat;
765 	crit_exit_quick(p->p_thread);
766 }
767 
768 /*
769  * Compute a tenex style load average of a quantity on
770  * 1, 5 and 15 minute intervals.
771  */
772 static void
773 loadav(void *arg)
774 {
775 	int i, nrun;
776 	struct loadavg *avg;
777 	struct proc *p;
778 	thread_t td;
779 
780 	avg = &averunnable;
781 	nrun = 0;
782 	FOREACH_PROC_IN_SYSTEM(p) {
783 		switch (p->p_stat) {
784 		case SRUN:
785 			if ((td = p->p_thread) == NULL)
786 				break;
787 			if (td->td_flags & TDF_BLOCKED)
788 				break;
789 			/* fall through */
790 		case SIDL:
791 			nrun++;
792 			break;
793 		default:
794 			break;
795 		}
796 	}
797 	for (i = 0; i < 3; i++)
798 		avg->ldavg[i] = (cexp[i] * avg->ldavg[i] +
799 		    nrun * FSCALE * (FSCALE - cexp[i])) >> FSHIFT;
800 
801 	/*
802 	 * Schedule the next update to occur after 5 seconds, but add a
803 	 * random variation to avoid synchronisation with processes that
804 	 * run at regular intervals.
805 	 */
806 	callout_reset(&loadav_callout, hz * 4 + (int)(random() % (hz * 2 + 1)),
807 	    loadav, NULL);
808 }
809 
810 /* ARGSUSED */
811 static void
812 sched_setup(void *dummy)
813 {
814 	callout_init(&loadav_callout);
815 	callout_init(&schedcpu_callout);
816 
817 	/* Kick off timeout driven events by calling first time. */
818 	schedcpu(NULL);
819 	loadav(NULL);
820 }
821 
822