xref: /netbsd-src/sys/kern/kern_synch.c (revision 8ac07aec990b9d2e483062509d0a9fa5b4f57cf2)
1 /*	$NetBSD: kern_synch.c,v 1.229 2008/04/24 18:39:24 ad Exp $	*/
2 
3 /*-
4  * Copyright (c) 1999, 2000, 2004, 2006, 2007, 2008 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
9  * NASA Ames Research Center, by Charles M. Hannum, Andrew Doran and
10  * Daniel Sieger.
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. All advertising materials mentioning features or use of this software
21  *    must display the following acknowledgement:
22  *	This product includes software developed by the NetBSD
23  *	Foundation, Inc. and its contributors.
24  * 4. Neither the name of The NetBSD Foundation nor the names of its
25  *    contributors may be used to endorse or promote products derived
26  *    from this software without specific prior written permission.
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
29  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
30  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
31  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
32  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
33  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
34  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
35  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
36  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
37  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
38  * POSSIBILITY OF SUCH DAMAGE.
39  */
40 
41 /*
42  * Copyright (c) 2007, 2008 Mindaugas Rasiukevicius <rmind at NetBSD org>
43  * All rights reserved.
44  *
45  * Redistribution and use in source and binary forms, with or without
46  * modification, are permitted provided that the following conditions
47  * are met:
48  * 1. Redistributions of source code must retain the above copyright
49  *    notice, this list of conditions and the following disclaimer.
50  * 2. Redistributions in binary form must reproduce the above copyright
51  *    notice, this list of conditions and the following disclaimer in the
52  *    documentation and/or other materials provided with the distribution.
53  *
54  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
55  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
56  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
57  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
58  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
59  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
60  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
61  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
62  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
63  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
64  * SUCH DAMAGE.
65  */
66 
67 /*-
68  * Copyright (c) 1982, 1986, 1990, 1991, 1993
69  *	The Regents of the University of California.  All rights reserved.
70  * (c) UNIX System Laboratories, Inc.
71  * All or some portions of this file are derived from material licensed
72  * to the University of California by American Telephone and Telegraph
73  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
74  * the permission of UNIX System Laboratories, Inc.
75  *
76  * Redistribution and use in source and binary forms, with or without
77  * modification, are permitted provided that the following conditions
78  * are met:
79  * 1. Redistributions of source code must retain the above copyright
80  *    notice, this list of conditions and the following disclaimer.
81  * 2. Redistributions in binary form must reproduce the above copyright
82  *    notice, this list of conditions and the following disclaimer in the
83  *    documentation and/or other materials provided with the distribution.
84  * 3. Neither the name of the University nor the names of its contributors
85  *    may be used to endorse or promote products derived from this software
86  *    without specific prior written permission.
87  *
88  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
89  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
90  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
91  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
92  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
93  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
94  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
95  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
96  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
97  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
98  * SUCH DAMAGE.
99  *
100  *	@(#)kern_synch.c	8.9 (Berkeley) 5/19/95
101  */
102 
103 #include <sys/cdefs.h>
104 __KERNEL_RCSID(0, "$NetBSD: kern_synch.c,v 1.229 2008/04/24 18:39:24 ad Exp $");
105 
106 #include "opt_kstack.h"
107 #include "opt_lockdebug.h"
108 #include "opt_multiprocessor.h"
109 #include "opt_perfctrs.h"
110 
111 #define	__MUTEX_PRIVATE
112 
113 #include <sys/param.h>
114 #include <sys/systm.h>
115 #include <sys/proc.h>
116 #include <sys/kernel.h>
117 #if defined(PERFCTRS)
118 #include <sys/pmc.h>
119 #endif
120 #include <sys/cpu.h>
121 #include <sys/resourcevar.h>
122 #include <sys/sched.h>
123 #include <sys/syscall_stats.h>
124 #include <sys/sleepq.h>
125 #include <sys/lockdebug.h>
126 #include <sys/evcnt.h>
127 #include <sys/intr.h>
128 #include <sys/lwpctl.h>
129 #include <sys/atomic.h>
130 #include <sys/simplelock.h>
131 #include <sys/bitops.h>
132 #include <sys/kmem.h>
133 #include <sys/sysctl.h>
134 #include <sys/idle.h>
135 
136 #include <uvm/uvm_extern.h>
137 
138 /*
139  * Priority related defintions.
140  */
141 #define	PRI_TS_COUNT	(NPRI_USER)
142 #define	PRI_RT_COUNT	(PRI_COUNT - PRI_TS_COUNT)
143 #define	PRI_HTS_RANGE	(PRI_TS_COUNT / 10)
144 
145 #define	PRI_HIGHEST_TS	(MAXPRI_USER)
146 
147 /*
148  * Bits per map.
149  */
150 #define	BITMAP_BITS	(32)
151 #define	BITMAP_SHIFT	(5)
152 #define	BITMAP_MSB	(0x80000000U)
153 #define	BITMAP_MASK	(BITMAP_BITS - 1)
154 
155 /*
156  * Structures, runqueue.
157  */
158 
159 typedef struct {
160 	TAILQ_HEAD(, lwp) q_head;
161 } queue_t;
162 
163 typedef struct {
164 	/* Lock and bitmap */
165 	uint32_t	r_bitmap[PRI_COUNT >> BITMAP_SHIFT];
166 	/* Counters */
167 	u_int		r_count;	/* Count of the threads */
168 	u_int		r_avgcount;	/* Average count of threads */
169 	u_int		r_mcount;	/* Count of migratable threads */
170 	/* Runqueues */
171 	queue_t		r_rt_queue[PRI_RT_COUNT];
172 	queue_t		r_ts_queue[PRI_TS_COUNT];
173 } runqueue_t;
174 
175 static u_int	sched_unsleep(struct lwp *, bool);
176 static void	sched_changepri(struct lwp *, pri_t);
177 static void	sched_lendpri(struct lwp *, pri_t);
178 static void	*sched_getrq(runqueue_t *, const pri_t);
179 #ifdef MULTIPROCESSOR
180 static lwp_t	*sched_catchlwp(void);
181 static void	sched_balance(void *);
182 #endif
183 
184 syncobj_t sleep_syncobj = {
185 	SOBJ_SLEEPQ_SORTED,
186 	sleepq_unsleep,
187 	sleepq_changepri,
188 	sleepq_lendpri,
189 	syncobj_noowner,
190 };
191 
192 syncobj_t sched_syncobj = {
193 	SOBJ_SLEEPQ_SORTED,
194 	sched_unsleep,
195 	sched_changepri,
196 	sched_lendpri,
197 	syncobj_noowner,
198 };
199 
200 const int 	schedppq = 1;
201 callout_t 	sched_pstats_ch;
202 unsigned	sched_pstats_ticks;
203 kcondvar_t	lbolt;			/* once a second sleep address */
204 
205 /*
206  * Migration and balancing.
207  */
208 static u_int	cacheht_time;		/* Cache hotness time */
209 static u_int	min_catch;		/* Minimal LWP count for catching */
210 static u_int	balance_period;		/* Balance period */
211 static struct cpu_info *worker_ci;	/* Victim CPU */
212 #ifdef MULTIPROCESSOR
213 static struct callout balance_ch;	/* Callout of balancer */
214 #endif
215 
216 /*
217  * During autoconfiguration or after a panic, a sleep will simply lower the
218  * priority briefly to allow interrupts, then return.  The priority to be
219  * used (safepri) is machine-dependent, thus this value is initialized and
220  * maintained in the machine-dependent layers.  This priority will typically
221  * be 0, or the lowest priority that is safe for use on the interrupt stack;
222  * it can be made higher to block network software interrupts after panics.
223  */
224 int	safepri;
225 
226 /*
227  * OBSOLETE INTERFACE
228  *
229  * General sleep call.  Suspends the current process until a wakeup is
230  * performed on the specified identifier.  The process will then be made
231  * runnable with the specified priority.  Sleeps at most timo/hz seconds (0
232  * means no timeout).  If pri includes PCATCH flag, signals are checked
233  * before and after sleeping, else signals are not checked.  Returns 0 if
234  * awakened, EWOULDBLOCK if the timeout expires.  If PCATCH is set and a
235  * signal needs to be delivered, ERESTART is returned if the current system
236  * call should be restarted if possible, and EINTR is returned if the system
237  * call should be interrupted by the signal (return EINTR).
238  *
239  * The interlock is held until we are on a sleep queue. The interlock will
240  * be locked before returning back to the caller unless the PNORELOCK flag
241  * is specified, in which case the interlock will always be unlocked upon
242  * return.
243  */
244 int
245 ltsleep(wchan_t ident, pri_t priority, const char *wmesg, int timo,
246 	volatile struct simplelock *interlock)
247 {
248 	struct lwp *l = curlwp;
249 	sleepq_t *sq;
250 	int error;
251 
252 	KASSERT((l->l_pflag & LP_INTR) == 0);
253 
254 	if (sleepq_dontsleep(l)) {
255 		(void)sleepq_abort(NULL, 0);
256 		if ((priority & PNORELOCK) != 0)
257 			simple_unlock(interlock);
258 		return 0;
259 	}
260 
261 	l->l_kpriority = true;
262 	sq = sleeptab_lookup(&sleeptab, ident);
263 	sleepq_enter(sq, l);
264 	sleepq_enqueue(sq, ident, wmesg, &sleep_syncobj);
265 
266 	if (interlock != NULL) {
267 		KASSERT(simple_lock_held(interlock));
268 		simple_unlock(interlock);
269 	}
270 
271 	error = sleepq_block(timo, priority & PCATCH);
272 
273 	if (interlock != NULL && (priority & PNORELOCK) == 0)
274 		simple_lock(interlock);
275 
276 	return error;
277 }
278 
279 int
280 mtsleep(wchan_t ident, pri_t priority, const char *wmesg, int timo,
281 	kmutex_t *mtx)
282 {
283 	struct lwp *l = curlwp;
284 	sleepq_t *sq;
285 	int error;
286 
287 	KASSERT((l->l_pflag & LP_INTR) == 0);
288 
289 	if (sleepq_dontsleep(l)) {
290 		(void)sleepq_abort(mtx, (priority & PNORELOCK) != 0);
291 		return 0;
292 	}
293 
294 	l->l_kpriority = true;
295 	sq = sleeptab_lookup(&sleeptab, ident);
296 	sleepq_enter(sq, l);
297 	sleepq_enqueue(sq, ident, wmesg, &sleep_syncobj);
298 	mutex_exit(mtx);
299 	error = sleepq_block(timo, priority & PCATCH);
300 
301 	if ((priority & PNORELOCK) == 0)
302 		mutex_enter(mtx);
303 
304 	return error;
305 }
306 
307 /*
308  * General sleep call for situations where a wake-up is not expected.
309  */
310 int
311 kpause(const char *wmesg, bool intr, int timo, kmutex_t *mtx)
312 {
313 	struct lwp *l = curlwp;
314 	sleepq_t *sq;
315 	int error;
316 
317 	if (sleepq_dontsleep(l))
318 		return sleepq_abort(NULL, 0);
319 
320 	if (mtx != NULL)
321 		mutex_exit(mtx);
322 	l->l_kpriority = true;
323 	sq = sleeptab_lookup(&sleeptab, l);
324 	sleepq_enter(sq, l);
325 	sleepq_enqueue(sq, l, wmesg, &sleep_syncobj);
326 	error = sleepq_block(timo, intr);
327 	if (mtx != NULL)
328 		mutex_enter(mtx);
329 
330 	return error;
331 }
332 
333 /*
334  * OBSOLETE INTERFACE
335  *
336  * Make all processes sleeping on the specified identifier runnable.
337  */
338 void
339 wakeup(wchan_t ident)
340 {
341 	sleepq_t *sq;
342 
343 	if (cold)
344 		return;
345 
346 	sq = sleeptab_lookup(&sleeptab, ident);
347 	sleepq_wake(sq, ident, (u_int)-1);
348 }
349 
350 /*
351  * OBSOLETE INTERFACE
352  *
353  * Make the highest priority process first in line on the specified
354  * identifier runnable.
355  */
356 void
357 wakeup_one(wchan_t ident)
358 {
359 	sleepq_t *sq;
360 
361 	if (cold)
362 		return;
363 
364 	sq = sleeptab_lookup(&sleeptab, ident);
365 	sleepq_wake(sq, ident, 1);
366 }
367 
368 
369 /*
370  * General yield call.  Puts the current process back on its run queue and
371  * performs a voluntary context switch.  Should only be called when the
372  * current process explicitly requests it (eg sched_yield(2)).
373  */
374 void
375 yield(void)
376 {
377 	struct lwp *l = curlwp;
378 
379 	KERNEL_UNLOCK_ALL(l, &l->l_biglocks);
380 	lwp_lock(l);
381 	KASSERT(lwp_locked(l, l->l_cpu->ci_schedstate.spc_lwplock));
382 	KASSERT(l->l_stat == LSONPROC);
383 	l->l_kpriority = false;
384 	(void)mi_switch(l);
385 	KERNEL_LOCK(l->l_biglocks, l);
386 }
387 
388 /*
389  * General preemption call.  Puts the current process back on its run queue
390  * and performs an involuntary context switch.
391  */
392 void
393 preempt(void)
394 {
395 	struct lwp *l = curlwp;
396 
397 	KERNEL_UNLOCK_ALL(l, &l->l_biglocks);
398 	lwp_lock(l);
399 	KASSERT(lwp_locked(l, l->l_cpu->ci_schedstate.spc_lwplock));
400 	KASSERT(l->l_stat == LSONPROC);
401 	l->l_kpriority = false;
402 	l->l_nivcsw++;
403 	(void)mi_switch(l);
404 	KERNEL_LOCK(l->l_biglocks, l);
405 }
406 
407 /*
408  * Compute the amount of time during which the current lwp was running.
409  *
410  * - update l_rtime unless it's an idle lwp.
411  */
412 
413 void
414 updatertime(lwp_t *l, const struct bintime *now)
415 {
416 
417 	if ((l->l_flag & LW_IDLE) != 0)
418 		return;
419 
420 	/* rtime += now - stime */
421 	bintime_add(&l->l_rtime, now);
422 	bintime_sub(&l->l_rtime, &l->l_stime);
423 }
424 
425 /*
426  * The machine independent parts of context switch.
427  *
428  * Returns 1 if another LWP was actually run.
429  */
430 int
431 mi_switch(lwp_t *l)
432 {
433 	struct cpu_info *ci, *tci = NULL;
434 	struct schedstate_percpu *spc;
435 	struct lwp *newl;
436 	int retval, oldspl;
437 	struct bintime bt;
438 	bool returning;
439 
440 	KASSERT(lwp_locked(l, NULL));
441 	LOCKDEBUG_BARRIER(l->l_mutex, 1);
442 
443 #ifdef KSTACK_CHECK_MAGIC
444 	kstack_check_magic(l);
445 #endif
446 
447 	binuptime(&bt);
448 
449 	KDASSERT(l->l_cpu == curcpu());
450 	ci = l->l_cpu;
451 	spc = &ci->ci_schedstate;
452 	returning = false;
453 	newl = NULL;
454 
455 	/*
456 	 * If we have been asked to switch to a specific LWP, then there
457 	 * is no need to inspect the run queues.  If a soft interrupt is
458 	 * blocking, then return to the interrupted thread without adjusting
459 	 * VM context or its start time: neither have been changed in order
460 	 * to take the interrupt.
461 	 */
462 	if (l->l_switchto != NULL) {
463 		if ((l->l_pflag & LP_INTR) != 0) {
464 			returning = true;
465 			softint_block(l);
466 			if ((l->l_flag & LW_TIMEINTR) != 0)
467 				updatertime(l, &bt);
468 		}
469 		newl = l->l_switchto;
470 		l->l_switchto = NULL;
471 	}
472 #ifndef __HAVE_FAST_SOFTINTS
473 	else if (ci->ci_data.cpu_softints != 0) {
474 		/* There are pending soft interrupts, so pick one. */
475 		newl = softint_picklwp();
476 		newl->l_stat = LSONPROC;
477 		newl->l_flag |= LW_RUNNING;
478 	}
479 #endif	/* !__HAVE_FAST_SOFTINTS */
480 
481 	/* Count time spent in current system call */
482 	if (!returning) {
483 		SYSCALL_TIME_SLEEP(l);
484 
485 		/*
486 		 * XXXSMP If we are using h/w performance counters,
487 		 * save context.
488 		 */
489 #if PERFCTRS
490 		if (PMC_ENABLED(l->l_proc)) {
491 			pmc_save_context(l->l_proc);
492 		}
493 #endif
494 		updatertime(l, &bt);
495 	}
496 
497 	/*
498 	 * If on the CPU and we have gotten this far, then we must yield.
499 	 */
500 	KASSERT(l->l_stat != LSRUN);
501 	if (l->l_stat == LSONPROC && (l->l_target_cpu || l != newl)) {
502 		KASSERT(lwp_locked(l, spc->spc_lwplock));
503 
504 		if (l->l_target_cpu == l->l_cpu) {
505 			l->l_target_cpu = NULL;
506 		} else {
507 			tci = l->l_target_cpu;
508 		}
509 
510 		if (__predict_false(tci != NULL)) {
511 			/* Double-lock the runqueues */
512 			spc_dlock(ci, tci);
513 		} else {
514 			/* Lock the runqueue */
515 			spc_lock(ci);
516 		}
517 
518 		if ((l->l_flag & LW_IDLE) == 0) {
519 			l->l_stat = LSRUN;
520 			if (__predict_false(tci != NULL)) {
521 				/*
522 				 * Set the new CPU, lock and unset the
523 				 * l_target_cpu - thread will be enqueued
524 				 * to the runqueue of target CPU.
525 				 */
526 				l->l_cpu = tci;
527 				lwp_setlock(l, tci->ci_schedstate.spc_mutex);
528 				l->l_target_cpu = NULL;
529 			} else {
530 				lwp_setlock(l, spc->spc_mutex);
531 			}
532 			sched_enqueue(l, true);
533 		} else {
534 			KASSERT(tci == NULL);
535 			l->l_stat = LSIDL;
536 		}
537 	} else {
538 		/* Lock the runqueue */
539 		spc_lock(ci);
540 	}
541 
542 	/*
543 	 * Let sched_nextlwp() select the LWP to run the CPU next.
544 	 * If no LWP is runnable, select the idle LWP.
545 	 *
546 	 * Note that spc_lwplock might not necessary be held, and
547 	 * new thread would be unlocked after setting the LWP-lock.
548 	 */
549 	if (newl == NULL) {
550 		newl = sched_nextlwp();
551 		if (newl != NULL) {
552 			sched_dequeue(newl);
553 			KASSERT(lwp_locked(newl, spc->spc_mutex));
554 			newl->l_stat = LSONPROC;
555 			newl->l_cpu = ci;
556 			newl->l_flag |= LW_RUNNING;
557 			lwp_setlock(newl, spc->spc_lwplock);
558 		} else {
559 			newl = ci->ci_data.cpu_idlelwp;
560 			newl->l_stat = LSONPROC;
561 			newl->l_flag |= LW_RUNNING;
562 		}
563 		/*
564 		 * Only clear want_resched if there are no
565 		 * pending (slow) software interrupts.
566 		 */
567 		ci->ci_want_resched = ci->ci_data.cpu_softints;
568 		spc->spc_flags &= ~SPCF_SWITCHCLEAR;
569 		spc->spc_curpriority = lwp_eprio(newl);
570 	}
571 
572 	/* Items that must be updated with the CPU locked. */
573 	if (!returning) {
574 		/* Update the new LWP's start time. */
575 		newl->l_stime = bt;
576 
577 		/*
578 		 * ci_curlwp changes when a fast soft interrupt occurs.
579 		 * We use cpu_onproc to keep track of which kernel or
580 		 * user thread is running 'underneath' the software
581 		 * interrupt.  This is important for time accounting,
582 		 * itimers and forcing user threads to preempt (aston).
583 		 */
584 		ci->ci_data.cpu_onproc = newl;
585 	}
586 
587 	if (l != newl) {
588 		struct lwp *prevlwp;
589 
590 		/* Release all locks, but leave the current LWP locked */
591 		if (l->l_mutex == l->l_cpu->ci_schedstate.spc_mutex) {
592 			/*
593 			 * In case of migration, drop the local runqueue
594 			 * lock, thread is on other runqueue now.
595 			 */
596 			if (__predict_false(tci != NULL))
597 				spc_unlock(ci);
598 			/*
599 			 * Drop spc_lwplock, if the current LWP has been moved
600 			 * to the run queue (it is now locked by spc_mutex).
601 			 */
602 			mutex_spin_exit(spc->spc_lwplock);
603 		} else {
604 			/*
605 			 * Otherwise, drop the spc_mutex, we are done with the
606 			 * run queues.
607 			 */
608 			mutex_spin_exit(spc->spc_mutex);
609 			KASSERT(tci == NULL);
610 		}
611 
612 		/*
613 		 * Mark that context switch is going to be perfomed
614 		 * for this LWP, to protect it from being switched
615 		 * to on another CPU.
616 		 */
617 		KASSERT(l->l_ctxswtch == 0);
618 		l->l_ctxswtch = 1;
619 		l->l_ncsw++;
620 		l->l_flag &= ~LW_RUNNING;
621 
622 		/*
623 		 * Increase the count of spin-mutexes before the release
624 		 * of the last lock - we must remain at IPL_SCHED during
625 		 * the context switch.
626 		 */
627 		oldspl = MUTEX_SPIN_OLDSPL(ci);
628 		ci->ci_mtx_count--;
629 		lwp_unlock(l);
630 
631 		/* Count the context switch on this CPU. */
632 		ci->ci_data.cpu_nswtch++;
633 
634 		/* Update status for lwpctl, if present. */
635 		if (l->l_lwpctl != NULL)
636 			l->l_lwpctl->lc_curcpu = LWPCTL_CPU_NONE;
637 
638 		/*
639 		 * Save old VM context, unless a soft interrupt
640 		 * handler is blocking.
641 		 */
642 		if (!returning)
643 			pmap_deactivate(l);
644 
645 		/*
646 		 * We may need to spin-wait for if 'newl' is still
647 		 * context switching on another CPU.
648 		 */
649 		if (newl->l_ctxswtch != 0) {
650 			u_int count;
651 			count = SPINLOCK_BACKOFF_MIN;
652 			while (newl->l_ctxswtch)
653 				SPINLOCK_BACKOFF(count);
654 		}
655 
656 		/* Switch to the new LWP.. */
657 		prevlwp = cpu_switchto(l, newl, returning);
658 		ci = curcpu();
659 
660 		/*
661 		 * Switched away - we have new curlwp.
662 		 * Restore VM context and IPL.
663 		 */
664 		pmap_activate(l);
665 		if (prevlwp != NULL) {
666 			/* Normalize the count of the spin-mutexes */
667 			ci->ci_mtx_count++;
668 			/* Unmark the state of context switch */
669 			membar_exit();
670 			prevlwp->l_ctxswtch = 0;
671 		}
672 		splx(oldspl);
673 
674 		/* Update status for lwpctl, if present. */
675 		if (l->l_lwpctl != NULL) {
676 			l->l_lwpctl->lc_curcpu = (int)cpu_index(ci);
677 			l->l_lwpctl->lc_pctr++;
678 		}
679 
680 		retval = 1;
681 	} else {
682 		/* Nothing to do - just unlock and return. */
683 		KASSERT(tci == NULL);
684 		spc_unlock(ci);
685 		lwp_unlock(l);
686 		retval = 0;
687 	}
688 
689 	KASSERT(l == curlwp);
690 	KASSERT(l->l_stat == LSONPROC);
691 	KASSERT(l->l_cpu == ci);
692 
693 	/*
694 	 * XXXSMP If we are using h/w performance counters, restore context.
695 	 */
696 #if PERFCTRS
697 	if (PMC_ENABLED(l->l_proc)) {
698 		pmc_restore_context(l->l_proc);
699 	}
700 #endif
701 	SYSCALL_TIME_WAKEUP(l);
702 	LOCKDEBUG_BARRIER(NULL, 1);
703 
704 	return retval;
705 }
706 
707 /*
708  * Change process state to be runnable, placing it on the run queue if it is
709  * in memory, and awakening the swapper if it isn't in memory.
710  *
711  * Call with the process and LWP locked.  Will return with the LWP unlocked.
712  */
713 void
714 setrunnable(struct lwp *l)
715 {
716 	struct proc *p = l->l_proc;
717 	struct cpu_info *ci;
718 	sigset_t *ss;
719 
720 	KASSERT((l->l_flag & LW_IDLE) == 0);
721 	KASSERT(mutex_owned(p->p_lock));
722 	KASSERT(lwp_locked(l, NULL));
723 	KASSERT(l->l_mutex != l->l_cpu->ci_schedstate.spc_mutex);
724 
725 	switch (l->l_stat) {
726 	case LSSTOP:
727 		/*
728 		 * If we're being traced (possibly because someone attached us
729 		 * while we were stopped), check for a signal from the debugger.
730 		 */
731 		if ((p->p_slflag & PSL_TRACED) != 0 && p->p_xstat != 0) {
732 			if ((sigprop[p->p_xstat] & SA_TOLWP) != 0)
733 				ss = &l->l_sigpend.sp_set;
734 			else
735 				ss = &p->p_sigpend.sp_set;
736 			sigaddset(ss, p->p_xstat);
737 			signotify(l);
738 		}
739 		p->p_nrlwps++;
740 		break;
741 	case LSSUSPENDED:
742 		l->l_flag &= ~LW_WSUSPEND;
743 		p->p_nrlwps++;
744 		cv_broadcast(&p->p_lwpcv);
745 		break;
746 	case LSSLEEP:
747 		KASSERT(l->l_wchan != NULL);
748 		break;
749 	default:
750 		panic("setrunnable: lwp %p state was %d", l, l->l_stat);
751 	}
752 
753 	/*
754 	 * If the LWP was sleeping interruptably, then it's OK to start it
755 	 * again.  If not, mark it as still sleeping.
756 	 */
757 	if (l->l_wchan != NULL) {
758 		l->l_stat = LSSLEEP;
759 		/* lwp_unsleep() will release the lock. */
760 		lwp_unsleep(l, true);
761 		return;
762 	}
763 
764 	/*
765 	 * If the LWP is still on the CPU, mark it as LSONPROC.  It may be
766 	 * about to call mi_switch(), in which case it will yield.
767 	 */
768 	if ((l->l_flag & LW_RUNNING) != 0) {
769 		l->l_stat = LSONPROC;
770 		l->l_slptime = 0;
771 		lwp_unlock(l);
772 		return;
773 	}
774 
775 	/*
776 	 * Look for a CPU to run.
777 	 * Set the LWP runnable.
778 	 */
779 	ci = sched_takecpu(l);
780 	l->l_cpu = ci;
781 	if (l->l_mutex != l->l_cpu->ci_schedstate.spc_mutex) {
782 		lwp_unlock_to(l, ci->ci_schedstate.spc_mutex);
783 		lwp_lock(l);
784 	}
785 	sched_setrunnable(l);
786 	l->l_stat = LSRUN;
787 	l->l_slptime = 0;
788 
789 	/*
790 	 * If thread is swapped out - wake the swapper to bring it back in.
791 	 * Otherwise, enter it into a run queue.
792 	 */
793 	if (l->l_flag & LW_INMEM) {
794 		sched_enqueue(l, false);
795 		resched_cpu(l);
796 		lwp_unlock(l);
797 	} else {
798 		lwp_unlock(l);
799 		uvm_kick_scheduler();
800 	}
801 }
802 
803 /*
804  * suspendsched:
805  *
806  *	Convert all non-L_SYSTEM LSSLEEP or LSRUN LWPs to LSSUSPENDED.
807  */
808 void
809 suspendsched(void)
810 {
811 	CPU_INFO_ITERATOR cii;
812 	struct cpu_info *ci;
813 	struct lwp *l;
814 	struct proc *p;
815 
816 	/*
817 	 * We do this by process in order not to violate the locking rules.
818 	 */
819 	mutex_enter(proc_lock);
820 	PROCLIST_FOREACH(p, &allproc) {
821 		mutex_enter(p->p_lock);
822 
823 		if ((p->p_flag & PK_SYSTEM) != 0) {
824 			mutex_exit(p->p_lock);
825 			continue;
826 		}
827 
828 		p->p_stat = SSTOP;
829 
830 		LIST_FOREACH(l, &p->p_lwps, l_sibling) {
831 			if (l == curlwp)
832 				continue;
833 
834 			lwp_lock(l);
835 
836 			/*
837 			 * Set L_WREBOOT so that the LWP will suspend itself
838 			 * when it tries to return to user mode.  We want to
839 			 * try and get to get as many LWPs as possible to
840 			 * the user / kernel boundary, so that they will
841 			 * release any locks that they hold.
842 			 */
843 			l->l_flag |= (LW_WREBOOT | LW_WSUSPEND);
844 
845 			if (l->l_stat == LSSLEEP &&
846 			    (l->l_flag & LW_SINTR) != 0) {
847 				/* setrunnable() will release the lock. */
848 				setrunnable(l);
849 				continue;
850 			}
851 
852 			lwp_unlock(l);
853 		}
854 
855 		mutex_exit(p->p_lock);
856 	}
857 	mutex_exit(proc_lock);
858 
859 	/*
860 	 * Kick all CPUs to make them preempt any LWPs running in user mode.
861 	 * They'll trap into the kernel and suspend themselves in userret().
862 	 */
863 	for (CPU_INFO_FOREACH(cii, ci)) {
864 		spc_lock(ci);
865 		cpu_need_resched(ci, RESCHED_IMMED);
866 		spc_unlock(ci);
867 	}
868 }
869 
870 /*
871  * sched_unsleep:
872  *
873  *	The is called when the LWP has not been awoken normally but instead
874  *	interrupted: for example, if the sleep timed out.  Because of this,
875  *	it's not a valid action for running or idle LWPs.
876  */
877 static u_int
878 sched_unsleep(struct lwp *l, bool cleanup)
879 {
880 
881 	lwp_unlock(l);
882 	panic("sched_unsleep");
883 }
884 
885 void
886 resched_cpu(struct lwp *l)
887 {
888 	struct cpu_info *ci;
889 
890 	/*
891 	 * XXXSMP
892 	 * Since l->l_cpu persists across a context switch,
893 	 * this gives us *very weak* processor affinity, in
894 	 * that we notify the CPU on which the process last
895 	 * ran that it should try to switch.
896 	 *
897 	 * This does not guarantee that the process will run on
898 	 * that processor next, because another processor might
899 	 * grab it the next time it performs a context switch.
900 	 *
901 	 * This also does not handle the case where its last
902 	 * CPU is running a higher-priority process, but every
903 	 * other CPU is running a lower-priority process.  There
904 	 * are ways to handle this situation, but they're not
905 	 * currently very pretty, and we also need to weigh the
906 	 * cost of moving a process from one CPU to another.
907 	 */
908 	ci = l->l_cpu;
909 	if (lwp_eprio(l) > ci->ci_schedstate.spc_curpriority)
910 		cpu_need_resched(ci, 0);
911 }
912 
913 static void
914 sched_changepri(struct lwp *l, pri_t pri)
915 {
916 
917 	KASSERT(lwp_locked(l, NULL));
918 
919 	if (l->l_stat == LSRUN && (l->l_flag & LW_INMEM) != 0) {
920 		KASSERT(lwp_locked(l, l->l_cpu->ci_schedstate.spc_mutex));
921 		sched_dequeue(l);
922 		l->l_priority = pri;
923 		sched_enqueue(l, false);
924 	} else {
925 		l->l_priority = pri;
926 	}
927 	resched_cpu(l);
928 }
929 
930 static void
931 sched_lendpri(struct lwp *l, pri_t pri)
932 {
933 
934 	KASSERT(lwp_locked(l, NULL));
935 
936 	if (l->l_stat == LSRUN && (l->l_flag & LW_INMEM) != 0) {
937 		KASSERT(lwp_locked(l, l->l_cpu->ci_schedstate.spc_mutex));
938 		sched_dequeue(l);
939 		l->l_inheritedprio = pri;
940 		sched_enqueue(l, false);
941 	} else {
942 		l->l_inheritedprio = pri;
943 	}
944 	resched_cpu(l);
945 }
946 
947 struct lwp *
948 syncobj_noowner(wchan_t wchan)
949 {
950 
951 	return NULL;
952 }
953 
954 /* decay 95% of `p_pctcpu' in 60 seconds; see CCPU_SHIFT before changing */
955 fixpt_t	ccpu = 0.95122942450071400909 * FSCALE;		/* exp(-1/20) */
956 
957 /*
958  * If `ccpu' is not equal to `exp(-1/20)' and you still want to use the
959  * faster/more-accurate formula, you'll have to estimate CCPU_SHIFT below
960  * and possibly adjust FSHIFT in "param.h" so that (FSHIFT >= CCPU_SHIFT).
961  *
962  * To estimate CCPU_SHIFT for exp(-1/20), the following formula was used:
963  *	1 - exp(-1/20) ~= 0.0487 ~= 0.0488 == 1 (fixed pt, *11* bits).
964  *
965  * If you dont want to bother with the faster/more-accurate formula, you
966  * can set CCPU_SHIFT to (FSHIFT + 1) which will use a slower/less-accurate
967  * (more general) method of calculating the %age of CPU used by a process.
968  */
969 #define	CCPU_SHIFT	(FSHIFT + 1)
970 
971 /*
972  * sched_pstats:
973  *
974  * Update process statistics and check CPU resource allocation.
975  * Call scheduler-specific hook to eventually adjust process/LWP
976  * priorities.
977  */
978 /* ARGSUSED */
979 void
980 sched_pstats(void *arg)
981 {
982 	struct rlimit *rlim;
983 	struct lwp *l;
984 	struct proc *p;
985 	int sig, clkhz;
986 	long runtm;
987 
988 	sched_pstats_ticks++;
989 
990 	mutex_enter(proc_lock);
991 	PROCLIST_FOREACH(p, &allproc) {
992 		/*
993 		 * Increment time in/out of memory and sleep time (if
994 		 * sleeping).  We ignore overflow; with 16-bit int's
995 		 * (remember them?) overflow takes 45 days.
996 		 */
997 		mutex_enter(p->p_lock);
998 		mutex_spin_enter(&p->p_stmutex);
999 		runtm = p->p_rtime.sec;
1000 		LIST_FOREACH(l, &p->p_lwps, l_sibling) {
1001 			if ((l->l_flag & LW_IDLE) != 0)
1002 				continue;
1003 			lwp_lock(l);
1004 			runtm += l->l_rtime.sec;
1005 			l->l_swtime++;
1006 			sched_pstats_hook(l);
1007 			lwp_unlock(l);
1008 
1009 			/*
1010 			 * p_pctcpu is only for ps.
1011 			 */
1012 			l->l_pctcpu = (l->l_pctcpu * ccpu) >> FSHIFT;
1013 			if (l->l_slptime < 1) {
1014 				clkhz = stathz != 0 ? stathz : hz;
1015 #if	(FSHIFT >= CCPU_SHIFT)
1016 				l->l_pctcpu += (clkhz == 100) ?
1017 				    ((fixpt_t)l->l_cpticks) <<
1018 				        (FSHIFT - CCPU_SHIFT) :
1019 				    100 * (((fixpt_t) p->p_cpticks)
1020 				        << (FSHIFT - CCPU_SHIFT)) / clkhz;
1021 #else
1022 				l->l_pctcpu += ((FSCALE - ccpu) *
1023 				    (l->l_cpticks * FSCALE / clkhz)) >> FSHIFT;
1024 #endif
1025 				l->l_cpticks = 0;
1026 			}
1027 		}
1028 		p->p_pctcpu = (p->p_pctcpu * ccpu) >> FSHIFT;
1029 		mutex_spin_exit(&p->p_stmutex);
1030 
1031 		/*
1032 		 * Check if the process exceeds its CPU resource allocation.
1033 		 * If over max, kill it.
1034 		 */
1035 		rlim = &p->p_rlimit[RLIMIT_CPU];
1036 		sig = 0;
1037 		if (runtm >= rlim->rlim_cur) {
1038 			if (runtm >= rlim->rlim_max)
1039 				sig = SIGKILL;
1040 			else {
1041 				sig = SIGXCPU;
1042 				if (rlim->rlim_cur < rlim->rlim_max)
1043 					rlim->rlim_cur += 5;
1044 			}
1045 		}
1046 		mutex_exit(p->p_lock);
1047 		if (sig)
1048 			psignal(p, sig);
1049 	}
1050 	mutex_exit(proc_lock);
1051 	uvm_meter();
1052 	cv_wakeup(&lbolt);
1053 	callout_schedule(&sched_pstats_ch, hz);
1054 }
1055 
1056 void
1057 sched_init(void)
1058 {
1059 
1060 	cv_init(&lbolt, "lbolt");
1061 	callout_init(&sched_pstats_ch, CALLOUT_MPSAFE);
1062 	callout_setfunc(&sched_pstats_ch, sched_pstats, NULL);
1063 
1064 	/* Balancing */
1065 	worker_ci = curcpu();
1066 	cacheht_time = mstohz(5);		/* ~5 ms  */
1067 	balance_period = mstohz(300);		/* ~300ms */
1068 
1069 	/* Minimal count of LWPs for catching: log2(count of CPUs) */
1070 	min_catch = min(ilog2(ncpu), 4);
1071 
1072 	/* Initialize balancing callout and run it */
1073 #ifdef MULTIPROCESSOR
1074 	callout_init(&balance_ch, CALLOUT_MPSAFE);
1075 	callout_setfunc(&balance_ch, sched_balance, NULL);
1076 	callout_schedule(&balance_ch, balance_period);
1077 #endif
1078 	sched_pstats(NULL);
1079 }
1080 
1081 SYSCTL_SETUP(sysctl_sched_setup, "sysctl sched setup")
1082 {
1083 	const struct sysctlnode *node = NULL;
1084 
1085 	sysctl_createv(clog, 0, NULL, NULL,
1086 		CTLFLAG_PERMANENT,
1087 		CTLTYPE_NODE, "kern", NULL,
1088 		NULL, 0, NULL, 0,
1089 		CTL_KERN, CTL_EOL);
1090 	sysctl_createv(clog, 0, NULL, &node,
1091 		CTLFLAG_PERMANENT,
1092 		CTLTYPE_NODE, "sched",
1093 		SYSCTL_DESCR("Scheduler options"),
1094 		NULL, 0, NULL, 0,
1095 		CTL_KERN, CTL_CREATE, CTL_EOL);
1096 
1097 	if (node == NULL)
1098 		return;
1099 
1100 	sysctl_createv(clog, 0, &node, NULL,
1101 		CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
1102 		CTLTYPE_INT, "cacheht_time",
1103 		SYSCTL_DESCR("Cache hotness time (in ticks)"),
1104 		NULL, 0, &cacheht_time, 0,
1105 		CTL_CREATE, CTL_EOL);
1106 	sysctl_createv(clog, 0, &node, NULL,
1107 		CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
1108 		CTLTYPE_INT, "balance_period",
1109 		SYSCTL_DESCR("Balance period (in ticks)"),
1110 		NULL, 0, &balance_period, 0,
1111 		CTL_CREATE, CTL_EOL);
1112 	sysctl_createv(clog, 0, &node, NULL,
1113 		CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
1114 		CTLTYPE_INT, "min_catch",
1115 		SYSCTL_DESCR("Minimal count of threads for catching"),
1116 		NULL, 0, &min_catch, 0,
1117 		CTL_CREATE, CTL_EOL);
1118 	sysctl_createv(clog, 0, &node, NULL,
1119 		CTLFLAG_READWRITE,
1120 		CTLTYPE_INT, "timesoftints",
1121 		SYSCTL_DESCR("Track CPU time for soft interrupts"),
1122 		NULL, 0, &softint_timing, 0,
1123 		CTL_CREATE, CTL_EOL);
1124 }
1125 
1126 void
1127 sched_cpuattach(struct cpu_info *ci)
1128 {
1129 	runqueue_t *ci_rq;
1130 	void *rq_ptr;
1131 	u_int i, size;
1132 
1133 	if (ci->ci_schedstate.spc_lwplock == NULL) {
1134 		ci->ci_schedstate.spc_lwplock =
1135 		    mutex_obj_alloc(MUTEX_DEFAULT, IPL_SCHED);
1136 	}
1137 	if (ci == lwp0.l_cpu) {
1138 		/* Initialize the scheduler structure of the primary LWP */
1139 		lwp0.l_mutex = ci->ci_schedstate.spc_lwplock;
1140 	}
1141 	if (ci->ci_schedstate.spc_mutex != NULL) {
1142 		/* Already initialized. */
1143 		return;
1144 	}
1145 
1146 	/* Allocate the run queue */
1147 	size = roundup2(sizeof(runqueue_t), coherency_unit) + coherency_unit;
1148 	rq_ptr = kmem_zalloc(size, KM_SLEEP);
1149 	if (rq_ptr == NULL) {
1150 		panic("sched_cpuattach: could not allocate the runqueue");
1151 	}
1152 	ci_rq = (void *)(roundup2((uintptr_t)(rq_ptr), coherency_unit));
1153 
1154 	/* Initialize run queues */
1155 	ci->ci_schedstate.spc_mutex =
1156 	    mutex_obj_alloc(MUTEX_DEFAULT, IPL_SCHED);
1157 	for (i = 0; i < PRI_RT_COUNT; i++)
1158 		TAILQ_INIT(&ci_rq->r_rt_queue[i].q_head);
1159 	for (i = 0; i < PRI_TS_COUNT; i++)
1160 		TAILQ_INIT(&ci_rq->r_ts_queue[i].q_head);
1161 
1162 	ci->ci_schedstate.spc_sched_info = ci_rq;
1163 }
1164 
1165 /*
1166  * Control of the runqueue.
1167  */
1168 
1169 static void *
1170 sched_getrq(runqueue_t *ci_rq, const pri_t prio)
1171 {
1172 
1173 	KASSERT(prio < PRI_COUNT);
1174 	return (prio <= PRI_HIGHEST_TS) ?
1175 	    &ci_rq->r_ts_queue[prio].q_head :
1176 	    &ci_rq->r_rt_queue[prio - PRI_HIGHEST_TS - 1].q_head;
1177 }
1178 
1179 void
1180 sched_enqueue(struct lwp *l, bool swtch)
1181 {
1182 	runqueue_t *ci_rq;
1183 	struct schedstate_percpu *spc;
1184 	TAILQ_HEAD(, lwp) *q_head;
1185 	const pri_t eprio = lwp_eprio(l);
1186 	struct cpu_info *ci;
1187 
1188 	ci = l->l_cpu;
1189 	spc = &ci->ci_schedstate;
1190 	ci_rq = spc->spc_sched_info;
1191 	KASSERT(lwp_locked(l, l->l_cpu->ci_schedstate.spc_mutex));
1192 
1193 	/* Update the last run time on switch */
1194 	if (__predict_true(swtch == true)) {
1195 		l->l_rticks = hardclock_ticks;
1196 		l->l_rticksum += (hardclock_ticks - l->l_rticks);
1197 	} else if (l->l_rticks == 0)
1198 		l->l_rticks = hardclock_ticks;
1199 
1200 	/* Enqueue the thread */
1201 	q_head = sched_getrq(ci_rq, eprio);
1202 	if (TAILQ_EMPTY(q_head)) {
1203 		u_int i;
1204 		uint32_t q;
1205 
1206 		/* Mark bit */
1207 		i = eprio >> BITMAP_SHIFT;
1208 		q = BITMAP_MSB >> (eprio & BITMAP_MASK);
1209 		KASSERT((ci_rq->r_bitmap[i] & q) == 0);
1210 		ci_rq->r_bitmap[i] |= q;
1211 	}
1212 	TAILQ_INSERT_TAIL(q_head, l, l_runq);
1213 	ci_rq->r_count++;
1214 	if ((l->l_pflag & LP_BOUND) == 0)
1215 		ci_rq->r_mcount++;
1216 
1217 	/*
1218 	 * Update the value of highest priority in the runqueue,
1219 	 * if priority of this thread is higher.
1220 	 */
1221 	if (eprio > spc->spc_maxpriority)
1222 		spc->spc_maxpriority = eprio;
1223 
1224 	sched_newts(l);
1225 
1226 	/*
1227 	 * Wake the chosen CPU or cause a preemption if the newly
1228 	 * enqueued thread has higher priority.  Don't cause a
1229 	 * preemption if the thread is yielding (swtch).
1230 	 */
1231 	if (!swtch && eprio > spc->spc_curpriority) {
1232 		cpu_need_resched(ci,
1233 		    (eprio >= PRI_KERNEL ? RESCHED_IMMED : 0));
1234 	}
1235 }
1236 
1237 void
1238 sched_dequeue(struct lwp *l)
1239 {
1240 	runqueue_t *ci_rq;
1241 	TAILQ_HEAD(, lwp) *q_head;
1242 	struct schedstate_percpu *spc;
1243 	const pri_t eprio = lwp_eprio(l);
1244 
1245 	spc = & l->l_cpu->ci_schedstate;
1246 	ci_rq = spc->spc_sched_info;
1247 	KASSERT(lwp_locked(l, spc->spc_mutex));
1248 
1249 	KASSERT(eprio <= spc->spc_maxpriority);
1250 	KASSERT(ci_rq->r_bitmap[eprio >> BITMAP_SHIFT] != 0);
1251 	KASSERT(ci_rq->r_count > 0);
1252 
1253 	ci_rq->r_count--;
1254 	if ((l->l_pflag & LP_BOUND) == 0)
1255 		ci_rq->r_mcount--;
1256 
1257 	q_head = sched_getrq(ci_rq, eprio);
1258 	TAILQ_REMOVE(q_head, l, l_runq);
1259 	if (TAILQ_EMPTY(q_head)) {
1260 		u_int i;
1261 		uint32_t q;
1262 
1263 		/* Unmark bit */
1264 		i = eprio >> BITMAP_SHIFT;
1265 		q = BITMAP_MSB >> (eprio & BITMAP_MASK);
1266 		KASSERT((ci_rq->r_bitmap[i] & q) != 0);
1267 		ci_rq->r_bitmap[i] &= ~q;
1268 
1269 		/*
1270 		 * Update the value of highest priority in the runqueue, in a
1271 		 * case it was a last thread in the queue of highest priority.
1272 		 */
1273 		if (eprio != spc->spc_maxpriority)
1274 			return;
1275 
1276 		do {
1277 			if (ci_rq->r_bitmap[i] != 0) {
1278 				q = ffs(ci_rq->r_bitmap[i]);
1279 				spc->spc_maxpriority =
1280 				    (i << BITMAP_SHIFT) + (BITMAP_BITS - q);
1281 				return;
1282 			}
1283 		} while (i--);
1284 
1285 		/* If not found - set the lowest value */
1286 		spc->spc_maxpriority = 0;
1287 	}
1288 }
1289 
1290 /*
1291  * Migration and balancing.
1292  */
1293 
1294 #ifdef MULTIPROCESSOR
1295 
1296 /* Estimate if LWP is cache-hot */
1297 static inline bool
1298 lwp_cache_hot(const struct lwp *l)
1299 {
1300 
1301 	if (l->l_slptime || l->l_rticks == 0)
1302 		return false;
1303 
1304 	return (hardclock_ticks - l->l_rticks <= cacheht_time);
1305 }
1306 
1307 /* Check if LWP can migrate to the chosen CPU */
1308 static inline bool
1309 sched_migratable(const struct lwp *l, struct cpu_info *ci)
1310 {
1311 	const struct schedstate_percpu *spc = &ci->ci_schedstate;
1312 
1313 	/* CPU is offline */
1314 	if (__predict_false(spc->spc_flags & SPCF_OFFLINE))
1315 		return false;
1316 
1317 	/* Affinity bind */
1318 	if (__predict_false(l->l_flag & LW_AFFINITY))
1319 		return CPU_ISSET(cpu_index(ci), &l->l_affinity);
1320 
1321 	/* Processor-set */
1322 	return (spc->spc_psid == l->l_psid);
1323 }
1324 
1325 /*
1326  * Estimate the migration of LWP to the other CPU.
1327  * Take and return the CPU, if migration is needed.
1328  */
1329 struct cpu_info *
1330 sched_takecpu(struct lwp *l)
1331 {
1332 	struct cpu_info *ci, *tci, *first, *next;
1333 	struct schedstate_percpu *spc;
1334 	runqueue_t *ci_rq, *ici_rq;
1335 	pri_t eprio, lpri, pri;
1336 
1337 	KASSERT(lwp_locked(l, NULL));
1338 
1339 	ci = l->l_cpu;
1340 	spc = &ci->ci_schedstate;
1341 	ci_rq = spc->spc_sched_info;
1342 
1343 	/* If thread is strictly bound, do not estimate other CPUs */
1344 	if (l->l_pflag & LP_BOUND)
1345 		return ci;
1346 
1347 	/* CPU of this thread is idling - run there */
1348 	if (ci_rq->r_count == 0)
1349 		return ci;
1350 
1351 	eprio = lwp_eprio(l);
1352 
1353 	/* Stay if thread is cache-hot */
1354 	if (__predict_true(l->l_stat != LSIDL) &&
1355 	    lwp_cache_hot(l) && eprio >= spc->spc_curpriority)
1356 		return ci;
1357 
1358 	/* Run on current CPU if priority of thread is higher */
1359 	ci = curcpu();
1360 	spc = &ci->ci_schedstate;
1361 	if (eprio > spc->spc_curpriority && sched_migratable(l, ci))
1362 		return ci;
1363 
1364 	/*
1365 	 * Look for the CPU with the lowest priority thread.  In case of
1366 	 * equal priority, choose the CPU with the fewest of threads.
1367 	 */
1368 	first = l->l_cpu;
1369 	ci = first;
1370 	tci = first;
1371 	lpri = PRI_COUNT;
1372 	do {
1373 		next = CIRCLEQ_LOOP_NEXT(&cpu_queue, ci, ci_data.cpu_qchain);
1374 		spc = &ci->ci_schedstate;
1375 		ici_rq = spc->spc_sched_info;
1376 		pri = max(spc->spc_curpriority, spc->spc_maxpriority);
1377 		if (pri > lpri)
1378 			continue;
1379 
1380 		if (pri == lpri && ci_rq->r_count < ici_rq->r_count)
1381 			continue;
1382 
1383 		if (!sched_migratable(l, ci))
1384 			continue;
1385 
1386 		lpri = pri;
1387 		tci = ci;
1388 		ci_rq = ici_rq;
1389 	} while (ci = next, ci != first);
1390 
1391 	return tci;
1392 }
1393 
1394 /*
1395  * Tries to catch an LWP from the runqueue of other CPU.
1396  */
1397 static struct lwp *
1398 sched_catchlwp(void)
1399 {
1400 	struct cpu_info *curci = curcpu(), *ci = worker_ci;
1401 	struct schedstate_percpu *spc;
1402 	TAILQ_HEAD(, lwp) *q_head;
1403 	runqueue_t *ci_rq;
1404 	struct lwp *l;
1405 
1406 	if (curci == ci)
1407 		return NULL;
1408 
1409 	/* Lockless check */
1410 	spc = &ci->ci_schedstate;
1411 	ci_rq = spc->spc_sched_info;
1412 	if (ci_rq->r_mcount < min_catch)
1413 		return NULL;
1414 
1415 	/*
1416 	 * Double-lock the runqueues.
1417 	 */
1418 	if (curci < ci) {
1419 		spc_lock(ci);
1420 	} else if (!mutex_tryenter(ci->ci_schedstate.spc_mutex)) {
1421 		const runqueue_t *cur_rq = curci->ci_schedstate.spc_sched_info;
1422 
1423 		spc_unlock(curci);
1424 		spc_lock(ci);
1425 		spc_lock(curci);
1426 
1427 		if (cur_rq->r_count) {
1428 			spc_unlock(ci);
1429 			return NULL;
1430 		}
1431 	}
1432 
1433 	if (ci_rq->r_mcount < min_catch) {
1434 		spc_unlock(ci);
1435 		return NULL;
1436 	}
1437 
1438 	/* Take the highest priority thread */
1439 	q_head = sched_getrq(ci_rq, spc->spc_maxpriority);
1440 	l = TAILQ_FIRST(q_head);
1441 
1442 	for (;;) {
1443 		/* Check the first and next result from the queue */
1444 		if (l == NULL)
1445 			break;
1446 		KASSERT(l->l_stat == LSRUN);
1447 		KASSERT(l->l_flag & LW_INMEM);
1448 
1449 		/* Look for threads, whose are allowed to migrate */
1450 		if ((l->l_pflag & LP_BOUND) || lwp_cache_hot(l) ||
1451 		    !sched_migratable(l, curci)) {
1452 			l = TAILQ_NEXT(l, l_runq);
1453 			continue;
1454 		}
1455 
1456 		/* Grab the thread, and move to the local run queue */
1457 		sched_dequeue(l);
1458 		l->l_cpu = curci;
1459 		lwp_unlock_to(l, curci->ci_schedstate.spc_mutex);
1460 		sched_enqueue(l, false);
1461 		return l;
1462 	}
1463 	spc_unlock(ci);
1464 
1465 	return l;
1466 }
1467 
1468 /*
1469  * Periodical calculations for balancing.
1470  */
1471 static void
1472 sched_balance(void *nocallout)
1473 {
1474 	struct cpu_info *ci, *hci;
1475 	runqueue_t *ci_rq;
1476 	CPU_INFO_ITERATOR cii;
1477 	u_int highest;
1478 
1479 	hci = curcpu();
1480 	highest = 0;
1481 
1482 	/* Make lockless countings */
1483 	for (CPU_INFO_FOREACH(cii, ci)) {
1484 		ci_rq = ci->ci_schedstate.spc_sched_info;
1485 
1486 		/* Average count of the threads */
1487 		ci_rq->r_avgcount = (ci_rq->r_avgcount + ci_rq->r_mcount) >> 1;
1488 
1489 		/* Look for CPU with the highest average */
1490 		if (ci_rq->r_avgcount > highest) {
1491 			hci = ci;
1492 			highest = ci_rq->r_avgcount;
1493 		}
1494 	}
1495 
1496 	/* Update the worker */
1497 	worker_ci = hci;
1498 
1499 	if (nocallout == NULL)
1500 		callout_schedule(&balance_ch, balance_period);
1501 }
1502 
1503 #else
1504 
1505 struct cpu_info *
1506 sched_takecpu(struct lwp *l)
1507 {
1508 
1509 	return l->l_cpu;
1510 }
1511 
1512 #endif	/* MULTIPROCESSOR */
1513 
1514 /*
1515  * Scheduler mill.
1516  */
1517 struct lwp *
1518 sched_nextlwp(void)
1519 {
1520 	struct cpu_info *ci = curcpu();
1521 	struct schedstate_percpu *spc;
1522 	TAILQ_HEAD(, lwp) *q_head;
1523 	runqueue_t *ci_rq;
1524 	struct lwp *l;
1525 
1526 	spc = &ci->ci_schedstate;
1527 	ci_rq = spc->spc_sched_info;
1528 
1529 #ifdef MULTIPROCESSOR
1530 	/* If runqueue is empty, try to catch some thread from other CPU */
1531 	if (__predict_false(spc->spc_flags & SPCF_OFFLINE)) {
1532 		if ((ci_rq->r_count - ci_rq->r_mcount) == 0)
1533 			return NULL;
1534 	} else if (ci_rq->r_count == 0) {
1535 		/* Reset the counter, and call the balancer */
1536 		ci_rq->r_avgcount = 0;
1537 		sched_balance(ci);
1538 
1539 		/* The re-locking will be done inside */
1540 		return sched_catchlwp();
1541 	}
1542 #else
1543 	if (ci_rq->r_count == 0)
1544 		return NULL;
1545 #endif
1546 
1547 	/* Take the highest priority thread */
1548 	KASSERT(ci_rq->r_bitmap[spc->spc_maxpriority >> BITMAP_SHIFT]);
1549 	q_head = sched_getrq(ci_rq, spc->spc_maxpriority);
1550 	l = TAILQ_FIRST(q_head);
1551 	KASSERT(l != NULL);
1552 
1553 	sched_oncpu(l);
1554 	l->l_rticks = hardclock_ticks;
1555 
1556 	return l;
1557 }
1558 
1559 bool
1560 sched_curcpu_runnable_p(void)
1561 {
1562 	const struct cpu_info *ci = curcpu();
1563 	const runqueue_t *ci_rq = ci->ci_schedstate.spc_sched_info;
1564 
1565 #ifndef __HAVE_FAST_SOFTINTS
1566 	if (ci->ci_data.cpu_softints)
1567 		return true;
1568 #endif
1569 
1570 	if (ci->ci_schedstate.spc_flags & SPCF_OFFLINE)
1571 		return (ci_rq->r_count - ci_rq->r_mcount);
1572 
1573 	return ci_rq->r_count;
1574 }
1575 
1576 /*
1577  * Debugging.
1578  */
1579 
1580 #ifdef DDB
1581 
1582 void
1583 sched_print_runqueue(void (*pr)(const char *, ...)
1584     __attribute__((__format__(__printf__,1,2))))
1585 {
1586 	runqueue_t *ci_rq;
1587 	struct schedstate_percpu *spc;
1588 	struct lwp *l;
1589 	struct proc *p;
1590 	int i;
1591 	struct cpu_info *ci;
1592 	CPU_INFO_ITERATOR cii;
1593 
1594 	for (CPU_INFO_FOREACH(cii, ci)) {
1595 		spc = &ci->ci_schedstate;
1596 		ci_rq = spc->spc_sched_info;
1597 
1598 		(*pr)("Run-queue (CPU = %u):\n", ci->ci_index);
1599 		(*pr)(" pid.lid = %d.%d, threads count = %u, "
1600 		    "avgcount = %u, highest pri = %d\n",
1601 #ifdef MULTIPROCESSOR
1602 		    ci->ci_curlwp->l_proc->p_pid, ci->ci_curlwp->l_lid,
1603 #else
1604 		    curlwp->l_proc->p_pid, curlwp->l_lid,
1605 #endif
1606 		    ci_rq->r_count, ci_rq->r_avgcount, spc->spc_maxpriority);
1607 		i = (PRI_COUNT >> BITMAP_SHIFT) - 1;
1608 		do {
1609 			uint32_t q;
1610 			q = ci_rq->r_bitmap[i];
1611 			(*pr)(" bitmap[%d] => [ %d (0x%x) ]\n", i, ffs(q), q);
1612 		} while (i--);
1613 	}
1614 
1615 	(*pr)("   %5s %4s %4s %10s %3s %18s %4s %s\n",
1616 	    "LID", "PRI", "EPRI", "FL", "ST", "LWP", "CPU", "LRTIME");
1617 
1618 	PROCLIST_FOREACH(p, &allproc) {
1619 		(*pr)(" /- %d (%s)\n", (int)p->p_pid, p->p_comm);
1620 		LIST_FOREACH(l, &p->p_lwps, l_sibling) {
1621 			ci = l->l_cpu;
1622 			(*pr)(" | %5d %4u %4u 0x%8.8x %3s %18p %4u %u\n",
1623 			    (int)l->l_lid, l->l_priority, lwp_eprio(l),
1624 			    l->l_flag, l->l_stat == LSRUN ? "RQ" :
1625 			    (l->l_stat == LSSLEEP ? "SQ" : "-"),
1626 			    l, ci->ci_index,
1627 			    (u_int)(hardclock_ticks - l->l_rticks));
1628 		}
1629 	}
1630 }
1631 
1632 #endif
1633