Home | History | Annotate | Line # | Download | only in kern
kern_lock.c revision 1.99.2.3
      1 /*	$NetBSD: kern_lock.c,v 1.99.2.3 2006/10/24 19:21:40 ad Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1999, 2000 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.
     10  *
     11  * This code is derived from software contributed to The NetBSD Foundation
     12  * by Ross Harvey.
     13  *
     14  * Redistribution and use in source and binary forms, with or without
     15  * modification, are permitted provided that the following conditions
     16  * are met:
     17  * 1. Redistributions of source code must retain the above copyright
     18  *    notice, this list of conditions and the following disclaimer.
     19  * 2. Redistributions in binary form must reproduce the above copyright
     20  *    notice, this list of conditions and the following disclaimer in the
     21  *    documentation and/or other materials provided with the distribution.
     22  * 3. All advertising materials mentioning features or use of this software
     23  *    must display the following acknowledgement:
     24  *	This product includes software developed by the NetBSD
     25  *	Foundation, Inc. and its contributors.
     26  * 4. Neither the name of The NetBSD Foundation nor the names of its
     27  *    contributors may be used to endorse or promote products derived
     28  *    from this software without specific prior written permission.
     29  *
     30  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     31  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     32  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     33  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     34  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     35  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     36  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     37  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     38  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     39  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     40  * POSSIBILITY OF SUCH DAMAGE.
     41  */
     42 
     43 /*
     44  * Copyright (c) 1995
     45  *	The Regents of the University of California.  All rights reserved.
     46  *
     47  * This code contains ideas from software contributed to Berkeley by
     48  * Avadis Tevanian, Jr., Michael Wayne Young, and the Mach Operating
     49  * System project at Carnegie-Mellon University.
     50  *
     51  * Redistribution and use in source and binary forms, with or without
     52  * modification, are permitted provided that the following conditions
     53  * are met:
     54  * 1. Redistributions of source code must retain the above copyright
     55  *    notice, this list of conditions and the following disclaimer.
     56  * 2. Redistributions in binary form must reproduce the above copyright
     57  *    notice, this list of conditions and the following disclaimer in the
     58  *    documentation and/or other materials provided with the distribution.
     59  * 3. Neither the name of the University nor the names of its contributors
     60  *    may be used to endorse or promote products derived from this software
     61  *    without specific prior written permission.
     62  *
     63  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     64  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     65  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     66  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     67  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     68  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     69  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     70  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     71  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     72  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     73  * SUCH DAMAGE.
     74  *
     75  *	@(#)kern_lock.c	8.18 (Berkeley) 5/21/95
     76  */
     77 
     78 #include <sys/cdefs.h>
     79 __KERNEL_RCSID(0, "$NetBSD: kern_lock.c,v 1.99.2.3 2006/10/24 19:21:40 ad Exp $");
     80 
     81 #include "opt_multiprocessor.h"
     82 #include "opt_ddb.h"
     83 
     84 #define	__MUTEX_PRIVATE
     85 
     86 #include <sys/param.h>
     87 #include <sys/proc.h>
     88 #include <sys/lock.h>
     89 #include <sys/systm.h>
     90 #include <sys/lockdebug.h>
     91 
     92 #include <machine/cpu.h>
     93 
     94 #include <dev/lockstat.h>
     95 
     96 #if defined(LOCKDEBUG)
     97 #include <sys/syslog.h>
     98 /*
     99  * note that stdarg.h and the ansi style va_start macro is used for both
    100  * ansi and traditional c compiles.
    101  * XXX: this requires that stdarg.h define: va_alist and va_dcl
    102  */
    103 #include <machine/stdarg.h>
    104 
    105 void	lock_printf(const char *fmt, ...)
    106     __attribute__((__format__(__printf__,1,2)));
    107 
    108 static int acquire(volatile struct lock **, int *, int, int, int, uintptr_t);
    109 
    110 int	lock_debug_syslog = 0;	/* defaults to printf, but can be patched */
    111 
    112 #ifdef DDB
    113 #include <ddb/ddbvar.h>
    114 #include <machine/db_machdep.h>
    115 #include <ddb/db_command.h>
    116 #include <ddb/db_interface.h>
    117 #endif
    118 #endif /* defined(LOCKDEBUG) */
    119 
    120 #if defined(MULTIPROCESSOR)
    121 /*
    122  * IPL_BIGLOCK: block IPLs which need to grab kernel_mutex.
    123  * XXX IPL_VM or IPL_AUDIO should be enough.
    124  */
    125 #if !defined(__HAVE_SPLBIGLOCK)
    126 #define	IPL_BIGLOCK	IPL_CLOCK
    127 #endif
    128 kmutex_t kernel_mutex;
    129 #endif
    130 
    131 /*
    132  * Locking primitives implementation.
    133  * Locks provide shared/exclusive synchronization.
    134  */
    135 
    136 #if defined(LOCKDEBUG) || defined(DIAGNOSTIC) /* { */
    137 #if defined(MULTIPROCESSOR) /* { */
    138 #define	COUNT_CPU(cpu_id, x)						\
    139 	curcpu()->ci_spin_locks += (x)
    140 #else
    141 u_long	spin_locks;
    142 #define	COUNT_CPU(cpu_id, x)	spin_locks += (x)
    143 #endif /* MULTIPROCESSOR */ /* } */
    144 
    145 #define	COUNT(lkp, l, cpu_id, x)					\
    146 do {									\
    147 	if ((lkp)->lk_flags & LK_SPIN)					\
    148 		COUNT_CPU((cpu_id), (x));				\
    149 	else								\
    150 		(l)->l_locks += (x);					\
    151 } while (/*CONSTCOND*/0)
    152 #else
    153 #define COUNT(lkp, p, cpu_id, x)
    154 #define COUNT_CPU(cpu_id, x)
    155 #endif /* LOCKDEBUG || DIAGNOSTIC */ /* } */
    156 
    157 #define	INTERLOCK_ACQUIRE(lkp, flags, s)				\
    158 do {									\
    159 	if ((flags) & LK_SPIN)						\
    160 		s = spllock();						\
    161 	simple_lock(&(lkp)->lk_interlock);				\
    162 } while (/*CONSTCOND*/ 0)
    163 
    164 #define	INTERLOCK_RELEASE(lkp, flags, s)				\
    165 do {									\
    166 	simple_unlock(&(lkp)->lk_interlock);				\
    167 	if ((flags) & LK_SPIN)						\
    168 		splx(s);						\
    169 } while (/*CONSTCOND*/ 0)
    170 
    171 #ifdef DDB /* { */
    172 #if defined(MULTIPROCESSOR) || defined(LOCKDEBUG)
    173 int simple_lock_debugger = 1;	/* more serious on MP */
    174 #else
    175 int simple_lock_debugger = 0;
    176 #endif
    177 #define	SLOCK_DEBUGGER()	if (simple_lock_debugger && db_onpanic) Debugger()
    178 #define	SLOCK_TRACE()							\
    179 	db_stack_trace_print((db_expr_t)__builtin_frame_address(0),	\
    180 	    TRUE, 65535, "", lock_printf);
    181 #else
    182 #define	SLOCK_DEBUGGER()	/* nothing */
    183 #define	SLOCK_TRACE()		/* nothing */
    184 #endif /* } */
    185 
    186 #if defined(LOCKDEBUG)
    187 #if defined(DDB)
    188 #define	SPINLOCK_SPINCHECK_DEBUGGER	if (db_onpanic) Debugger()
    189 #else
    190 #define	SPINLOCK_SPINCHECK_DEBUGGER	/* nothing */
    191 #endif
    192 
    193 #define	SPINLOCK_SPINCHECK_DECL						\
    194 	/* 32-bits of count -- wrap constitutes a "spinout" */		\
    195 	uint32_t __spinc = 0
    196 
    197 #define	SPINLOCK_SPINCHECK						\
    198 do {									\
    199 	if (++__spinc == 0) {						\
    200 		lock_printf("LK_SPIN spinout, excl %d, share %d\n",	\
    201 		    lkp->lk_exclusivecount, lkp->lk_sharecount);	\
    202 		if (lkp->lk_exclusivecount)				\
    203 			lock_printf("held by CPU %lu\n",		\
    204 			    (u_long) lkp->lk_cpu);			\
    205 		if (lkp->lk_lock_file)					\
    206 			lock_printf("last locked at %s:%d\n",		\
    207 			    lkp->lk_lock_file, lkp->lk_lock_line);	\
    208 		if (lkp->lk_unlock_file)				\
    209 			lock_printf("last unlocked at %s:%d\n",		\
    210 			    lkp->lk_unlock_file, lkp->lk_unlock_line);	\
    211 		SLOCK_TRACE();						\
    212 		SPINLOCK_SPINCHECK_DEBUGGER;				\
    213 	}								\
    214 } while (/*CONSTCOND*/ 0)
    215 #else
    216 #define	SPINLOCK_SPINCHECK_DECL			/* nothing */
    217 #define	SPINLOCK_SPINCHECK			/* nothing */
    218 #endif /* LOCKDEBUG && DDB */
    219 
    220 #define	RETURN_ADDRESS		((uintptr_t)__builtin_return_address(0))
    221 
    222 /*
    223  * Acquire a resource.
    224  */
    225 static int
    226 acquire(volatile struct lock **lkpp, int *s, int extflags,
    227     int drain, int wanted, uintptr_t ra)
    228 {
    229 	int error;
    230 	volatile struct lock *lkp = *lkpp;
    231 	LOCKSTAT_TIMER(slptime);
    232 
    233 	KASSERT(drain || (wanted & LK_WAIT_NONZERO) == 0);
    234 
    235 	if (extflags & LK_SPIN) {
    236 		int interlocked;
    237 
    238 		SPINLOCK_SPINCHECK_DECL;
    239 
    240 		if (!drain) {
    241 			lkp->lk_waitcount++;
    242 			lkp->lk_flags |= LK_WAIT_NONZERO;
    243 		}
    244 		for (interlocked = 1;;) {
    245 			SPINLOCK_SPINCHECK;
    246 			if ((lkp->lk_flags & wanted) != 0) {
    247 				if (interlocked) {
    248 					INTERLOCK_RELEASE(lkp, LK_SPIN, *s);
    249 					interlocked = 0;
    250 				}
    251 				SPINLOCK_SPIN_HOOK;
    252 			} else if (interlocked) {
    253 				break;
    254 			} else {
    255 				INTERLOCK_ACQUIRE(lkp, LK_SPIN, *s);
    256 				interlocked = 1;
    257 			}
    258 		}
    259 		if (!drain) {
    260 			lkp->lk_waitcount--;
    261 			if (lkp->lk_waitcount == 0)
    262 				lkp->lk_flags &= ~LK_WAIT_NONZERO;
    263 		}
    264 		KASSERT((lkp->lk_flags & wanted) == 0);
    265 		error = 0;	/* sanity */
    266 	} else {
    267 		for (error = 0; (lkp->lk_flags & wanted) != 0; ) {
    268 			if (drain)
    269 				lkp->lk_flags |= LK_WAITDRAIN;
    270 			else {
    271 				lkp->lk_waitcount++;
    272 				lkp->lk_flags |= LK_WAIT_NONZERO;
    273 			}
    274 			/* XXX Cast away volatile. */
    275 			LOCKSTAT_START_TIMER(slptime);
    276 			error = ltsleep(drain ?
    277 			    (volatile const void *)&lkp->lk_flags :
    278 			    (volatile const void *)lkp, lkp->lk_prio,
    279 			    lkp->lk_wmesg, lkp->lk_timo, &lkp->lk_interlock);
    280 			LOCKSTAT_STOP_TIMER(slptime);
    281 			LOCKSTAT_EVENT_RA((void *)(uintptr_t)lkp,
    282 			    LB_LOCKMGR | LB_SLEEP, 1, slptime, ra);
    283 			if (!drain) {
    284 				lkp->lk_waitcount--;
    285 				if (lkp->lk_waitcount == 0)
    286 					lkp->lk_flags &= ~LK_WAIT_NONZERO;
    287 			}
    288 			if (error)
    289 				break;
    290 			if (extflags & LK_SLEEPFAIL) {
    291 				error = ENOLCK;
    292 				break;
    293 			}
    294 			if (lkp->lk_newlock != NULL) {
    295 				simple_lock(&lkp->lk_newlock->lk_interlock);
    296 				simple_unlock(&lkp->lk_interlock);
    297 				if (lkp->lk_waitcount == 0)
    298 					wakeup(&lkp->lk_newlock);
    299 				*lkpp = lkp = lkp->lk_newlock;
    300 			}
    301 		}
    302 	}
    303 
    304 	return error;
    305 }
    306 
    307 #define	SETHOLDER(lkp, pid, lid, cpu_id)				\
    308 do {									\
    309 	if ((lkp)->lk_flags & LK_SPIN)					\
    310 		(lkp)->lk_cpu = cpu_id;					\
    311 	else {								\
    312 		(lkp)->lk_lockholder = pid;				\
    313 		(lkp)->lk_locklwp = lid;				\
    314 	}								\
    315 } while (/*CONSTCOND*/0)
    316 
    317 #define	WEHOLDIT(lkp, pid, lid, cpu_id)					\
    318 	(((lkp)->lk_flags & LK_SPIN) != 0 ?				\
    319 	 ((lkp)->lk_cpu == (cpu_id)) :					\
    320 	 ((lkp)->lk_lockholder == (pid) && (lkp)->lk_locklwp == (lid)))
    321 
    322 #define	WAKEUP_WAITER(lkp)						\
    323 do {									\
    324 	if (((lkp)->lk_flags & (LK_SPIN | LK_WAIT_NONZERO)) ==		\
    325 	    LK_WAIT_NONZERO) {						\
    326 		wakeup((lkp));						\
    327 	}								\
    328 } while (/*CONSTCOND*/0)
    329 
    330 #if defined(LOCKDEBUG) /* { */
    331 #if defined(MULTIPROCESSOR) /* { */
    332 struct simplelock spinlock_list_slock = SIMPLELOCK_INITIALIZER;
    333 
    334 #define	SPINLOCK_LIST_LOCK()						\
    335 	__cpu_simple_lock(&spinlock_list_slock.lock_data)
    336 
    337 #define	SPINLOCK_LIST_UNLOCK()						\
    338 	__cpu_simple_unlock(&spinlock_list_slock.lock_data)
    339 #else
    340 #define	SPINLOCK_LIST_LOCK()	/* nothing */
    341 
    342 #define	SPINLOCK_LIST_UNLOCK()	/* nothing */
    343 #endif /* MULTIPROCESSOR */ /* } */
    344 
    345 _TAILQ_HEAD(, struct lock, volatile) spinlock_list =
    346     TAILQ_HEAD_INITIALIZER(spinlock_list);
    347 
    348 #define	HAVEIT(lkp)							\
    349 do {									\
    350 	if ((lkp)->lk_flags & LK_SPIN) {				\
    351 		int sp = spllock();					\
    352 		SPINLOCK_LIST_LOCK();					\
    353 		TAILQ_INSERT_TAIL(&spinlock_list, (lkp), lk_list);	\
    354 		SPINLOCK_LIST_UNLOCK();					\
    355 		splx(sp);						\
    356 	}								\
    357 } while (/*CONSTCOND*/0)
    358 
    359 #define	DONTHAVEIT(lkp)							\
    360 do {									\
    361 	if ((lkp)->lk_flags & LK_SPIN) {				\
    362 		int sp = spllock();					\
    363 		SPINLOCK_LIST_LOCK();					\
    364 		TAILQ_REMOVE(&spinlock_list, (lkp), lk_list);		\
    365 		SPINLOCK_LIST_UNLOCK();					\
    366 		splx(sp);						\
    367 	}								\
    368 } while (/*CONSTCOND*/0)
    369 #else
    370 #define	HAVEIT(lkp)		/* nothing */
    371 
    372 #define	DONTHAVEIT(lkp)		/* nothing */
    373 #endif /* LOCKDEBUG */ /* } */
    374 
    375 #if defined(LOCKDEBUG)
    376 /*
    377  * Lock debug printing routine; can be configured to print to console
    378  * or log to syslog.
    379  */
    380 void
    381 lock_printf(const char *fmt, ...)
    382 {
    383 	char b[150];
    384 	va_list ap;
    385 
    386 	va_start(ap, fmt);
    387 	if (lock_debug_syslog)
    388 		vlog(LOG_DEBUG, fmt, ap);
    389 	else {
    390 		vsnprintf(b, sizeof(b), fmt, ap);
    391 		printf_nolog("%s", b);
    392 	}
    393 	va_end(ap);
    394 }
    395 #endif /* LOCKDEBUG */
    396 
    397 /*
    398  * Transfer any waiting processes from one lock to another.
    399  */
    400 void
    401 transferlockers(struct lock *from, struct lock *to)
    402 {
    403 
    404 	KASSERT(from != to);
    405 	KASSERT((from->lk_flags & LK_WAITDRAIN) == 0);
    406 	if (from->lk_waitcount == 0)
    407 		return;
    408 	from->lk_newlock = to;
    409 	wakeup((void *)from);
    410 	tsleep((void *)&from->lk_newlock, from->lk_prio, "lkxfer", 0);
    411 	from->lk_newlock = NULL;
    412 	from->lk_flags &= ~(LK_WANT_EXCL | LK_WANT_UPGRADE);
    413 	KASSERT(from->lk_waitcount == 0);
    414 }
    415 
    416 
    417 /*
    418  * Initialize a lock; required before use.
    419  */
    420 void
    421 lockinit(struct lock *lkp, int prio, const char *wmesg, int timo, int flags)
    422 {
    423 
    424 	memset(lkp, 0, sizeof(struct lock));
    425 	simple_lock_init(&lkp->lk_interlock);
    426 	lkp->lk_flags = flags & LK_EXTFLG_MASK;
    427 	if (flags & LK_SPIN)
    428 		lkp->lk_cpu = LK_NOCPU;
    429 	else {
    430 		lkp->lk_lockholder = LK_NOPROC;
    431 		lkp->lk_newlock = NULL;
    432 		lkp->lk_prio = prio;
    433 		lkp->lk_timo = timo;
    434 	}
    435 	lkp->lk_wmesg = wmesg;	/* just a name for spin locks */
    436 #if defined(LOCKDEBUG)
    437 	lkp->lk_lock_file = NULL;
    438 	lkp->lk_unlock_file = NULL;
    439 #endif
    440 }
    441 
    442 /*
    443  * Determine the status of a lock.
    444  */
    445 int
    446 lockstatus(struct lock *lkp)
    447 {
    448 	int s = 0; /* XXX: gcc */
    449 	int lock_type = 0;
    450 	struct lwp *l = curlwp; /* XXX */
    451 	pid_t pid;
    452 	lwpid_t lid;
    453 	cpuid_t cpu_num;
    454 
    455 	if ((lkp->lk_flags & LK_SPIN) || l == NULL) {
    456 		cpu_num = cpu_number();
    457 		pid = LK_KERNPROC;
    458 		lid = 0;
    459 	} else {
    460 		cpu_num = LK_NOCPU;
    461 		pid = l->l_proc->p_pid;
    462 		lid = l->l_lid;
    463 	}
    464 
    465 	INTERLOCK_ACQUIRE(lkp, lkp->lk_flags, s);
    466 	if (lkp->lk_exclusivecount != 0) {
    467 		if (WEHOLDIT(lkp, pid, lid, cpu_num))
    468 			lock_type = LK_EXCLUSIVE;
    469 		else
    470 			lock_type = LK_EXCLOTHER;
    471 	} else if (lkp->lk_sharecount != 0)
    472 		lock_type = LK_SHARED;
    473 	INTERLOCK_RELEASE(lkp, lkp->lk_flags, s);
    474 	return (lock_type);
    475 }
    476 
    477 #if defined(LOCKDEBUG)
    478 /*
    479  * Make sure no spin locks are held by a CPU that is about
    480  * to context switch.
    481  */
    482 void
    483 spinlock_switchcheck(void)
    484 {
    485 	u_long cnt;
    486 	int s;
    487 
    488 	s = spllock();
    489 #if defined(MULTIPROCESSOR)
    490 	cnt = curcpu()->ci_spin_locks;
    491 #else
    492 	cnt = spin_locks;
    493 #endif
    494 	splx(s);
    495 
    496 	if (cnt != 0)
    497 		panic("spinlock_switchcheck: CPU %lu has %lu spin locks",
    498 		    (u_long) cpu_number(), cnt);
    499 }
    500 #endif /* LOCKDEBUG */
    501 
    502 /*
    503  * Locks and IPLs (interrupt priority levels):
    504  *
    505  * Locks which may be taken from interrupt context must be handled
    506  * very carefully; you must spl to the highest IPL where the lock
    507  * is needed before acquiring the lock.
    508  *
    509  * It is also important to avoid deadlock, since certain (very high
    510  * priority) interrupts are often needed to keep the system as a whole
    511  * from deadlocking, and must not be blocked while you are spinning
    512  * waiting for a lower-priority lock.
    513  *
    514  * In addition, the lock-debugging hooks themselves need to use locks!
    515  *
    516  * A raw __cpu_simple_lock may be used from interrupts are long as it
    517  * is acquired and held at a single IPL.
    518  *
    519  * A simple_lock (which is a __cpu_simple_lock wrapped with some
    520  * debugging hooks) may be used at or below spllock(), which is
    521  * typically at or just below splhigh() (i.e. blocks everything
    522  * but certain machine-dependent extremely high priority interrupts).
    523  *
    524  * spinlockmgr spinlocks should be used at or below splsched().
    525  *
    526  * Some platforms may have interrupts of higher priority than splsched(),
    527  * including hard serial interrupts, inter-processor interrupts, and
    528  * kernel debugger traps.
    529  */
    530 
    531 /*
    532  * XXX XXX kludge around another kludge..
    533  *
    534  * vfs_shutdown() may be called from interrupt context, either as a result
    535  * of a panic, or from the debugger.   It proceeds to call
    536  * sys_sync(&proc0, ...), pretending its running on behalf of proc0
    537  *
    538  * We would like to make an attempt to sync the filesystems in this case, so
    539  * if this happens, we treat attempts to acquire locks specially.
    540  * All locks are acquired on behalf of proc0.
    541  *
    542  * If we've already paniced, we don't block waiting for locks, but
    543  * just barge right ahead since we're already going down in flames.
    544  */
    545 
    546 /*
    547  * Set, change, or release a lock.
    548  *
    549  * Shared requests increment the shared count. Exclusive requests set the
    550  * LK_WANT_EXCL flag (preventing further shared locks), and wait for already
    551  * accepted shared locks and shared-to-exclusive upgrades to go away.
    552  */
    553 int
    554 #if defined(LOCKDEBUG)
    555 _lockmgr(volatile struct lock *lkp, u_int flags,
    556     struct simplelock *interlkp, const char *file, int line)
    557 #else
    558 lockmgr(volatile struct lock *lkp, u_int flags,
    559     struct simplelock *interlkp)
    560 #endif
    561 {
    562 	int error;
    563 	pid_t pid;
    564 	lwpid_t lid;
    565 	int extflags;
    566 	cpuid_t cpu_num;
    567 	struct lwp *l = curlwp;
    568 	int lock_shutdown_noblock = 0;
    569 	int s = 0;
    570 
    571 	error = 0;
    572 
    573 	/* LK_RETRY is for vn_lock, not for lockmgr. */
    574 	KASSERT((flags & LK_RETRY) == 0);
    575 
    576 	INTERLOCK_ACQUIRE(lkp, lkp->lk_flags, s);
    577 	if (flags & LK_INTERLOCK)
    578 		simple_unlock(interlkp);
    579 	extflags = (flags | lkp->lk_flags) & LK_EXTFLG_MASK;
    580 
    581 #ifdef DIAGNOSTIC /* { */
    582 	/*
    583 	 * Don't allow spins on sleep locks and don't allow sleeps
    584 	 * on spin locks.
    585 	 */
    586 	if ((flags ^ lkp->lk_flags) & LK_SPIN)
    587 		panic("lockmgr: sleep/spin mismatch");
    588 #endif /* } */
    589 
    590 	if (extflags & LK_SPIN) {
    591 		pid = LK_KERNPROC;
    592 		lid = 0;
    593 	} else {
    594 		if (l == NULL) {
    595 			if (!doing_shutdown) {
    596 				panic("lockmgr: no context");
    597 			} else {
    598 				l = &lwp0;
    599 				if (panicstr && (!(flags & LK_NOWAIT))) {
    600 					flags |= LK_NOWAIT;
    601 					lock_shutdown_noblock = 1;
    602 				}
    603 			}
    604 		}
    605 		lid = l->l_lid;
    606 		pid = l->l_proc->p_pid;
    607 	}
    608 	cpu_num = cpu_number();
    609 
    610 	/*
    611 	 * Once a lock has drained, the LK_DRAINING flag is set and an
    612 	 * exclusive lock is returned. The only valid operation thereafter
    613 	 * is a single release of that exclusive lock. This final release
    614 	 * clears the LK_DRAINING flag and sets the LK_DRAINED flag. Any
    615 	 * further requests of any sort will result in a panic. The bits
    616 	 * selected for these two flags are chosen so that they will be set
    617 	 * in memory that is freed (freed memory is filled with 0xdeadbeef).
    618 	 * The final release is permitted to give a new lease on life to
    619 	 * the lock by specifying LK_REENABLE.
    620 	 */
    621 	if (lkp->lk_flags & (LK_DRAINING|LK_DRAINED)) {
    622 #ifdef DIAGNOSTIC /* { */
    623 		if (lkp->lk_flags & LK_DRAINED)
    624 			panic("lockmgr: using decommissioned lock");
    625 		if ((flags & LK_TYPE_MASK) != LK_RELEASE ||
    626 		    WEHOLDIT(lkp, pid, lid, cpu_num) == 0)
    627 			panic("lockmgr: non-release on draining lock: %d",
    628 			    flags & LK_TYPE_MASK);
    629 #endif /* DIAGNOSTIC */ /* } */
    630 		lkp->lk_flags &= ~LK_DRAINING;
    631 		if ((flags & LK_REENABLE) == 0)
    632 			lkp->lk_flags |= LK_DRAINED;
    633 	}
    634 
    635 	switch (flags & LK_TYPE_MASK) {
    636 
    637 	case LK_SHARED:
    638 		if (WEHOLDIT(lkp, pid, lid, cpu_num) == 0) {
    639 			/*
    640 			 * If just polling, check to see if we will block.
    641 			 */
    642 			if ((extflags & LK_NOWAIT) && (lkp->lk_flags &
    643 			    (LK_HAVE_EXCL | LK_WANT_EXCL | LK_WANT_UPGRADE))) {
    644 				error = EBUSY;
    645 				break;
    646 			}
    647 			/*
    648 			 * Wait for exclusive locks and upgrades to clear.
    649 			 */
    650 			error = acquire(&lkp, &s, extflags, 0,
    651 			    LK_HAVE_EXCL | LK_WANT_EXCL | LK_WANT_UPGRADE,
    652 			    RETURN_ADDRESS);
    653 			if (error)
    654 				break;
    655 			lkp->lk_sharecount++;
    656 			lkp->lk_flags |= LK_SHARE_NONZERO;
    657 			COUNT(lkp, l, cpu_num, 1);
    658 			break;
    659 		}
    660 		/*
    661 		 * We hold an exclusive lock, so downgrade it to shared.
    662 		 * An alternative would be to fail with EDEADLK.
    663 		 */
    664 		lkp->lk_sharecount++;
    665 		lkp->lk_flags |= LK_SHARE_NONZERO;
    666 		COUNT(lkp, l, cpu_num, 1);
    667 		/* fall into downgrade */
    668 
    669 	case LK_DOWNGRADE:
    670 		if (WEHOLDIT(lkp, pid, lid, cpu_num) == 0 ||
    671 		    lkp->lk_exclusivecount == 0)
    672 			panic("lockmgr: not holding exclusive lock");
    673 		lkp->lk_sharecount += lkp->lk_exclusivecount;
    674 		lkp->lk_flags |= LK_SHARE_NONZERO;
    675 		lkp->lk_exclusivecount = 0;
    676 		lkp->lk_recurselevel = 0;
    677 		lkp->lk_flags &= ~LK_HAVE_EXCL;
    678 		SETHOLDER(lkp, LK_NOPROC, 0, LK_NOCPU);
    679 #if defined(LOCKDEBUG)
    680 		lkp->lk_unlock_file = file;
    681 		lkp->lk_unlock_line = line;
    682 #endif
    683 		DONTHAVEIT(lkp);
    684 		WAKEUP_WAITER(lkp);
    685 		break;
    686 
    687 	case LK_EXCLUPGRADE:
    688 		/*
    689 		 * If another process is ahead of us to get an upgrade,
    690 		 * then we want to fail rather than have an intervening
    691 		 * exclusive access.
    692 		 */
    693 		if (lkp->lk_flags & LK_WANT_UPGRADE) {
    694 			lkp->lk_sharecount--;
    695 			if (lkp->lk_sharecount == 0)
    696 				lkp->lk_flags &= ~LK_SHARE_NONZERO;
    697 			COUNT(lkp, l, cpu_num, -1);
    698 			error = EBUSY;
    699 			break;
    700 		}
    701 		/* fall into normal upgrade */
    702 
    703 	case LK_UPGRADE:
    704 		/*
    705 		 * Upgrade a shared lock to an exclusive one. If another
    706 		 * shared lock has already requested an upgrade to an
    707 		 * exclusive lock, our shared lock is released and an
    708 		 * exclusive lock is requested (which will be granted
    709 		 * after the upgrade). If we return an error, the file
    710 		 * will always be unlocked.
    711 		 */
    712 		if (WEHOLDIT(lkp, pid, lid, cpu_num) || lkp->lk_sharecount <= 0)
    713 			panic("lockmgr: upgrade exclusive lock");
    714 		lkp->lk_sharecount--;
    715 		if (lkp->lk_sharecount == 0)
    716 			lkp->lk_flags &= ~LK_SHARE_NONZERO;
    717 		COUNT(lkp, l, cpu_num, -1);
    718 		/*
    719 		 * If we are just polling, check to see if we will block.
    720 		 */
    721 		if ((extflags & LK_NOWAIT) &&
    722 		    ((lkp->lk_flags & LK_WANT_UPGRADE) ||
    723 		     lkp->lk_sharecount > 1)) {
    724 			error = EBUSY;
    725 			break;
    726 		}
    727 		if ((lkp->lk_flags & LK_WANT_UPGRADE) == 0) {
    728 			/*
    729 			 * We are first shared lock to request an upgrade, so
    730 			 * request upgrade and wait for the shared count to
    731 			 * drop to zero, then take exclusive lock.
    732 			 */
    733 			lkp->lk_flags |= LK_WANT_UPGRADE;
    734 			error = acquire(&lkp, &s, extflags, 0, LK_SHARE_NONZERO,
    735 			    RETURN_ADDRESS);
    736 			lkp->lk_flags &= ~LK_WANT_UPGRADE;
    737 			if (error) {
    738 				WAKEUP_WAITER(lkp);
    739 				break;
    740 			}
    741 			lkp->lk_flags |= LK_HAVE_EXCL;
    742 			SETHOLDER(lkp, pid, lid, cpu_num);
    743 #if defined(LOCKDEBUG)
    744 			lkp->lk_lock_file = file;
    745 			lkp->lk_lock_line = line;
    746 #endif
    747 			HAVEIT(lkp);
    748 			if (lkp->lk_exclusivecount != 0)
    749 				panic("lockmgr: non-zero exclusive count");
    750 			lkp->lk_exclusivecount = 1;
    751 			if (extflags & LK_SETRECURSE)
    752 				lkp->lk_recurselevel = 1;
    753 			COUNT(lkp, l, cpu_num, 1);
    754 			break;
    755 		}
    756 		/*
    757 		 * Someone else has requested upgrade. Release our shared
    758 		 * lock, awaken upgrade requestor if we are the last shared
    759 		 * lock, then request an exclusive lock.
    760 		 */
    761 		if (lkp->lk_sharecount == 0)
    762 			WAKEUP_WAITER(lkp);
    763 		/* fall into exclusive request */
    764 
    765 	case LK_EXCLUSIVE:
    766 		if (WEHOLDIT(lkp, pid, lid, cpu_num)) {
    767 			/*
    768 			 * Recursive lock.
    769 			 */
    770 			if ((extflags & LK_CANRECURSE) == 0 &&
    771 			     lkp->lk_recurselevel == 0) {
    772 				if (extflags & LK_RECURSEFAIL) {
    773 					error = EDEADLK;
    774 					break;
    775 				} else
    776 					panic("lockmgr: locking against myself");
    777 			}
    778 			lkp->lk_exclusivecount++;
    779 			if (extflags & LK_SETRECURSE &&
    780 			    lkp->lk_recurselevel == 0)
    781 				lkp->lk_recurselevel = lkp->lk_exclusivecount;
    782 			COUNT(lkp, l, cpu_num, 1);
    783 			break;
    784 		}
    785 		/*
    786 		 * If we are just polling, check to see if we will sleep.
    787 		 */
    788 		if ((extflags & LK_NOWAIT) && (lkp->lk_flags &
    789 		     (LK_HAVE_EXCL | LK_WANT_EXCL | LK_WANT_UPGRADE |
    790 		     LK_SHARE_NONZERO))) {
    791 			error = EBUSY;
    792 			break;
    793 		}
    794 		/*
    795 		 * Try to acquire the want_exclusive flag.
    796 		 */
    797 		error = acquire(&lkp, &s, extflags, 0,
    798 		    LK_HAVE_EXCL | LK_WANT_EXCL, RETURN_ADDRESS);
    799 		if (error)
    800 			break;
    801 		lkp->lk_flags |= LK_WANT_EXCL;
    802 		/*
    803 		 * Wait for shared locks and upgrades to finish.
    804 		 */
    805 		error = acquire(&lkp, &s, extflags, 0,
    806 		    LK_HAVE_EXCL | LK_WANT_UPGRADE | LK_SHARE_NONZERO,
    807 		    RETURN_ADDRESS);
    808 		lkp->lk_flags &= ~LK_WANT_EXCL;
    809 		if (error) {
    810 			WAKEUP_WAITER(lkp);
    811 			break;
    812 		}
    813 		lkp->lk_flags |= LK_HAVE_EXCL;
    814 		SETHOLDER(lkp, pid, lid, cpu_num);
    815 #if defined(LOCKDEBUG)
    816 		lkp->lk_lock_file = file;
    817 		lkp->lk_lock_line = line;
    818 #endif
    819 		HAVEIT(lkp);
    820 		if (lkp->lk_exclusivecount != 0)
    821 			panic("lockmgr: non-zero exclusive count");
    822 		lkp->lk_exclusivecount = 1;
    823 		if (extflags & LK_SETRECURSE)
    824 			lkp->lk_recurselevel = 1;
    825 		COUNT(lkp, l, cpu_num, 1);
    826 		break;
    827 
    828 	case LK_RELEASE:
    829 		if (lkp->lk_exclusivecount != 0) {
    830 			if (WEHOLDIT(lkp, pid, lid, cpu_num) == 0) {
    831 				if (lkp->lk_flags & LK_SPIN) {
    832 					panic("lockmgr: processor %lu, not "
    833 					    "exclusive lock holder %lu "
    834 					    "unlocking", cpu_num, lkp->lk_cpu);
    835 				} else {
    836 					panic("lockmgr: pid %d, not "
    837 					    "exclusive lock holder %d "
    838 					    "unlocking", pid,
    839 					    lkp->lk_lockholder);
    840 				}
    841 			}
    842 			if (lkp->lk_exclusivecount == lkp->lk_recurselevel)
    843 				lkp->lk_recurselevel = 0;
    844 			lkp->lk_exclusivecount--;
    845 			COUNT(lkp, l, cpu_num, -1);
    846 			if (lkp->lk_exclusivecount == 0) {
    847 				lkp->lk_flags &= ~LK_HAVE_EXCL;
    848 				SETHOLDER(lkp, LK_NOPROC, 0, LK_NOCPU);
    849 #if defined(LOCKDEBUG)
    850 				lkp->lk_unlock_file = file;
    851 				lkp->lk_unlock_line = line;
    852 #endif
    853 				DONTHAVEIT(lkp);
    854 			}
    855 		} else if (lkp->lk_sharecount != 0) {
    856 			lkp->lk_sharecount--;
    857 			if (lkp->lk_sharecount == 0)
    858 				lkp->lk_flags &= ~LK_SHARE_NONZERO;
    859 			COUNT(lkp, l, cpu_num, -1);
    860 		}
    861 #ifdef DIAGNOSTIC
    862 		else
    863 			panic("lockmgr: release of unlocked lock!");
    864 #endif
    865 		WAKEUP_WAITER(lkp);
    866 		break;
    867 
    868 	case LK_DRAIN:
    869 		/*
    870 		 * Check that we do not already hold the lock, as it can
    871 		 * never drain if we do. Unfortunately, we have no way to
    872 		 * check for holding a shared lock, but at least we can
    873 		 * check for an exclusive one.
    874 		 */
    875 		if (WEHOLDIT(lkp, pid, lid, cpu_num))
    876 			panic("lockmgr: draining against myself");
    877 		/*
    878 		 * If we are just polling, check to see if we will sleep.
    879 		 */
    880 		if ((extflags & LK_NOWAIT) && (lkp->lk_flags &
    881 		     (LK_HAVE_EXCL | LK_WANT_EXCL | LK_WANT_UPGRADE |
    882 		     LK_SHARE_NONZERO | LK_WAIT_NONZERO))) {
    883 			error = EBUSY;
    884 			break;
    885 		}
    886 		error = acquire(&lkp, &s, extflags, 1,
    887 		    LK_HAVE_EXCL | LK_WANT_EXCL | LK_WANT_UPGRADE |
    888 		    LK_SHARE_NONZERO | LK_WAIT_NONZERO,
    889 		    RETURN_ADDRESS);
    890 		if (error)
    891 			break;
    892 		lkp->lk_flags |= LK_DRAINING | LK_HAVE_EXCL;
    893 		SETHOLDER(lkp, pid, lid, cpu_num);
    894 #if defined(LOCKDEBUG)
    895 		lkp->lk_lock_file = file;
    896 		lkp->lk_lock_line = line;
    897 #endif
    898 		HAVEIT(lkp);
    899 		lkp->lk_exclusivecount = 1;
    900 		/* XXX unlikely that we'd want this */
    901 		if (extflags & LK_SETRECURSE)
    902 			lkp->lk_recurselevel = 1;
    903 		COUNT(lkp, l, cpu_num, 1);
    904 		break;
    905 
    906 	default:
    907 		INTERLOCK_RELEASE(lkp, lkp->lk_flags, s);
    908 		panic("lockmgr: unknown locktype request %d",
    909 		    flags & LK_TYPE_MASK);
    910 		/* NOTREACHED */
    911 	}
    912 	if ((lkp->lk_flags & (LK_WAITDRAIN|LK_SPIN)) == LK_WAITDRAIN &&
    913 	    ((lkp->lk_flags &
    914 	      (LK_HAVE_EXCL | LK_WANT_EXCL | LK_WANT_UPGRADE |
    915 	      LK_SHARE_NONZERO | LK_WAIT_NONZERO)) == 0)) {
    916 		lkp->lk_flags &= ~LK_WAITDRAIN;
    917 		wakeup(&lkp->lk_flags);
    918 	}
    919 	/*
    920 	 * Note that this panic will be a recursive panic, since
    921 	 * we only set lock_shutdown_noblock above if panicstr != NULL.
    922 	 */
    923 	if (error && lock_shutdown_noblock)
    924 		panic("lockmgr: deadlock (see previous panic)");
    925 
    926 	INTERLOCK_RELEASE(lkp, lkp->lk_flags, s);
    927 	return (error);
    928 }
    929 
    930 /*
    931  * For a recursive spinlock held one or more times by the current CPU,
    932  * release all N locks, and return N.
    933  * Intended for use in mi_switch() shortly before context switching.
    934  */
    935 
    936 int
    937 #if defined(LOCKDEBUG)
    938 _spinlock_release_all(volatile struct lock *lkp, const char *file, int line)
    939 #else
    940 spinlock_release_all(volatile struct lock *lkp)
    941 #endif
    942 {
    943 	int s, count;
    944 	cpuid_t cpu_num;
    945 
    946 	KASSERT(lkp->lk_flags & LK_SPIN);
    947 
    948 	INTERLOCK_ACQUIRE(lkp, LK_SPIN, s);
    949 
    950 	cpu_num = cpu_number();
    951 	count = lkp->lk_exclusivecount;
    952 
    953 	if (count != 0) {
    954 #ifdef DIAGNOSTIC
    955 		if (WEHOLDIT(lkp, 0, 0, cpu_num) == 0) {
    956 			panic("spinlock_release_all: processor %lu, not "
    957 			    "exclusive lock holder %lu "
    958 			    "unlocking", (long)cpu_num, lkp->lk_cpu);
    959 		}
    960 #endif
    961 		lkp->lk_recurselevel = 0;
    962 		lkp->lk_exclusivecount = 0;
    963 		COUNT_CPU(cpu_num, -count);
    964 		lkp->lk_flags &= ~LK_HAVE_EXCL;
    965 		SETHOLDER(lkp, LK_NOPROC, 0, LK_NOCPU);
    966 #if defined(LOCKDEBUG)
    967 		lkp->lk_unlock_file = file;
    968 		lkp->lk_unlock_line = line;
    969 #endif
    970 		DONTHAVEIT(lkp);
    971 	}
    972 #ifdef DIAGNOSTIC
    973 	else if (lkp->lk_sharecount != 0)
    974 		panic("spinlock_release_all: release of shared lock!");
    975 	else
    976 		panic("spinlock_release_all: release of unlocked lock!");
    977 #endif
    978 	INTERLOCK_RELEASE(lkp, LK_SPIN, s);
    979 
    980 	return (count);
    981 }
    982 
    983 /*
    984  * For a recursive spinlock held one or more times by the current CPU,
    985  * release all N locks, and return N.
    986  * Intended for use in mi_switch() right after resuming execution.
    987  */
    988 
    989 void
    990 #if defined(LOCKDEBUG)
    991 _spinlock_acquire_count(volatile struct lock *lkp, int count,
    992     const char *file, int line)
    993 #else
    994 spinlock_acquire_count(volatile struct lock *lkp, int count)
    995 #endif
    996 {
    997 	int s, error;
    998 	cpuid_t cpu_num;
    999 
   1000 	KASSERT(lkp->lk_flags & LK_SPIN);
   1001 
   1002 	INTERLOCK_ACQUIRE(lkp, LK_SPIN, s);
   1003 
   1004 	cpu_num = cpu_number();
   1005 
   1006 #ifdef DIAGNOSTIC
   1007 	if (WEHOLDIT(lkp, LK_NOPROC, 0, cpu_num))
   1008 		panic("spinlock_acquire_count: processor %lu already holds lock", (long)cpu_num);
   1009 #endif
   1010 	/*
   1011 	 * Try to acquire the want_exclusive flag.
   1012 	 */
   1013 	error = acquire(&lkp, &s, LK_SPIN, 0, LK_HAVE_EXCL | LK_WANT_EXCL,
   1014 	    RETURN_ADDRESS);
   1015 	lkp->lk_flags |= LK_WANT_EXCL;
   1016 	/*
   1017 	 * Wait for shared locks and upgrades to finish.
   1018 	 */
   1019 	error = acquire(&lkp, &s, LK_SPIN, 0,
   1020 	    LK_HAVE_EXCL | LK_SHARE_NONZERO | LK_WANT_UPGRADE,
   1021 	    RETURN_ADDRESS);
   1022 	lkp->lk_flags &= ~LK_WANT_EXCL;
   1023 	lkp->lk_flags |= LK_HAVE_EXCL;
   1024 	SETHOLDER(lkp, LK_NOPROC, 0, cpu_num);
   1025 #if defined(LOCKDEBUG)
   1026 	lkp->lk_lock_file = file;
   1027 	lkp->lk_lock_line = line;
   1028 #endif
   1029 	HAVEIT(lkp);
   1030 	if (lkp->lk_exclusivecount != 0)
   1031 		panic("lockmgr: non-zero exclusive count");
   1032 	lkp->lk_exclusivecount = count;
   1033 	lkp->lk_recurselevel = 1;
   1034 	COUNT_CPU(cpu_num, count);
   1035 
   1036 	INTERLOCK_RELEASE(lkp, lkp->lk_flags, s);
   1037 }
   1038 
   1039 
   1040 
   1041 /*
   1042  * Print out information about state of a lock. Used by VOP_PRINT
   1043  * routines to display ststus about contained locks.
   1044  */
   1045 void
   1046 lockmgr_printinfo(volatile struct lock *lkp)
   1047 {
   1048 
   1049 	if (lkp->lk_sharecount)
   1050 		printf(" lock type %s: SHARED (count %d)", lkp->lk_wmesg,
   1051 		    lkp->lk_sharecount);
   1052 	else if (lkp->lk_flags & LK_HAVE_EXCL) {
   1053 		printf(" lock type %s: EXCL (count %d) by ",
   1054 		    lkp->lk_wmesg, lkp->lk_exclusivecount);
   1055 		if (lkp->lk_flags & LK_SPIN)
   1056 			printf("processor %lu", lkp->lk_cpu);
   1057 		else
   1058 			printf("pid %d.%d", lkp->lk_lockholder,
   1059 			    lkp->lk_locklwp);
   1060 	} else
   1061 		printf(" not locked");
   1062 	if ((lkp->lk_flags & LK_SPIN) == 0 && lkp->lk_waitcount > 0)
   1063 		printf(" with %d pending", lkp->lk_waitcount);
   1064 }
   1065 
   1066 #if defined(LOCKDEBUG) /* { */
   1067 _TAILQ_HEAD(, struct simplelock, volatile) simplelock_list =
   1068     TAILQ_HEAD_INITIALIZER(simplelock_list);
   1069 
   1070 #if defined(MULTIPROCESSOR) /* { */
   1071 struct simplelock simplelock_list_slock = SIMPLELOCK_INITIALIZER;
   1072 
   1073 #define	SLOCK_LIST_LOCK()						\
   1074 	__cpu_simple_lock(&simplelock_list_slock.lock_data)
   1075 
   1076 #define	SLOCK_LIST_UNLOCK()						\
   1077 	__cpu_simple_unlock(&simplelock_list_slock.lock_data)
   1078 
   1079 #define	SLOCK_COUNT(x)							\
   1080 	curcpu()->ci_simple_locks += (x)
   1081 #else
   1082 u_long simple_locks;
   1083 
   1084 #define	SLOCK_LIST_LOCK()	/* nothing */
   1085 
   1086 #define	SLOCK_LIST_UNLOCK()	/* nothing */
   1087 
   1088 #define	SLOCK_COUNT(x)		simple_locks += (x)
   1089 #endif /* MULTIPROCESSOR */ /* } */
   1090 
   1091 #ifdef MULTIPROCESSOR
   1092 #define SLOCK_MP()		lock_printf("on CPU %ld\n", 		\
   1093 				    (u_long) cpu_number())
   1094 #else
   1095 #define SLOCK_MP()		/* nothing */
   1096 #endif
   1097 
   1098 #define	SLOCK_WHERE(str, alp, id, l)					\
   1099 do {									\
   1100 	lock_printf("\n");						\
   1101 	lock_printf(str);						\
   1102 	lock_printf("lock: %p, currently at: %s:%d\n", (alp), (id), (l)); \
   1103 	SLOCK_MP();							\
   1104 	if ((alp)->lock_file != NULL)					\
   1105 		lock_printf("last locked: %s:%d\n", (alp)->lock_file,	\
   1106 		    (alp)->lock_line);					\
   1107 	if ((alp)->unlock_file != NULL)					\
   1108 		lock_printf("last unlocked: %s:%d\n", (alp)->unlock_file, \
   1109 		    (alp)->unlock_line);				\
   1110 	SLOCK_TRACE()							\
   1111 	SLOCK_DEBUGGER();						\
   1112 } while (/*CONSTCOND*/0)
   1113 
   1114 /*
   1115  * Simple lock functions so that the debugger can see from whence
   1116  * they are being called.
   1117  */
   1118 void
   1119 simple_lock_init(volatile struct simplelock *alp)
   1120 {
   1121 
   1122 #if defined(MULTIPROCESSOR) /* { */
   1123 	__cpu_simple_lock_init(&alp->lock_data);
   1124 #else
   1125 	alp->lock_data = __SIMPLELOCK_UNLOCKED;
   1126 #endif /* } */
   1127 	alp->lock_file = NULL;
   1128 	alp->lock_line = 0;
   1129 	alp->unlock_file = NULL;
   1130 	alp->unlock_line = 0;
   1131 	alp->lock_holder = LK_NOCPU;
   1132 }
   1133 
   1134 void
   1135 _simple_lock(volatile struct simplelock *alp, const char *id, int l)
   1136 {
   1137 	cpuid_t cpu_num = cpu_number();
   1138 	int s;
   1139 
   1140 	s = spllock();
   1141 
   1142 	/*
   1143 	 * MULTIPROCESSOR case: This is `safe' since if it's not us, we
   1144 	 * don't take any action, and just fall into the normal spin case.
   1145 	 */
   1146 	if (alp->lock_data == __SIMPLELOCK_LOCKED) {
   1147 #if defined(MULTIPROCESSOR) /* { */
   1148 		if (alp->lock_holder == cpu_num) {
   1149 			SLOCK_WHERE("simple_lock: locking against myself\n",
   1150 			    alp, id, l);
   1151 			goto out;
   1152 		}
   1153 #else
   1154 		SLOCK_WHERE("simple_lock: lock held\n", alp, id, l);
   1155 		goto out;
   1156 #endif /* MULTIPROCESSOR */ /* } */
   1157 	}
   1158 
   1159 #if defined(MULTIPROCESSOR) /* { */
   1160 	/* Acquire the lock before modifying any fields. */
   1161 	splx(s);
   1162 	__cpu_simple_lock(&alp->lock_data);
   1163 	s = spllock();
   1164 #else
   1165 	alp->lock_data = __SIMPLELOCK_LOCKED;
   1166 #endif /* } */
   1167 
   1168 	if (alp->lock_holder != LK_NOCPU) {
   1169 		SLOCK_WHERE("simple_lock: uninitialized lock\n",
   1170 		    alp, id, l);
   1171 	}
   1172 	alp->lock_file = id;
   1173 	alp->lock_line = l;
   1174 	alp->lock_holder = cpu_num;
   1175 
   1176 	SLOCK_LIST_LOCK();
   1177 	TAILQ_INSERT_TAIL(&simplelock_list, alp, list);
   1178 	SLOCK_LIST_UNLOCK();
   1179 
   1180 	SLOCK_COUNT(1);
   1181 
   1182  out:
   1183 	splx(s);
   1184 }
   1185 
   1186 int
   1187 _simple_lock_held(volatile struct simplelock *alp)
   1188 {
   1189 #if defined(MULTIPROCESSOR) || defined(DIAGNOSTIC)
   1190 	cpuid_t cpu_num = cpu_number();
   1191 #endif
   1192 	int s, locked = 0;
   1193 
   1194 	s = spllock();
   1195 
   1196 #if defined(MULTIPROCESSOR)
   1197 	if (__cpu_simple_lock_try(&alp->lock_data) == 0)
   1198 		locked = (alp->lock_holder == cpu_num);
   1199 	else
   1200 		__cpu_simple_unlock(&alp->lock_data);
   1201 #else
   1202 	if (alp->lock_data == __SIMPLELOCK_LOCKED) {
   1203 		locked = 1;
   1204 		KASSERT(alp->lock_holder == cpu_num);
   1205 	}
   1206 #endif
   1207 
   1208 	splx(s);
   1209 
   1210 	return (locked);
   1211 }
   1212 
   1213 int
   1214 _simple_lock_try(volatile struct simplelock *alp, const char *id, int l)
   1215 {
   1216 	cpuid_t cpu_num = cpu_number();
   1217 	int s, rv = 0;
   1218 
   1219 	s = spllock();
   1220 
   1221 	/*
   1222 	 * MULTIPROCESSOR case: This is `safe' since if it's not us, we
   1223 	 * don't take any action.
   1224 	 */
   1225 #if defined(MULTIPROCESSOR) /* { */
   1226 	if ((rv = __cpu_simple_lock_try(&alp->lock_data)) == 0) {
   1227 		if (alp->lock_holder == cpu_num)
   1228 			SLOCK_WHERE("simple_lock_try: locking against myself\n",
   1229 			    alp, id, l);
   1230 		goto out;
   1231 	}
   1232 #else
   1233 	if (alp->lock_data == __SIMPLELOCK_LOCKED) {
   1234 		SLOCK_WHERE("simple_lock_try: lock held\n", alp, id, l);
   1235 		goto out;
   1236 	}
   1237 	alp->lock_data = __SIMPLELOCK_LOCKED;
   1238 #endif /* MULTIPROCESSOR */ /* } */
   1239 
   1240 	/*
   1241 	 * At this point, we have acquired the lock.
   1242 	 */
   1243 
   1244 	rv = 1;
   1245 
   1246 	alp->lock_file = id;
   1247 	alp->lock_line = l;
   1248 	alp->lock_holder = cpu_num;
   1249 
   1250 	SLOCK_LIST_LOCK();
   1251 	TAILQ_INSERT_TAIL(&simplelock_list, alp, list);
   1252 	SLOCK_LIST_UNLOCK();
   1253 
   1254 	SLOCK_COUNT(1);
   1255 
   1256  out:
   1257 	splx(s);
   1258 	return (rv);
   1259 }
   1260 
   1261 void
   1262 _simple_unlock(volatile struct simplelock *alp, const char *id, int l)
   1263 {
   1264 	int s;
   1265 
   1266 	s = spllock();
   1267 
   1268 	/*
   1269 	 * MULTIPROCESSOR case: This is `safe' because we think we hold
   1270 	 * the lock, and if we don't, we don't take any action.
   1271 	 */
   1272 	if (alp->lock_data == __SIMPLELOCK_UNLOCKED) {
   1273 		SLOCK_WHERE("simple_unlock: lock not held\n",
   1274 		    alp, id, l);
   1275 		goto out;
   1276 	}
   1277 
   1278 	SLOCK_LIST_LOCK();
   1279 	TAILQ_REMOVE(&simplelock_list, alp, list);
   1280 	SLOCK_LIST_UNLOCK();
   1281 
   1282 	SLOCK_COUNT(-1);
   1283 
   1284 	alp->list.tqe_next = NULL;	/* sanity */
   1285 	alp->list.tqe_prev = NULL;	/* sanity */
   1286 
   1287 	alp->unlock_file = id;
   1288 	alp->unlock_line = l;
   1289 
   1290 #if defined(MULTIPROCESSOR) /* { */
   1291 	alp->lock_holder = LK_NOCPU;
   1292 	/* Now that we've modified all fields, release the lock. */
   1293 	__cpu_simple_unlock(&alp->lock_data);
   1294 #else
   1295 	alp->lock_data = __SIMPLELOCK_UNLOCKED;
   1296 	KASSERT(alp->lock_holder == cpu_number());
   1297 	alp->lock_holder = LK_NOCPU;
   1298 #endif /* } */
   1299 
   1300  out:
   1301 	splx(s);
   1302 }
   1303 
   1304 void
   1305 simple_lock_dump(void)
   1306 {
   1307 	volatile struct simplelock *alp;
   1308 	int s;
   1309 
   1310 	s = spllock();
   1311 	SLOCK_LIST_LOCK();
   1312 	lock_printf("all simple locks:\n");
   1313 	TAILQ_FOREACH(alp, &simplelock_list, list) {
   1314 		lock_printf("%p CPU %lu %s:%d\n", alp, alp->lock_holder,
   1315 		    alp->lock_file, alp->lock_line);
   1316 	}
   1317 	SLOCK_LIST_UNLOCK();
   1318 	splx(s);
   1319 }
   1320 
   1321 void
   1322 simple_lock_freecheck(void *start, void *end)
   1323 {
   1324 	volatile struct simplelock *alp;
   1325 	int s;
   1326 
   1327 	s = spllock();
   1328 	SLOCK_LIST_LOCK();
   1329 	TAILQ_FOREACH(alp, &simplelock_list, list) {
   1330 		if ((volatile void *)alp >= start &&
   1331 		    (volatile void *)alp < end) {
   1332 			lock_printf("freeing simple_lock %p CPU %lu %s:%d\n",
   1333 			    alp, alp->lock_holder, alp->lock_file,
   1334 			    alp->lock_line);
   1335 			SLOCK_DEBUGGER();
   1336 		}
   1337 	}
   1338 	SLOCK_LIST_UNLOCK();
   1339 	splx(s);
   1340 }
   1341 
   1342 /*
   1343  * We must be holding exactly one lock: the sched_lock.
   1344  */
   1345 
   1346 void
   1347 simple_lock_switchcheck(void)
   1348 {
   1349 
   1350 	simple_lock_only_held(NULL, "switching");
   1351 }
   1352 
   1353 /*
   1354  * Drop into the debugger if lp isn't the only lock held.
   1355  * lp may be NULL.
   1356  */
   1357 void
   1358 simple_lock_only_held(volatile struct simplelock *lp, const char *where)
   1359 {
   1360 	volatile struct simplelock *alp;
   1361 	cpuid_t cpu_num = cpu_number();
   1362 	int s;
   1363 
   1364 	if (lp) {
   1365 		LOCK_ASSERT(simple_lock_held(lp));
   1366 	}
   1367 	s = spllock();
   1368 	SLOCK_LIST_LOCK();
   1369 	TAILQ_FOREACH(alp, &simplelock_list, list) {
   1370 		if (alp == lp)
   1371 			continue;
   1372 		if (alp->lock_holder == cpu_num)
   1373 			break;
   1374 	}
   1375 	SLOCK_LIST_UNLOCK();
   1376 	splx(s);
   1377 
   1378 	if (alp != NULL) {
   1379 		lock_printf("\n%s with held simple_lock %p "
   1380 		    "CPU %lu %s:%d\n",
   1381 		    where, alp, alp->lock_holder, alp->lock_file,
   1382 		    alp->lock_line);
   1383 		SLOCK_TRACE();
   1384 		SLOCK_DEBUGGER();
   1385 	}
   1386 }
   1387 
   1388 /*
   1389  * Set to 1 by simple_lock_assert_*().
   1390  * Can be cleared from ddb to avoid a panic.
   1391  */
   1392 int slock_assert_will_panic;
   1393 
   1394 /*
   1395  * If the lock isn't held, print a traceback, optionally drop into the
   1396  *  debugger, then panic.
   1397  * The panic can be avoided by clearing slock_assert_with_panic from the
   1398  *  debugger.
   1399  */
   1400 void
   1401 _simple_lock_assert_locked(volatile struct simplelock *alp,
   1402     const char *lockname, const char *id, int l)
   1403 {
   1404 	if (simple_lock_held(alp) == 0) {
   1405 		slock_assert_will_panic = 1;
   1406 		lock_printf("%s lock not held\n", lockname);
   1407 		SLOCK_WHERE("lock not held", alp, id, l);
   1408 		if (slock_assert_will_panic)
   1409 			panic("%s: not locked", lockname);
   1410 	}
   1411 }
   1412 
   1413 void
   1414 _simple_lock_assert_unlocked(volatile struct simplelock *alp,
   1415     const char *lockname, const char *id, int l)
   1416 {
   1417 	if (simple_lock_held(alp)) {
   1418 		slock_assert_will_panic = 1;
   1419 		lock_printf("%s lock held\n", lockname);
   1420 		SLOCK_WHERE("lock held", alp, id, l);
   1421 		if (slock_assert_will_panic)
   1422 			panic("%s: locked", lockname);
   1423 	}
   1424 }
   1425 
   1426 void
   1427 assert_sleepable(struct simplelock *interlock, const char *msg)
   1428 {
   1429 
   1430 	if (curlwp == NULL) {
   1431 		panic("assert_sleepable: NULL curlwp");
   1432 	}
   1433 	simple_lock_only_held(interlock, msg);
   1434 }
   1435 
   1436 #endif /* LOCKDEBUG */ /* } */
   1437 
   1438 #if defined(MULTIPROCESSOR)
   1439 /*
   1440  * Functions for manipulating the kernel_lock.  We put them here
   1441  * so that they show up in profiles.
   1442  */
   1443 
   1444 
   1445 void
   1446 _kernel_lock_init(void)
   1447 {
   1448 
   1449 	mutex_init(&kernel_mutex, MUTEX_SPIN, IPL_BIGLOCK);
   1450 }
   1451 
   1452 /*
   1453  * Acquire/release the kernel lock.  Intended for use in the scheduler
   1454  * and the lower half of the kernel.
   1455  */
   1456 void
   1457 _kernel_lock(int flag)
   1458 {
   1459 	struct cpu_info *ci = curcpu();
   1460 
   1461 	if (ci->ci_data.cpu_biglock_count > 0) {
   1462 		LOCK_ASSERT(mutex_owned(&kernel_mutex));
   1463 		ci->ci_data.cpu_biglock_count++;
   1464 	} else {
   1465 		mutex_enter(&kernel_mutex);
   1466 		ci->ci_data.cpu_biglock_count++;
   1467 		splx(mutex_getspl(&kernel_mutex));
   1468 	}
   1469 }
   1470 
   1471 void
   1472 _kernel_unlock(void)
   1473 {
   1474 	struct cpu_info *ci = curcpu();
   1475 	int s;
   1476 
   1477 	KASSERT(ci->ci_data.cpu_biglock_count > 0);
   1478 
   1479 	s = splraiseipl(kernel_mutex.mtx_minspl);
   1480 	if ((--ci->ci_data.cpu_biglock_count) == 0) {
   1481 		mutex_setspl(&kernel_mutex, s);
   1482 		mutex_exit(&kernel_mutex);
   1483 	} else
   1484 		splx(s);
   1485 }
   1486 
   1487 /*
   1488  * Acquire/release the kernel_lock on behalf of a process.  Intended for
   1489  * use in the top half of the kernel.
   1490  */
   1491 void
   1492 _kernel_proc_lock(struct lwp *l)
   1493 {
   1494 
   1495 	LOCKDEBUG_BARRIER(&kernel_mutex, 0);
   1496 	_kernel_lock(0);
   1497 }
   1498 
   1499 void
   1500 _kernel_proc_unlock(struct lwp *l)
   1501 {
   1502 
   1503 	_kernel_unlock();
   1504 }
   1505 
   1506 int
   1507 _kernel_lock_release_all()
   1508 {
   1509 	struct cpu_info *ci = curcpu();
   1510 	int hold_count;
   1511 
   1512 	hold_count = ci->ci_data.cpu_biglock_count;
   1513 
   1514 	if (hold_count) {
   1515 		mutex_setspl(&kernel_mutex, splraiseipl(kernel_mutex.mtx_minspl));
   1516 		ci->ci_data.cpu_biglock_count = 0;
   1517 		mutex_exit(&kernel_mutex);
   1518 	}
   1519 
   1520 	return hold_count;
   1521 }
   1522 
   1523 void
   1524 _kernel_lock_acquire_count(int hold_count)
   1525 {
   1526 
   1527 	KASSERT(curcpu()->ci_data.cpu_biglock_count == 0);
   1528 
   1529 	if (hold_count != 0) {
   1530 		struct cpu_info *ci = curcpu();
   1531 
   1532 		mutex_enter(&kernel_mutex);
   1533 		ci->ci_data.cpu_biglock_count = hold_count;
   1534 		splx(mutex_getspl(&kernel_mutex));
   1535 	}
   1536 }
   1537 #if defined(DEBUG)
   1538 void
   1539 _kernel_lock_assert_locked()
   1540 {
   1541 
   1542 	LOCK_ASSERT(mutex_owned(&kernel_mutex));
   1543 }
   1544 #endif
   1545 
   1546 int
   1547 lock_owner_onproc(uintptr_t owner)
   1548 {
   1549 	CPU_INFO_ITERATOR cii;
   1550 	struct cpu_info *ci;
   1551 
   1552 	for (CPU_INFO_FOREACH(cii, ci))
   1553 		if (owner == (uintptr_t)ci || owner == (uintptr_t)ci->ci_curlwp)
   1554 			return (1);
   1555 
   1556 	return (0);
   1557 }
   1558 
   1559 #else	/* MULTIPROCESSOR */
   1560 
   1561 int
   1562 lock_owner_onproc(uintptr_t owner)
   1563 {
   1564 
   1565 	return 0;
   1566 }
   1567 
   1568 #endif /* MULTIPROCESSOR */
   1569