Home | History | Annotate | Line # | Download | only in kern
kern_synch.c revision 1.177.2.29
      1 /*	$NetBSD: kern_synch.c,v 1.177.2.29 2007/05/13 17:02:58 ad Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1999, 2000, 2004, 2006, 2007 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) 1982, 1986, 1990, 1991, 1993
     43  *	The Regents of the University of California.  All rights reserved.
     44  * (c) UNIX System Laboratories, Inc.
     45  * All or some portions of this file are derived from material licensed
     46  * to the University of California by American Telephone and Telegraph
     47  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
     48  * the permission of UNIX System Laboratories, Inc.
     49  *
     50  * Redistribution and use in source and binary forms, with or without
     51  * modification, are permitted provided that the following conditions
     52  * are met:
     53  * 1. Redistributions of source code must retain the above copyright
     54  *    notice, this list of conditions and the following disclaimer.
     55  * 2. Redistributions in binary form must reproduce the above copyright
     56  *    notice, this list of conditions and the following disclaimer in the
     57  *    documentation and/or other materials provided with the distribution.
     58  * 3. Neither the name of the University nor the names of its contributors
     59  *    may be used to endorse or promote products derived from this software
     60  *    without specific prior written permission.
     61  *
     62  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     63  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     64  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     65  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     66  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     67  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     68  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     69  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     70  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     71  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     72  * SUCH DAMAGE.
     73  *
     74  *	@(#)kern_synch.c	8.9 (Berkeley) 5/19/95
     75  */
     76 
     77 #include <sys/cdefs.h>
     78 __KERNEL_RCSID(0, "$NetBSD: kern_synch.c,v 1.177.2.29 2007/05/13 17:02:58 ad Exp $");
     79 
     80 #include "opt_kstack.h"
     81 #include "opt_lockdebug.h"
     82 #include "opt_multiprocessor.h"
     83 #include "opt_perfctrs.h"
     84 
     85 #define	__MUTEX_PRIVATE
     86 
     87 #include <sys/param.h>
     88 #include <sys/systm.h>
     89 #include <sys/proc.h>
     90 #include <sys/kernel.h>
     91 #if defined(PERFCTRS)
     92 #include <sys/pmc.h>
     93 #endif
     94 #include <sys/cpu.h>
     95 #include <sys/resourcevar.h>
     96 #include <sys/sched.h>
     97 #include <sys/syscall_stats.h>
     98 #include <sys/sleepq.h>
     99 #include <sys/lockdebug.h>
    100 
    101 #include <uvm/uvm_extern.h>
    102 
    103 struct callout sched_pstats_ch = CALLOUT_INITIALIZER_SETFUNC(sched_pstats, NULL);
    104 unsigned int sched_pstats_ticks;
    105 
    106 int	lbolt;			/* once a second sleep address */
    107 
    108 static void	sched_unsleep(struct lwp *);
    109 static void	sched_changepri(struct lwp *, pri_t);
    110 static void	sched_lendpri(struct lwp *, pri_t);
    111 
    112 syncobj_t sleep_syncobj = {
    113 	SOBJ_SLEEPQ_SORTED,
    114 	sleepq_unsleep,
    115 	sleepq_changepri,
    116 	sleepq_lendpri,
    117 	syncobj_noowner,
    118 };
    119 
    120 syncobj_t sched_syncobj = {
    121 	SOBJ_SLEEPQ_SORTED,
    122 	sched_unsleep,
    123 	sched_changepri,
    124 	sched_lendpri,
    125 	syncobj_noowner,
    126 };
    127 
    128 /*
    129  * During autoconfiguration or after a panic, a sleep will simply lower the
    130  * priority briefly to allow interrupts, then return.  The priority to be
    131  * used (safepri) is machine-dependent, thus this value is initialized and
    132  * maintained in the machine-dependent layers.  This priority will typically
    133  * be 0, or the lowest priority that is safe for use on the interrupt stack;
    134  * it can be made higher to block network software interrupts after panics.
    135  */
    136 int	safepri;
    137 
    138 /*
    139  * OBSOLETE INTERFACE
    140  *
    141  * General sleep call.  Suspends the current process until a wakeup is
    142  * performed on the specified identifier.  The process will then be made
    143  * runnable with the specified priority.  Sleeps at most timo/hz seconds (0
    144  * means no timeout).  If pri includes PCATCH flag, signals are checked
    145  * before and after sleeping, else signals are not checked.  Returns 0 if
    146  * awakened, EWOULDBLOCK if the timeout expires.  If PCATCH is set and a
    147  * signal needs to be delivered, ERESTART is returned if the current system
    148  * call should be restarted if possible, and EINTR is returned if the system
    149  * call should be interrupted by the signal (return EINTR).
    150  *
    151  * The interlock is held until we are on a sleep queue. The interlock will
    152  * be locked before returning back to the caller unless the PNORELOCK flag
    153  * is specified, in which case the interlock will always be unlocked upon
    154  * return.
    155  */
    156 int
    157 ltsleep(wchan_t ident, pri_t priority, const char *wmesg, int timo,
    158 	volatile struct simplelock *interlock)
    159 {
    160 	struct lwp *l = curlwp;
    161 	sleepq_t *sq;
    162 	int error;
    163 
    164 	if (sleepq_dontsleep(l)) {
    165 		(void)sleepq_abort(NULL, 0);
    166 		if ((priority & PNORELOCK) != 0)
    167 			simple_unlock(interlock);
    168 		return 0;
    169 	}
    170 
    171 	sq = sleeptab_lookup(&sleeptab, ident);
    172 	sleepq_enter(sq, l);
    173 	sleepq_enqueue(sq, priority & PRIMASK, ident, wmesg, &sleep_syncobj);
    174 
    175 	if (interlock != NULL) {
    176 		LOCK_ASSERT(simple_lock_held(interlock));
    177 		simple_unlock(interlock);
    178 	}
    179 
    180 	error = sleepq_block(timo, priority & PCATCH);
    181 
    182 	if (interlock != NULL && (priority & PNORELOCK) == 0)
    183 		simple_lock(interlock);
    184 
    185 	return error;
    186 }
    187 
    188 int
    189 mtsleep(wchan_t ident, pri_t priority, const char *wmesg, int timo,
    190 	kmutex_t *mtx)
    191 {
    192 	struct lwp *l = curlwp;
    193 	sleepq_t *sq;
    194 	int error;
    195 
    196 	if (sleepq_dontsleep(l)) {
    197 		(void)sleepq_abort(mtx, (priority & PNORELOCK) != 0);
    198 		return 0;
    199 	}
    200 
    201 	sq = sleeptab_lookup(&sleeptab, ident);
    202 	sleepq_enter(sq, l);
    203 	sleepq_enqueue(sq, priority & PRIMASK, ident, wmesg, &sleep_syncobj);
    204 	mutex_exit(mtx);
    205 	error = sleepq_block(timo, priority & PCATCH);
    206 
    207 	if ((priority & PNORELOCK) == 0)
    208 		mutex_enter(mtx);
    209 
    210 	return error;
    211 }
    212 
    213 /*
    214  * General sleep call for situations where a wake-up is not expected.
    215  */
    216 int
    217 kpause(const char *wmesg, bool intr, int timo, kmutex_t *mtx)
    218 {
    219 	struct lwp *l = curlwp;
    220 	sleepq_t *sq;
    221 	int error;
    222 
    223 	if (sleepq_dontsleep(l))
    224 		return sleepq_abort(NULL, 0);
    225 
    226 	if (mtx != NULL)
    227 		mutex_exit(mtx);
    228 	sq = sleeptab_lookup(&sleeptab, l);
    229 	sleepq_enter(sq, l);
    230 	sleepq_enqueue(sq, sched_kpri(l), l, wmesg, &sleep_syncobj);
    231 	error = sleepq_block(timo, intr);
    232 	if (mtx != NULL)
    233 		mutex_enter(mtx);
    234 
    235 	return error;
    236 }
    237 
    238 /*
    239  * OBSOLETE INTERFACE
    240  *
    241  * Make all processes sleeping on the specified identifier runnable.
    242  */
    243 void
    244 wakeup(wchan_t ident)
    245 {
    246 	sleepq_t *sq;
    247 
    248 	if (cold)
    249 		return;
    250 
    251 	sq = sleeptab_lookup(&sleeptab, ident);
    252 	sleepq_wake(sq, ident, (u_int)-1);
    253 }
    254 
    255 /*
    256  * OBSOLETE INTERFACE
    257  *
    258  * Make the highest priority process first in line on the specified
    259  * identifier runnable.
    260  */
    261 void
    262 wakeup_one(wchan_t ident)
    263 {
    264 	sleepq_t *sq;
    265 
    266 	if (cold)
    267 		return;
    268 
    269 	sq = sleeptab_lookup(&sleeptab, ident);
    270 	sleepq_wake(sq, ident, 1);
    271 }
    272 
    273 
    274 /*
    275  * General yield call.  Puts the current process back on its run queue and
    276  * performs a voluntary context switch.  Should only be called when the
    277  * current process explicitly requests it (eg sched_yield(2) in compat code).
    278  */
    279 void
    280 yield(void)
    281 {
    282 	struct lwp *l = curlwp;
    283 
    284 	KERNEL_UNLOCK_ALL(l, &l->l_biglocks);
    285 	lwp_lock(l);
    286 	KASSERT(lwp_locked(l, &l->l_cpu->ci_schedstate.spc_lwplock));
    287 	KASSERT(l->l_stat == LSONPROC);
    288 	l->l_priority = l->l_usrpri;
    289 	(void)mi_switch(l);
    290 	KERNEL_LOCK(l->l_biglocks, l);
    291 }
    292 
    293 /*
    294  * General preemption call.  Puts the current process back on its run queue
    295  * and performs an involuntary context switch.
    296  */
    297 void
    298 preempt(void)
    299 {
    300 	struct lwp *l = curlwp;
    301 
    302 	KERNEL_UNLOCK_ALL(l, &l->l_biglocks);
    303 	lwp_lock(l);
    304 	KASSERT(lwp_locked(l, &l->l_cpu->ci_schedstate.spc_lwplock));
    305 	KASSERT(l->l_stat == LSONPROC);
    306 	l->l_priority = l->l_usrpri;
    307 	l->l_nivcsw++;
    308 	(void)mi_switch(l);
    309 	KERNEL_LOCK(l->l_biglocks, l);
    310 }
    311 
    312 /*
    313  * Compute the amount of time during which the current lwp was running.
    314  *
    315  * - update l_rtime unless it's an idle lwp.
    316  * - update spc_runtime for the next lwp.
    317  */
    318 
    319 static inline void
    320 updatertime(struct lwp *l, struct schedstate_percpu *spc)
    321 {
    322 	struct timeval tv;
    323 	long s, u;
    324 
    325 	if ((l->l_flag & LW_IDLE) != 0) {
    326 		microtime(&spc->spc_runtime);
    327 		return;
    328 	}
    329 
    330 	microtime(&tv);
    331 	u = l->l_rtime.tv_usec + (tv.tv_usec - spc->spc_runtime.tv_usec);
    332 	s = l->l_rtime.tv_sec + (tv.tv_sec - spc->spc_runtime.tv_sec);
    333 	if (u < 0) {
    334 		u += 1000000;
    335 		s--;
    336 	} else if (u >= 1000000) {
    337 		u -= 1000000;
    338 		s++;
    339 	}
    340 	l->l_rtime.tv_usec = u;
    341 	l->l_rtime.tv_sec = s;
    342 
    343 	spc->spc_runtime = tv;
    344 }
    345 
    346 /*
    347  * The machine independent parts of context switch.
    348  *
    349  * Returns 1 if another LWP was actually run.
    350  */
    351 int
    352 mi_switch(struct lwp *l)
    353 {
    354 	struct schedstate_percpu *spc;
    355 	struct lwp *newl;
    356 	int retval, oldspl;
    357 
    358 	KASSERT(lwp_locked(l, NULL));
    359 	LOCKDEBUG_BARRIER(l->l_mutex, 1);
    360 
    361 #ifdef LOCKDEBUG
    362 	spinlock_switchcheck();
    363 	simple_lock_switchcheck();
    364 #endif
    365 #ifdef KSTACK_CHECK_MAGIC
    366 	kstack_check_magic(l);
    367 #endif
    368 
    369 	/*
    370 	 * It's safe to read the per CPU schedstate unlocked here, as all we
    371 	 * are after is the run time and that's guarenteed to have been last
    372 	 * updated by this CPU.
    373 	 */
    374 	KDASSERT(l->l_cpu == curcpu());
    375 
    376 	/* Count time spent in current system call */
    377 	SYSCALL_TIME_SLEEP(l);
    378 
    379 	/*
    380 	 * XXXSMP If we are using h/w performance counters, save context.
    381 	 */
    382 #if PERFCTRS
    383 	if (PMC_ENABLED(l->l_proc)) {
    384 		pmc_save_context(l->l_proc);
    385 	}
    386 #endif
    387 	/*
    388 	 * Process is about to yield the CPU; clear the appropriate
    389 	 * scheduling flags.
    390 	 */
    391 	spc = &l->l_cpu->ci_schedstate;
    392 	spc->spc_flags &= ~SPCF_SWITCHCLEAR;
    393 	updatertime(l, spc);
    394 
    395 	/*
    396 	 * If on the CPU and we have gotten this far, then we must yield.
    397 	 */
    398 	mutex_spin_enter(spc->spc_mutex);
    399 	KASSERT(l->l_stat != LSRUN);
    400 	if (l->l_stat == LSONPROC) {
    401 		KASSERT(lwp_locked(l, &spc->spc_lwplock));
    402 		if ((l->l_flag & LW_IDLE) == 0) {
    403 			l->l_stat = LSRUN;
    404 			lwp_setlock(l, spc->spc_mutex);
    405 			sched_enqueue(l, true);
    406 		} else
    407 			l->l_stat = LSIDL;
    408 	}
    409 
    410 	/*
    411 	 * Let sched_nextlwp() select the LWP to run the CPU next.
    412 	 * If no LWP is runnable, switch to the idle LWP.
    413 	 */
    414 	newl = sched_nextlwp();
    415 	if (newl) {
    416 		sched_dequeue(newl);
    417 		KASSERT(lwp_locked(newl, spc->spc_mutex));
    418 		newl->l_stat = LSONPROC;
    419 		newl->l_cpu = l->l_cpu;
    420 		newl->l_flag |= LW_RUNNING;
    421 		lwp_setlock(newl, &spc->spc_lwplock);
    422 	} else {
    423 		newl = l->l_cpu->ci_data.cpu_idlelwp;
    424 		newl->l_stat = LSONPROC;
    425 		newl->l_flag |= LW_RUNNING;
    426 	}
    427 	spc->spc_curpriority = newl->l_usrpri;
    428 	cpu_did_resched();
    429 
    430 	if (l != newl) {
    431 		struct lwp *prevlwp;
    432 
    433 		/*
    434 		 * If the old LWP has been moved to a run queue above,
    435 		 * drop the general purpose LWP lock: it's now locked
    436 		 * by the scheduler lock.
    437 		 *
    438 		 * Otherwise, drop the scheduler lock.  We're done with
    439 		 * the run queues for now.
    440 		 */
    441 		if (l->l_mutex == spc->spc_mutex) {
    442 			mutex_spin_exit(&spc->spc_lwplock);
    443 		} else {
    444 			mutex_spin_exit(spc->spc_mutex);
    445 		}
    446 
    447 		/* Unlocked, but for statistics only. */
    448 		uvmexp.swtch++;
    449 
    450 		/* Save old VM context. */
    451 		pmap_deactivate(l);
    452 
    453 		/* Switch to the new LWP.. */
    454 		l->l_ncsw++;
    455 		l->l_flag &= ~LW_RUNNING;
    456 		oldspl = MUTEX_SPIN_OLDSPL(l->l_cpu);
    457 		prevlwp = cpu_switchto(l, newl);
    458 
    459 		/*
    460 		 * .. we have switched away and are now back so we must
    461 		 * be the new curlwp.  prevlwp is who we replaced.
    462 		 */
    463 		curlwp = l;
    464 		if (prevlwp != NULL) {
    465 			curcpu()->ci_mtx_oldspl = oldspl;
    466 			lwp_unlock(prevlwp);
    467 		} else {
    468 			splx(oldspl);
    469 		}
    470 
    471 		/* Restore VM context. */
    472 		pmap_activate(l);
    473 		retval = 1;
    474 	} else {
    475 		/* Nothing to do - just unlock and return. */
    476 		mutex_spin_exit(spc->spc_mutex);
    477 		lwp_unlock(l);
    478 		retval = 0;
    479 	}
    480 
    481 	KASSERT(l == curlwp);
    482 	KASSERT(l->l_stat == LSONPROC);
    483 
    484 	/*
    485 	 * XXXSMP If we are using h/w performance counters, restore context.
    486 	 */
    487 #if PERFCTRS
    488 	if (PMC_ENABLED(l->l_proc)) {
    489 		pmc_restore_context(l->l_proc);
    490 	}
    491 #endif
    492 
    493 	/*
    494 	 * We're running again; record our new start time.  We might
    495 	 * be running on a new CPU now, so don't use the cached
    496 	 * schedstate_percpu pointer.
    497 	 */
    498 	SYSCALL_TIME_WAKEUP(l);
    499 	KDASSERT(l->l_cpu == curcpu());
    500 	LOCKDEBUG_BARRIER(NULL, 1);
    501 
    502 	return retval;
    503 }
    504 
    505 /*
    506  * Change process state to be runnable, placing it on the run queue if it is
    507  * in memory, and awakening the swapper if it isn't in memory.
    508  *
    509  * Call with the process and LWP locked.  Will return with the LWP unlocked.
    510  */
    511 void
    512 setrunnable(struct lwp *l)
    513 {
    514 	struct proc *p = l->l_proc;
    515 	sigset_t *ss;
    516 
    517 	KASSERT((l->l_flag & LW_IDLE) == 0);
    518 	KASSERT(mutex_owned(&p->p_smutex));
    519 	KASSERT(lwp_locked(l, NULL));
    520 
    521 	switch (l->l_stat) {
    522 	case LSSTOP:
    523 		/*
    524 		 * If we're being traced (possibly because someone attached us
    525 		 * while we were stopped), check for a signal from the debugger.
    526 		 */
    527 		if ((p->p_slflag & PSL_TRACED) != 0 && p->p_xstat != 0) {
    528 			if ((sigprop[p->p_xstat] & SA_TOLWP) != 0)
    529 				ss = &l->l_sigpend.sp_set;
    530 			else
    531 				ss = &p->p_sigpend.sp_set;
    532 			sigaddset(ss, p->p_xstat);
    533 			signotify(l);
    534 		}
    535 		p->p_nrlwps++;
    536 		break;
    537 	case LSSUSPENDED:
    538 		l->l_flag &= ~LW_WSUSPEND;
    539 		p->p_nrlwps++;
    540 		break;
    541 	case LSSLEEP:
    542 		KASSERT(l->l_wchan != NULL);
    543 		break;
    544 	default:
    545 		panic("setrunnable: lwp %p state was %d", l, l->l_stat);
    546 	}
    547 
    548 	/*
    549 	 * If the LWP was sleeping interruptably, then it's OK to start it
    550 	 * again.  If not, mark it as still sleeping.
    551 	 */
    552 	if (l->l_wchan != NULL) {
    553 		l->l_stat = LSSLEEP;
    554 		/* lwp_unsleep() will release the lock. */
    555 		lwp_unsleep(l);
    556 		return;
    557 	}
    558 
    559 	KASSERT(lwp_locked(l, &l->l_cpu->ci_schedstate.spc_lwplock));
    560 
    561 	/*
    562 	 * If the LWP is still on the CPU, mark it as LSONPROC.  It may be
    563 	 * about to call mi_switch(), in which case it will yield.
    564 	 */
    565 	if ((l->l_flag & LW_RUNNING) != 0) {
    566 		l->l_stat = LSONPROC;
    567 		l->l_slptime = 0;
    568 		lwp_unlock(l);
    569 		return;
    570 	}
    571 
    572 	/*
    573 	 * Set the LWP runnable.  If it's swapped out, we need to wake the swapper
    574 	 * to bring it back in.  Otherwise, enter it into a run queue.
    575 	 */
    576 	spc_lock(l->l_cpu);
    577 	lwp_unlock_to(l, l->l_cpu->ci_schedstate.spc_mutex);
    578 	sched_setrunnable(l);
    579 	l->l_stat = LSRUN;
    580 	l->l_slptime = 0;
    581 
    582 	if (l->l_flag & LW_INMEM) {
    583 		sched_enqueue(l, false);
    584 		resched_cpu(l);
    585 		lwp_unlock(l);
    586 	} else {
    587 		lwp_unlock(l);
    588 		uvm_kick_scheduler();
    589 	}
    590 }
    591 
    592 /*
    593  * suspendsched:
    594  *
    595  *	Convert all non-L_SYSTEM LSSLEEP or LSRUN LWPs to LSSUSPENDED.
    596  */
    597 void
    598 suspendsched(void)
    599 {
    600 #ifdef MULTIPROCESSOR
    601 	CPU_INFO_ITERATOR cii;
    602 	struct cpu_info *ci;
    603 #endif
    604 	struct lwp *l;
    605 	struct proc *p;
    606 
    607 	/*
    608 	 * We do this by process in order not to violate the locking rules.
    609 	 */
    610 	mutex_enter(&proclist_mutex);
    611 	PROCLIST_FOREACH(p, &allproc) {
    612 		mutex_enter(&p->p_smutex);
    613 
    614 		if ((p->p_flag & PK_SYSTEM) != 0) {
    615 			mutex_exit(&p->p_smutex);
    616 			continue;
    617 		}
    618 
    619 		p->p_stat = SSTOP;
    620 
    621 		LIST_FOREACH(l, &p->p_lwps, l_sibling) {
    622 			if (l == curlwp)
    623 				continue;
    624 
    625 			lwp_lock(l);
    626 
    627 			/*
    628 			 * Set L_WREBOOT so that the LWP will suspend itself
    629 			 * when it tries to return to user mode.  We want to
    630 			 * try and get to get as many LWPs as possible to
    631 			 * the user / kernel boundary, so that they will
    632 			 * release any locks that they hold.
    633 			 */
    634 			l->l_flag |= (LW_WREBOOT | LW_WSUSPEND);
    635 
    636 			if (l->l_stat == LSSLEEP &&
    637 			    (l->l_flag & LW_SINTR) != 0) {
    638 				/* setrunnable() will release the lock. */
    639 				setrunnable(l);
    640 				continue;
    641 			}
    642 
    643 			lwp_unlock(l);
    644 		}
    645 
    646 		mutex_exit(&p->p_smutex);
    647 	}
    648 	mutex_exit(&proclist_mutex);
    649 
    650 	/*
    651 	 * Kick all CPUs to make them preempt any LWPs running in user mode.
    652 	 * They'll trap into the kernel and suspend themselves in userret().
    653 	 */
    654 #ifdef MULTIPROCESSOR
    655 	for (CPU_INFO_FOREACH(cii, ci))
    656 		cpu_need_resched(ci, 0);
    657 #else
    658 	cpu_need_resched(curcpu(), 0);
    659 #endif
    660 }
    661 
    662 /*
    663  * sched_kpri:
    664  *
    665  *	Scale a priority level to a kernel priority level, usually
    666  *	for an LWP that is about to sleep.
    667  */
    668 pri_t
    669 sched_kpri(struct lwp *l)
    670 {
    671 	/*
    672 	 * Scale user priorities (127 -> 50) up to kernel priorities
    673 	 * in the range (49 -> 8).  Reserve the top 8 kernel priorities
    674 	 * for high priority kthreads.  Kernel priorities passed in
    675 	 * are left "as is".  XXX This is somewhat arbitrary.
    676 	 */
    677 	static const uint8_t kpri_tab[] = {
    678 		 0,   1,   2,   3,   4,   5,   6,   7,
    679 		 8,   9,  10,  11,  12,  13,  14,  15,
    680 		16,  17,  18,  19,  20,  21,  22,  23,
    681 		24,  25,  26,  27,  28,  29,  30,  31,
    682 		32,  33,  34,  35,  36,  37,  38,  39,
    683 		40,  41,  42,  43,  44,  45,  46,  47,
    684 		48,  49,   8,   8,   9,   9,  10,  10,
    685 		11,  11,  12,  12,  13,  14,  14,  15,
    686 		15,  16,  16,  17,  17,  18,  18,  19,
    687 		20,  20,  21,  21,  22,  22,  23,  23,
    688 		24,  24,  25,  26,  26,  27,  27,  28,
    689 		28,  29,  29,  30,  30,  31,  32,  32,
    690 		33,  33,  34,  34,  35,  35,  36,  36,
    691 		37,  38,  38,  39,  39,  40,  40,  41,
    692 		41,  42,  42,  43,  44,  44,  45,  45,
    693 		46,  46,  47,  47,  48,  48,  49,  49,
    694 	};
    695 
    696 	return (pri_t)kpri_tab[l->l_usrpri];
    697 }
    698 
    699 /*
    700  * sched_unsleep:
    701  *
    702  *	The is called when the LWP has not been awoken normally but instead
    703  *	interrupted: for example, if the sleep timed out.  Because of this,
    704  *	it's not a valid action for running or idle LWPs.
    705  */
    706 static void
    707 sched_unsleep(struct lwp *l)
    708 {
    709 
    710 	lwp_unlock(l);
    711 	panic("sched_unsleep");
    712 }
    713 
    714 inline void
    715 resched_cpu(struct lwp *l)
    716 {
    717 	struct cpu_info *ci;
    718 	const pri_t pri = lwp_eprio(l);
    719 
    720 	/*
    721 	 * XXXSMP
    722 	 * Since l->l_cpu persists across a context switch,
    723 	 * this gives us *very weak* processor affinity, in
    724 	 * that we notify the CPU on which the process last
    725 	 * ran that it should try to switch.
    726 	 *
    727 	 * This does not guarantee that the process will run on
    728 	 * that processor next, because another processor might
    729 	 * grab it the next time it performs a context switch.
    730 	 *
    731 	 * This also does not handle the case where its last
    732 	 * CPU is running a higher-priority process, but every
    733 	 * other CPU is running a lower-priority process.  There
    734 	 * are ways to handle this situation, but they're not
    735 	 * currently very pretty, and we also need to weigh the
    736 	 * cost of moving a process from one CPU to another.
    737 	 */
    738 	ci = (l->l_cpu != NULL) ? l->l_cpu : curcpu();
    739 	if (pri < ci->ci_schedstate.spc_curpriority)
    740 		cpu_need_resched(ci, 0);
    741 }
    742 
    743 static void
    744 sched_changepri(struct lwp *l, pri_t pri)
    745 {
    746 
    747 	KASSERT(lwp_locked(l, NULL));
    748 
    749 	l->l_usrpri = pri;
    750 	if (l->l_priority < PUSER)
    751 		return;
    752 
    753 	if (l->l_stat != LSRUN || (l->l_flag & LW_INMEM) == 0) {
    754 		l->l_priority = pri;
    755 		return;
    756 	}
    757 
    758 	KASSERT(lwp_locked(l, l->l_cpu->ci_schedstate.spc_mutex));
    759 
    760 	sched_dequeue(l);
    761 	l->l_priority = pri;
    762 	sched_enqueue(l, false);
    763 	resched_cpu(l);
    764 }
    765 
    766 static void
    767 sched_lendpri(struct lwp *l, pri_t pri)
    768 {
    769 
    770 	KASSERT(lwp_locked(l, NULL));
    771 
    772 	if (l->l_stat != LSRUN || (l->l_flag & LW_INMEM) == 0) {
    773 		l->l_inheritedprio = pri;
    774 		return;
    775 	}
    776 
    777 	KASSERT(lwp_locked(l, l->l_cpu->ci_schedstate.spc_mutex));
    778 
    779 	sched_dequeue(l);
    780 	l->l_inheritedprio = pri;
    781 	sched_enqueue(l, false);
    782 	resched_cpu(l);
    783 }
    784 
    785 struct lwp *
    786 syncobj_noowner(wchan_t wchan)
    787 {
    788 
    789 	return NULL;
    790 }
    791 
    792 
    793 /* decay 95% of `p_pctcpu' in 60 seconds; see CCPU_SHIFT before changing */
    794 fixpt_t	ccpu = 0.95122942450071400909 * FSCALE;		/* exp(-1/20) */
    795 
    796 /*
    797  * If `ccpu' is not equal to `exp(-1/20)' and you still want to use the
    798  * faster/more-accurate formula, you'll have to estimate CCPU_SHIFT below
    799  * and possibly adjust FSHIFT in "param.h" so that (FSHIFT >= CCPU_SHIFT).
    800  *
    801  * To estimate CCPU_SHIFT for exp(-1/20), the following formula was used:
    802  *	1 - exp(-1/20) ~= 0.0487 ~= 0.0488 == 1 (fixed pt, *11* bits).
    803  *
    804  * If you dont want to bother with the faster/more-accurate formula, you
    805  * can set CCPU_SHIFT to (FSHIFT + 1) which will use a slower/less-accurate
    806  * (more general) method of calculating the %age of CPU used by a process.
    807  */
    808 #define	CCPU_SHIFT	(FSHIFT + 1)
    809 
    810 /*
    811  * sched_pstats:
    812  *
    813  * Update process statistics and check CPU resource allocation.
    814  * Call scheduler-specific hook to eventually adjust process/LWP
    815  * priorities.
    816  *
    817  *	XXXSMP This needs to be reorganised in order to reduce the locking
    818  *	burden.
    819  */
    820 /* ARGSUSED */
    821 void
    822 sched_pstats(void *arg)
    823 {
    824 	struct rlimit *rlim;
    825 	struct lwp *l;
    826 	struct proc *p;
    827 	int minslp, sig, clkhz;
    828 	long runtm;
    829 
    830 	sched_pstats_ticks++;
    831 
    832 	mutex_enter(&proclist_mutex);
    833 	PROCLIST_FOREACH(p, &allproc) {
    834 		/*
    835 		 * Increment time in/out of memory and sleep time (if
    836 		 * sleeping).  We ignore overflow; with 16-bit int's
    837 		 * (remember them?) overflow takes 45 days.
    838 		 */
    839 		minslp = 2;
    840 		mutex_enter(&p->p_smutex);
    841 		mutex_spin_enter(&p->p_stmutex);
    842 		runtm = p->p_rtime.tv_sec;
    843 		LIST_FOREACH(l, &p->p_lwps, l_sibling) {
    844 			if ((l->l_flag & LW_IDLE) != 0)
    845 				continue;
    846 			lwp_lock(l);
    847 			runtm += l->l_rtime.tv_sec;
    848 			l->l_swtime++;
    849 			if (l->l_stat == LSSLEEP || l->l_stat == LSSTOP ||
    850 			    l->l_stat == LSSUSPENDED) {
    851 				l->l_slptime++;
    852 				minslp = min(minslp, l->l_slptime);
    853 			} else
    854 				minslp = 0;
    855 			lwp_unlock(l);
    856 
    857 			/*
    858 			 * p_pctcpu is only for ps.
    859 			 */
    860 			l->l_pctcpu = (l->l_pctcpu * ccpu) >> FSHIFT;
    861 			if (l->l_slptime < 1) {
    862 				clkhz = stathz != 0 ? stathz : hz;
    863 #if	(FSHIFT >= CCPU_SHIFT)
    864 				l->l_pctcpu += (clkhz == 100) ?
    865 				    ((fixpt_t)l->l_cpticks) <<
    866 				        (FSHIFT - CCPU_SHIFT) :
    867 				    100 * (((fixpt_t) p->p_cpticks)
    868 				        << (FSHIFT - CCPU_SHIFT)) / clkhz;
    869 #else
    870 				l->l_pctcpu += ((FSCALE - ccpu) *
    871 				    (l->l_cpticks * FSCALE / clkhz)) >> FSHIFT;
    872 #endif
    873 				l->l_cpticks = 0;
    874 			}
    875 		}
    876 		p->p_pctcpu = (p->p_pctcpu * ccpu) >> FSHIFT;
    877 		sched_pstats_hook(p, minslp);
    878 		mutex_spin_exit(&p->p_stmutex);
    879 
    880 		/*
    881 		 * Check if the process exceeds its CPU resource allocation.
    882 		 * If over max, kill it.
    883 		 */
    884 		rlim = &p->p_rlimit[RLIMIT_CPU];
    885 		sig = 0;
    886 		if (runtm >= rlim->rlim_cur) {
    887 			if (runtm >= rlim->rlim_max)
    888 				sig = SIGKILL;
    889 			else {
    890 				sig = SIGXCPU;
    891 				if (rlim->rlim_cur < rlim->rlim_max)
    892 					rlim->rlim_cur += 5;
    893 			}
    894 		}
    895 		mutex_exit(&p->p_smutex);
    896 		if (sig) {
    897 			psignal(p, sig);
    898 		}
    899 	}
    900 	mutex_exit(&proclist_mutex);
    901 	uvm_meter();
    902 	wakeup(&lbolt);
    903 	callout_schedule(&sched_pstats_ch, hz);
    904 }
    905