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