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