Home | History | Annotate | Line # | Download | only in kern
kern_lock.c revision 1.110.2.13
      1 /*	$NetBSD: kern_lock.c,v 1.110.2.13 2007/10/10 21:21:21 ad Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1999, 2000, 2006, 2007 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
      9  * NASA Ames Research Center, 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.110.2.13 2007/10/10 21:21:21 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 #include <machine/stdarg.h>
     94 
     95 #include <dev/lockstat.h>
     96 
     97 #if defined(LOCKDEBUG)
     98 #include <sys/syslog.h>
     99 /*
    100  * note that stdarg.h and the ansi style va_start macro is used for both
    101  * ansi and traditional c compiles.
    102  * XXX: this requires that stdarg.h define: va_alist and va_dcl
    103  */
    104 #include <machine/stdarg.h>
    105 
    106 void	lock_printf(const char *fmt, ...)
    107     __attribute__((__format__(__printf__,1,2)));
    108 
    109 static int acquire(volatile struct lock **, int *, int, int, int, uintptr_t);
    110 
    111 int	lock_debug_syslog = 0;	/* defaults to printf, but can be patched */
    112 
    113 #ifdef DDB
    114 #include <ddb/ddbvar.h>
    115 #include <machine/db_machdep.h>
    116 #include <ddb/db_command.h>
    117 #include <ddb/db_interface.h>
    118 #endif
    119 #endif /* defined(LOCKDEBUG) */
    120 
    121 #if defined(MULTIPROCESSOR)
    122 /*
    123  * IPL_BIGLOCK: block IPLs which need to grab kernel_mutex.
    124  * XXX IPL_VM or IPL_AUDIO should be enough.
    125  */
    126 #if !defined(__HAVE_SPLBIGLOCK)
    127 #define	splbiglock	splclock
    128 #endif
    129 int kernel_lock_id;
    130 #endif
    131 
    132 __cpu_simple_lock_t kernel_lock;
    133 
    134 /*
    135  * Locking primitives implementation.
    136  * Locks provide shared/exclusive synchronization.
    137  */
    138 
    139 #if defined(LOCKDEBUG) || defined(DIAGNOSTIC) /* { */
    140 #define	COUNT(lkp, l, cpu_id, x)	(l)->l_locks += (x)
    141 #else
    142 #define COUNT(lkp, p, cpu_id, x)
    143 #endif /* LOCKDEBUG || DIAGNOSTIC */ /* } */
    144 
    145 #define	RETURN_ADDRESS		((uintptr_t)__builtin_return_address(0))
    146 
    147 /*
    148  * Acquire a resource.
    149  */
    150 static int
    151 acquire(volatile struct lock **lkpp, int *s, int extflags,
    152     int drain, int wanted, uintptr_t ra)
    153 {
    154 	int error;
    155 	volatile struct lock *lkp = *lkpp;
    156 	LOCKSTAT_TIMER(slptime);
    157 	LOCKSTAT_FLAG(lsflag);
    158 
    159 	KASSERT(drain || (wanted & LK_WAIT_NONZERO) == 0);
    160 
    161 	LOCKSTAT_ENTER(lsflag);
    162 
    163 	for (error = 0; (lkp->lk_flags & wanted) != 0; ) {
    164 		if (drain)
    165 			lkp->lk_flags |= LK_WAITDRAIN;
    166 		else {
    167 			lkp->lk_waitcount++;
    168 			lkp->lk_flags |= LK_WAIT_NONZERO;
    169 		}
    170 		/* XXX Cast away volatile. */
    171 		LOCKSTAT_START_TIMER(lsflag, slptime);
    172 		error = mtsleep(drain ?
    173 		    (volatile const void *)&lkp->lk_flags :
    174 		    (volatile const void *)lkp, lkp->lk_prio,
    175 		    lkp->lk_wmesg, lkp->lk_timo,
    176 		    __UNVOLATILE(&lkp->lk_interlock));
    177 		LOCKSTAT_STOP_TIMER(lsflag, slptime);
    178 		LOCKSTAT_EVENT_RA(lsflag, (void *)(uintptr_t)lkp,
    179 		    LB_LOCKMGR | LB_SLEEP1, 1, slptime, ra);
    180 		if (!drain) {
    181 			lkp->lk_waitcount--;
    182 			if (lkp->lk_waitcount == 0)
    183 				lkp->lk_flags &= ~LK_WAIT_NONZERO;
    184 		}
    185 		if (error)
    186 			break;
    187 		if (extflags & LK_SLEEPFAIL) {
    188 			error = ENOLCK;
    189 			break;
    190 		}
    191 		if (lkp->lk_newlock != NULL) {
    192 			mutex_enter(__UNVOLATILE
    193 			    (&lkp->lk_newlock->lk_interlock));
    194 			mutex_exit(__UNVOLATILE
    195 			    (&lkp->lk_interlock));
    196 			if (lkp->lk_waitcount == 0)
    197 				wakeup(&lkp->lk_newlock);
    198 			*lkpp = lkp = lkp->lk_newlock;
    199 		}
    200 	}
    201 
    202 	LOCKSTAT_EXIT(lsflag);
    203 
    204 	return error;
    205 }
    206 
    207 #define	SETHOLDER(lkp, pid, lid, cpu_id)				\
    208 do {									\
    209 	(lkp)->lk_lockholder = pid;					\
    210 	(lkp)->lk_locklwp = lid;					\
    211 } while (/*CONSTCOND*/0)
    212 
    213 #define	WEHOLDIT(lkp, pid, lid, cpu_id)					\
    214 	 ((lkp)->lk_lockholder == (pid) && (lkp)->lk_locklwp == (lid))
    215 
    216 #define	WAKEUP_WAITER(lkp)						\
    217 do {									\
    218 	if (((lkp)->lk_flags & LK_WAIT_NONZERO) != 0) {			\
    219 		wakeup((lkp));						\
    220 	}								\
    221 } while (/*CONSTCOND*/0)
    222 
    223 #if defined(LOCKDEBUG)
    224 /*
    225  * Lock debug printing routine; can be configured to print to console
    226  * or log to syslog.
    227  */
    228 void
    229 lock_printf(const char *fmt, ...)
    230 {
    231 	char b[150];
    232 	va_list ap;
    233 
    234 	va_start(ap, fmt);
    235 	if (lock_debug_syslog)
    236 		vlog(LOG_DEBUG, fmt, ap);
    237 	else {
    238 		vsnprintf(b, sizeof(b), fmt, ap);
    239 		printf_nolog("%s", b);
    240 	}
    241 	va_end(ap);
    242 }
    243 #endif /* LOCKDEBUG */
    244 
    245 static void
    246 lockpanic(volatile struct lock *lkp, const char *fmt, ...)
    247 {
    248 	char s[150], b[150];
    249 #ifdef LOCKDEBUG
    250 	static const char *locktype[] = {
    251 	    "*0*", "shared", "exclusive", "upgrade", "exclupgrade",
    252 	    "downgrade", "release", "drain", "exclother", "*9*",
    253 	    "*10*", "*11*", "*12*", "*13*", "*14*", "*15*"
    254 	};
    255 #endif
    256 	va_list ap;
    257 	va_start(ap, fmt);
    258 	vsnprintf(s, sizeof(s), fmt, ap);
    259 	va_end(ap);
    260 	bitmask_snprintf(lkp->lk_flags, __LK_FLAG_BITS, b, sizeof(b));
    261 	panic("%s ("
    262 #ifdef LOCKDEBUG
    263 	    "type %s "
    264 #endif
    265 	    "flags %s, sharecount %d, exclusivecount %d, "
    266 	    "recurselevel %d, waitcount %d, wmesg %s"
    267 	    ", lock_addr %p, unlock_addr %p"
    268 	    ")\n",
    269 	    s,
    270 #ifdef LOCKDEBUG
    271 	    locktype[lkp->lk_flags & LK_TYPE_MASK],
    272 #endif
    273 	    b, lkp->lk_sharecount, lkp->lk_exclusivecount,
    274 	    lkp->lk_recurselevel, lkp->lk_waitcount, lkp->lk_wmesg
    275 #ifdef LOCKDEBUG
    276 	    , (void *)lkp->lk_lock_addr, (void *)lkp->lk_unlock_addr
    277 #endif
    278 	);
    279 }
    280 
    281 /*
    282  * Transfer any waiting processes from one lock to another.
    283  */
    284 void
    285 transferlockers(struct lock *from, struct lock *to)
    286 {
    287 
    288 	KASSERT(from != to);
    289 	KASSERT((from->lk_flags & LK_WAITDRAIN) == 0);
    290 	if (from->lk_waitcount == 0)
    291 		return;
    292 	from->lk_newlock = to;
    293 	wakeup((void *)from);
    294 	tsleep((void *)&from->lk_newlock, from->lk_prio, "lkxfer", 0);
    295 	from->lk_newlock = NULL;
    296 	from->lk_flags &= ~(LK_WANT_EXCL | LK_WANT_UPGRADE);
    297 	KASSERT(from->lk_waitcount == 0);
    298 }
    299 
    300 
    301 /*
    302  * Initialize a lock; required before use.
    303  */
    304 void
    305 lockinit(struct lock *lkp, pri_t prio, const char *wmesg, int timo, int flags)
    306 {
    307 
    308 	memset(lkp, 0, sizeof(struct lock));
    309 	lkp->lk_flags = flags & LK_EXTFLG_MASK;
    310 	mutex_init(&lkp->lk_interlock, MUTEX_DEFAULT, IPL_NONE);
    311 	lkp->lk_lockholder = LK_NOPROC;
    312 	lkp->lk_newlock = NULL;
    313 	lkp->lk_prio = prio;
    314 	lkp->lk_timo = timo;
    315 	lkp->lk_wmesg = wmesg;
    316 	lkp->lk_lock_addr = 0;
    317 	lkp->lk_unlock_addr = 0;
    318 }
    319 
    320 void
    321 lockdestroy(struct lock *lkp)
    322 {
    323 
    324 	mutex_destroy(&lkp->lk_interlock);
    325 }
    326 
    327 /*
    328  * Determine the status of a lock.
    329  */
    330 int
    331 lockstatus(struct lock *lkp)
    332 {
    333 	int lock_type = 0;
    334 	struct lwp *l = curlwp; /* XXX */
    335 	pid_t pid;
    336 	lwpid_t lid;
    337 	cpuid_t cpu_num;
    338 
    339 	if (l == NULL) {
    340 		cpu_num = cpu_number();
    341 		pid = LK_KERNPROC;
    342 		lid = 0;
    343 	} else {
    344 		cpu_num = LK_NOCPU;
    345 		pid = l->l_proc->p_pid;
    346 		lid = l->l_lid;
    347 	}
    348 
    349 	mutex_enter(&lkp->lk_interlock);
    350 	if (lkp->lk_exclusivecount != 0) {
    351 		if (WEHOLDIT(lkp, pid, lid, cpu_num))
    352 			lock_type = LK_EXCLUSIVE;
    353 		else
    354 			lock_type = LK_EXCLOTHER;
    355 	} else if (lkp->lk_sharecount != 0)
    356 		lock_type = LK_SHARED;
    357 	else if (lkp->lk_flags & (LK_WANT_EXCL | LK_WANT_UPGRADE))
    358 		lock_type = LK_EXCLOTHER;
    359 	mutex_exit(__UNVOLATILE(&lkp->lk_interlock));
    360 	return (lock_type);
    361 }
    362 
    363 /*
    364  * XXX XXX kludge around another kludge..
    365  *
    366  * vfs_shutdown() may be called from interrupt context, either as a result
    367  * of a panic, or from the debugger.   It proceeds to call
    368  * sys_sync(&proc0, ...), pretending its running on behalf of proc0
    369  *
    370  * We would like to make an attempt to sync the filesystems in this case, so
    371  * if this happens, we treat attempts to acquire locks specially.
    372  * All locks are acquired on behalf of proc0.
    373  *
    374  * If we've already paniced, we don't block waiting for locks, but
    375  * just barge right ahead since we're already going down in flames.
    376  */
    377 
    378 /*
    379  * Set, change, or release a lock.
    380  *
    381  * Shared requests increment the shared count. Exclusive requests set the
    382  * LK_WANT_EXCL flag (preventing further shared locks), and wait for already
    383  * accepted shared locks and shared-to-exclusive upgrades to go away.
    384  */
    385 int
    386 lockmgr(volatile struct lock *lkp, u_int flags,
    387     kmutex_t *interlkp)
    388 {
    389 	int error;
    390 	pid_t pid;
    391 	lwpid_t lid;
    392 	int extflags;
    393 	cpuid_t cpu_num;
    394 	struct lwp *l = curlwp;
    395 	int lock_shutdown_noblock = 0;
    396 	kmutex_t *mutex;
    397 	int s = 0;
    398 
    399 	error = 0;
    400 	mutex = __UNVOLATILE(&lkp->lk_interlock);
    401 
    402 	/* LK_RETRY is for vn_lock, not for lockmgr. */
    403 	KASSERT((flags & LK_RETRY) == 0);
    404 	KASSERT((l->l_flag & LW_INTR) == 0 || panicstr != NULL);
    405 
    406 	mutex_enter(mutex);
    407 	if (flags & LK_INTERLOCK)
    408 		mutex_exit(__UNVOLATILE(interlkp));
    409 	extflags = (flags | lkp->lk_flags) & LK_EXTFLG_MASK;
    410 
    411 	if (l == NULL) {
    412 		if (!doing_shutdown) {
    413 			panic("lockmgr: no context");
    414 		} else {
    415 			l = &lwp0;
    416 			if (panicstr && (!(flags & LK_NOWAIT))) {
    417 				flags |= LK_NOWAIT;
    418 				lock_shutdown_noblock = 1;
    419 			}
    420 		}
    421 	}
    422 	lid = l->l_lid;
    423 	pid = l->l_proc->p_pid;
    424 	cpu_num = cpu_number();
    425 
    426 	/*
    427 	 * Once a lock has drained, the LK_DRAINING flag is set and an
    428 	 * exclusive lock is returned. The only valid operation thereafter
    429 	 * is a single release of that exclusive lock. This final release
    430 	 * clears the LK_DRAINING flag and sets the LK_DRAINED flag. Any
    431 	 * further requests of any sort will result in a panic. The bits
    432 	 * selected for these two flags are chosen so that they will be set
    433 	 * in memory that is freed (freed memory is filled with 0xdeadbeef).
    434 	 * The final release is permitted to give a new lease on life to
    435 	 * the lock by specifying LK_REENABLE.
    436 	 */
    437 	if (lkp->lk_flags & (LK_DRAINING|LK_DRAINED)) {
    438 #ifdef DIAGNOSTIC /* { */
    439 		if (lkp->lk_flags & LK_DRAINED)
    440 			lockpanic(lkp, "lockmgr: using decommissioned lock");
    441 		if ((flags & LK_TYPE_MASK) != LK_RELEASE ||
    442 		    WEHOLDIT(lkp, pid, lid, cpu_num) == 0)
    443 			lockpanic(lkp, "lockmgr: non-release on draining lock: %d",
    444 			    flags & LK_TYPE_MASK);
    445 #endif /* DIAGNOSTIC */ /* } */
    446 		lkp->lk_flags &= ~LK_DRAINING;
    447 		if ((flags & LK_REENABLE) == 0)
    448 			lkp->lk_flags |= LK_DRAINED;
    449 	}
    450 
    451 	switch (flags & LK_TYPE_MASK) {
    452 
    453 	case LK_SHARED:
    454 		if (WEHOLDIT(lkp, pid, lid, cpu_num) == 0) {
    455 			/*
    456 			 * If just polling, check to see if we will block.
    457 			 */
    458 			if ((extflags & LK_NOWAIT) && (lkp->lk_flags &
    459 			    (LK_HAVE_EXCL | LK_WANT_EXCL | LK_WANT_UPGRADE))) {
    460 				error = EBUSY;
    461 				break;
    462 			}
    463 			/*
    464 			 * Wait for exclusive locks and upgrades to clear.
    465 			 */
    466 			error = acquire(&lkp, &s, extflags, 0,
    467 			    LK_HAVE_EXCL | LK_WANT_EXCL | LK_WANT_UPGRADE,
    468 			    RETURN_ADDRESS);
    469 			if (error)
    470 				break;
    471 			lkp->lk_sharecount++;
    472 			lkp->lk_flags |= LK_SHARE_NONZERO;
    473 			COUNT(lkp, l, cpu_num, 1);
    474 			break;
    475 		}
    476 		/*
    477 		 * We hold an exclusive lock, so downgrade it to shared.
    478 		 * An alternative would be to fail with EDEADLK.
    479 		 */
    480 		lkp->lk_sharecount++;
    481 		lkp->lk_flags |= LK_SHARE_NONZERO;
    482 		COUNT(lkp, l, cpu_num, 1);
    483 		/* fall into downgrade */
    484 
    485 	case LK_DOWNGRADE:
    486 		if (WEHOLDIT(lkp, pid, lid, cpu_num) == 0 ||
    487 		    lkp->lk_exclusivecount == 0)
    488 			lockpanic(lkp, "lockmgr: not holding exclusive lock");
    489 		lkp->lk_sharecount += lkp->lk_exclusivecount;
    490 		lkp->lk_flags |= LK_SHARE_NONZERO;
    491 		lkp->lk_exclusivecount = 0;
    492 		lkp->lk_recurselevel = 0;
    493 		lkp->lk_flags &= ~LK_HAVE_EXCL;
    494 		SETHOLDER(lkp, LK_NOPROC, 0, LK_NOCPU);
    495 #if defined(LOCKDEBUG)
    496 		lkp->lk_unlock_addr = RETURN_ADDRESS;
    497 #endif
    498 		WAKEUP_WAITER(lkp);
    499 		break;
    500 
    501 	case LK_EXCLUPGRADE:
    502 		/*
    503 		 * If another process is ahead of us to get an upgrade,
    504 		 * then we want to fail rather than have an intervening
    505 		 * exclusive access.
    506 		 */
    507 		if (lkp->lk_flags & LK_WANT_UPGRADE) {
    508 			lkp->lk_sharecount--;
    509 			if (lkp->lk_sharecount == 0)
    510 				lkp->lk_flags &= ~LK_SHARE_NONZERO;
    511 			COUNT(lkp, l, cpu_num, -1);
    512 			error = EBUSY;
    513 			break;
    514 		}
    515 		/* fall into normal upgrade */
    516 
    517 	case LK_UPGRADE:
    518 		/*
    519 		 * Upgrade a shared lock to an exclusive one. If another
    520 		 * shared lock has already requested an upgrade to an
    521 		 * exclusive lock, our shared lock is released and an
    522 		 * exclusive lock is requested (which will be granted
    523 		 * after the upgrade). If we return an error, the file
    524 		 * will always be unlocked.
    525 		 */
    526 		if (WEHOLDIT(lkp, pid, lid, cpu_num) || lkp->lk_sharecount <= 0)
    527 			lockpanic(lkp, "lockmgr: upgrade exclusive lock");
    528 		lkp->lk_sharecount--;
    529 		if (lkp->lk_sharecount == 0)
    530 			lkp->lk_flags &= ~LK_SHARE_NONZERO;
    531 		COUNT(lkp, l, cpu_num, -1);
    532 		/*
    533 		 * If we are just polling, check to see if we will block.
    534 		 */
    535 		if ((extflags & LK_NOWAIT) &&
    536 		    ((lkp->lk_flags & LK_WANT_UPGRADE) ||
    537 		     lkp->lk_sharecount > 1)) {
    538 			error = EBUSY;
    539 			break;
    540 		}
    541 		if ((lkp->lk_flags & LK_WANT_UPGRADE) == 0) {
    542 			/*
    543 			 * We are first shared lock to request an upgrade, so
    544 			 * request upgrade and wait for the shared count to
    545 			 * drop to zero, then take exclusive lock.
    546 			 */
    547 			lkp->lk_flags |= LK_WANT_UPGRADE;
    548 			error = acquire(&lkp, &s, extflags, 0, LK_SHARE_NONZERO,
    549 			    RETURN_ADDRESS);
    550 			lkp->lk_flags &= ~LK_WANT_UPGRADE;
    551 			if (error) {
    552 				WAKEUP_WAITER(lkp);
    553 				break;
    554 			}
    555 			lkp->lk_flags |= LK_HAVE_EXCL;
    556 			SETHOLDER(lkp, pid, lid, cpu_num);
    557 #if defined(LOCKDEBUG)
    558 			lkp->lk_lock_addr = RETURN_ADDRESS;
    559 #endif
    560 			if (lkp->lk_exclusivecount != 0)
    561 				lockpanic(lkp, "lockmgr: non-zero exclusive count");
    562 			lkp->lk_exclusivecount = 1;
    563 			if (extflags & LK_SETRECURSE)
    564 				lkp->lk_recurselevel = 1;
    565 			COUNT(lkp, l, cpu_num, 1);
    566 			break;
    567 		}
    568 		/*
    569 		 * Someone else has requested upgrade. Release our shared
    570 		 * lock, awaken upgrade requestor if we are the last shared
    571 		 * lock, then request an exclusive lock.
    572 		 */
    573 		if (lkp->lk_sharecount == 0)
    574 			WAKEUP_WAITER(lkp);
    575 		/* fall into exclusive request */
    576 
    577 	case LK_EXCLUSIVE:
    578 		if (WEHOLDIT(lkp, pid, lid, cpu_num)) {
    579 			/*
    580 			 * Recursive lock.
    581 			 */
    582 			if ((extflags & LK_CANRECURSE) == 0 &&
    583 			     lkp->lk_recurselevel == 0) {
    584 				if (extflags & LK_RECURSEFAIL) {
    585 					error = EDEADLK;
    586 					break;
    587 				} else
    588 					lockpanic(lkp, "lockmgr: locking against myself");
    589 			}
    590 			lkp->lk_exclusivecount++;
    591 			if (extflags & LK_SETRECURSE &&
    592 			    lkp->lk_recurselevel == 0)
    593 				lkp->lk_recurselevel = lkp->lk_exclusivecount;
    594 			COUNT(lkp, l, cpu_num, 1);
    595 			break;
    596 		}
    597 		/*
    598 		 * If we are just polling, check to see if we will sleep.
    599 		 */
    600 		if ((extflags & LK_NOWAIT) && (lkp->lk_flags &
    601 		     (LK_HAVE_EXCL | LK_WANT_EXCL | LK_WANT_UPGRADE |
    602 		     LK_SHARE_NONZERO))) {
    603 			error = EBUSY;
    604 			break;
    605 		}
    606 		/*
    607 		 * Try to acquire the want_exclusive flag.
    608 		 */
    609 		error = acquire(&lkp, &s, extflags, 0,
    610 		    LK_HAVE_EXCL | LK_WANT_EXCL, RETURN_ADDRESS);
    611 		if (error)
    612 			break;
    613 		lkp->lk_flags |= LK_WANT_EXCL;
    614 		/*
    615 		 * Wait for shared locks and upgrades to finish.
    616 		 */
    617 		error = acquire(&lkp, &s, extflags, 0,
    618 		    LK_HAVE_EXCL | LK_WANT_UPGRADE | LK_SHARE_NONZERO,
    619 		    RETURN_ADDRESS);
    620 		lkp->lk_flags &= ~LK_WANT_EXCL;
    621 		if (error) {
    622 			WAKEUP_WAITER(lkp);
    623 			break;
    624 		}
    625 		lkp->lk_flags |= LK_HAVE_EXCL;
    626 		SETHOLDER(lkp, pid, lid, cpu_num);
    627 #if defined(LOCKDEBUG)
    628 		lkp->lk_lock_addr = RETURN_ADDRESS;
    629 #endif
    630 		if (lkp->lk_exclusivecount != 0)
    631 			lockpanic(lkp, "lockmgr: non-zero exclusive count");
    632 		lkp->lk_exclusivecount = 1;
    633 		if (extflags & LK_SETRECURSE)
    634 			lkp->lk_recurselevel = 1;
    635 		COUNT(lkp, l, cpu_num, 1);
    636 		break;
    637 
    638 	case LK_RELEASE:
    639 		if (lkp->lk_exclusivecount != 0) {
    640 			if (WEHOLDIT(lkp, pid, lid, cpu_num) == 0) {
    641 				lockpanic(lkp, "lockmgr: pid %d.%d, not "
    642 				    "exclusive lock holder %d.%d "
    643 				    "unlocking", pid, lid,
    644 				    lkp->lk_lockholder,
    645 				    lkp->lk_locklwp);
    646 			}
    647 			if (lkp->lk_exclusivecount == lkp->lk_recurselevel)
    648 				lkp->lk_recurselevel = 0;
    649 			lkp->lk_exclusivecount--;
    650 			COUNT(lkp, l, cpu_num, -1);
    651 			if (lkp->lk_exclusivecount == 0) {
    652 				lkp->lk_flags &= ~LK_HAVE_EXCL;
    653 				SETHOLDER(lkp, LK_NOPROC, 0, LK_NOCPU);
    654 #if defined(LOCKDEBUG)
    655 				lkp->lk_unlock_addr = RETURN_ADDRESS;
    656 #endif
    657 			}
    658 		} else if (lkp->lk_sharecount != 0) {
    659 			lkp->lk_sharecount--;
    660 			if (lkp->lk_sharecount == 0)
    661 				lkp->lk_flags &= ~LK_SHARE_NONZERO;
    662 			COUNT(lkp, l, cpu_num, -1);
    663 		}
    664 #ifdef DIAGNOSTIC
    665 		else
    666 			lockpanic(lkp, "lockmgr: release of unlocked lock!");
    667 #endif
    668 		WAKEUP_WAITER(lkp);
    669 		break;
    670 
    671 	case LK_DRAIN:
    672 		/*
    673 		 * Check that we do not already hold the lock, as it can
    674 		 * never drain if we do. Unfortunately, we have no way to
    675 		 * check for holding a shared lock, but at least we can
    676 		 * check for an exclusive one.
    677 		 */
    678 		if (WEHOLDIT(lkp, pid, lid, cpu_num))
    679 			lockpanic(lkp, "lockmgr: draining against myself");
    680 		/*
    681 		 * If we are just polling, check to see if we will sleep.
    682 		 */
    683 		if ((extflags & LK_NOWAIT) && (lkp->lk_flags &
    684 		     (LK_HAVE_EXCL | LK_WANT_EXCL | LK_WANT_UPGRADE |
    685 		     LK_SHARE_NONZERO | LK_WAIT_NONZERO))) {
    686 			error = EBUSY;
    687 			break;
    688 		}
    689 		error = acquire(&lkp, &s, extflags, 1,
    690 		    LK_HAVE_EXCL | LK_WANT_EXCL | LK_WANT_UPGRADE |
    691 		    LK_SHARE_NONZERO | LK_WAIT_NONZERO,
    692 		    RETURN_ADDRESS);
    693 		if (error)
    694 			break;
    695 		lkp->lk_flags |= LK_HAVE_EXCL;
    696 		if ((extflags & LK_RESURRECT) == 0)
    697 			lkp->lk_flags |= LK_DRAINING;
    698 		SETHOLDER(lkp, pid, lid, cpu_num);
    699 #if defined(LOCKDEBUG)
    700 		lkp->lk_lock_addr = RETURN_ADDRESS;
    701 #endif
    702 		lkp->lk_exclusivecount = 1;
    703 		/* XXX unlikely that we'd want this */
    704 		if (extflags & LK_SETRECURSE)
    705 			lkp->lk_recurselevel = 1;
    706 		COUNT(lkp, l, cpu_num, 1);
    707 		break;
    708 
    709 	default:
    710 		mutex_exit(mutex);
    711 		lockpanic(lkp, "lockmgr: unknown locktype request %d",
    712 		    flags & LK_TYPE_MASK);
    713 		/* NOTREACHED */
    714 	}
    715 	if ((lkp->lk_flags & LK_WAITDRAIN) != 0 &&
    716 	    ((lkp->lk_flags &
    717 	      (LK_HAVE_EXCL | LK_WANT_EXCL | LK_WANT_UPGRADE |
    718 	      LK_SHARE_NONZERO | LK_WAIT_NONZERO)) == 0)) {
    719 		lkp->lk_flags &= ~LK_WAITDRAIN;
    720 		wakeup(&lkp->lk_flags);
    721 	}
    722 	/*
    723 	 * Note that this panic will be a recursive panic, since
    724 	 * we only set lock_shutdown_noblock above if panicstr != NULL.
    725 	 */
    726 	if (error && lock_shutdown_noblock)
    727 		lockpanic(lkp, "lockmgr: deadlock (see previous panic)");
    728 
    729 	mutex_exit(mutex);
    730 	return (error);
    731 }
    732 
    733 /*
    734  * Print out information about state of a lock. Used by VOP_PRINT
    735  * routines to display ststus about contained locks.
    736  */
    737 void
    738 lockmgr_printinfo(volatile struct lock *lkp)
    739 {
    740 
    741 	if (lkp->lk_sharecount)
    742 		printf(" lock type %s: SHARED (count %d)", lkp->lk_wmesg,
    743 		    lkp->lk_sharecount);
    744 	else if (lkp->lk_flags & LK_HAVE_EXCL) {
    745 		printf(" lock type %s: EXCL (count %d) by ",
    746 		    lkp->lk_wmesg, lkp->lk_exclusivecount);
    747 		printf("pid %d.%d", lkp->lk_lockholder,
    748 		    lkp->lk_locklwp);
    749 	} else
    750 		printf(" not locked");
    751 	if (lkp->lk_waitcount > 0)
    752 		printf(" with %d pending", lkp->lk_waitcount);
    753 }
    754 
    755 #if defined(LOCKDEBUG)
    756 void
    757 assert_sleepable(struct simplelock *interlock, const char *msg)
    758 {
    759 
    760 	if (panicstr != NULL)
    761 		return;
    762 	LOCKDEBUG_BARRIER(&kernel_lock, 1);
    763 	if (CURCPU_IDLE_P()) {
    764 		panic("assert_sleepable: idle");
    765 	}
    766 }
    767 #endif
    768 
    769 #if defined(MULTIPROCESSOR)
    770 
    771 /*
    772  * Functions for manipulating the kernel_lock.  We put them here
    773  * so that they show up in profiles.
    774  */
    775 
    776 #define	_KERNEL_LOCK_ABORT(msg)						\
    777     LOCKDEBUG_ABORT(kernel_lock_id, &kernel_lock, &_kernel_lock_ops,	\
    778         __func__, msg)
    779 
    780 #ifdef LOCKDEBUG
    781 #define	_KERNEL_LOCK_ASSERT(cond)					\
    782 do {									\
    783 	if (!(cond))							\
    784 		_KERNEL_LOCK_ABORT("assertion failed: " #cond);		\
    785 } while (/* CONSTCOND */ 0)
    786 #else
    787 #define	_KERNEL_LOCK_ASSERT(cond)	/* nothing */
    788 #endif
    789 
    790 void	_kernel_lock_dump(volatile void *);
    791 
    792 lockops_t _kernel_lock_ops = {
    793 	"Kernel lock",
    794 	0,
    795 	_kernel_lock_dump
    796 };
    797 
    798 /*
    799  * Initialize the kernel lock.
    800  */
    801 void
    802 _kernel_lock_init(void)
    803 {
    804 
    805 	__cpu_simple_lock_init(&kernel_lock);
    806 	kernel_lock_id = LOCKDEBUG_ALLOC(&kernel_lock, &_kernel_lock_ops,
    807 	    RETURN_ADDRESS);
    808 }
    809 
    810 /*
    811  * Print debugging information about the kernel lock.
    812  */
    813 void
    814 _kernel_lock_dump(volatile void *junk)
    815 {
    816 	struct cpu_info *ci = curcpu();
    817 
    818 	(void)junk;
    819 
    820 	printf_nolog("curcpu holds : %18d wanted by: %#018lx\n",
    821 	    ci->ci_biglock_count, (long)ci->ci_biglock_wanted);
    822 }
    823 
    824 /*
    825  * Acquire 'nlocks' holds on the kernel lock.  If 'l' is non-null, the
    826  * acquisition is from process context.
    827  */
    828 void
    829 _kernel_lock(int nlocks, struct lwp *l)
    830 {
    831 	struct cpu_info *ci = curcpu();
    832 	LOCKSTAT_TIMER(spintime);
    833 	LOCKSTAT_FLAG(lsflag);
    834 	struct lwp *owant;
    835 #ifdef LOCKDEBUG
    836 	u_int spins;
    837 #endif
    838 	int s;
    839 
    840 	if (nlocks == 0)
    841 		return;
    842 	_KERNEL_LOCK_ASSERT(nlocks > 0);
    843 
    844 	l = curlwp;
    845 
    846 	if (ci->ci_biglock_count != 0) {
    847 		_KERNEL_LOCK_ASSERT(__SIMPLELOCK_LOCKED_P(&kernel_lock));
    848 		ci->ci_biglock_count += nlocks;
    849 		l->l_blcnt += nlocks;
    850 		return;
    851 	}
    852 
    853 	_KERNEL_LOCK_ASSERT(l->l_blcnt == 0);
    854 	LOCKDEBUG_WANTLOCK(kernel_lock_id, RETURN_ADDRESS, 0);
    855 
    856 	s = splbiglock();
    857 	if (__cpu_simple_lock_try(&kernel_lock)) {
    858 		ci->ci_biglock_count = nlocks;
    859 		l->l_blcnt = nlocks;
    860 		LOCKDEBUG_LOCKED(kernel_lock_id, RETURN_ADDRESS, 0);
    861 		splx(s);
    862 		return;
    863 	}
    864 
    865 	LOCKSTAT_ENTER(lsflag);
    866 	LOCKSTAT_START_TIMER(lsflag, spintime);
    867 
    868 	/*
    869 	 * Before setting ci_biglock_wanted we must post a store
    870 	 * fence (see kern_mutex.c).  This is accomplished by the
    871 	 * __cpu_simple_lock_try() above.
    872 	 */
    873 	owant = ci->ci_biglock_wanted;
    874 	ci->ci_biglock_wanted = curlwp;	/* XXXAD */
    875 
    876 #ifdef LOCKDEBUG
    877 	spins = 0;
    878 #endif
    879 
    880 	do {
    881 		splx(s);
    882 		while (kernel_lock == __SIMPLELOCK_LOCKED) {
    883 #ifdef LOCKDEBUG
    884 			if (SPINLOCK_SPINOUT(spins))
    885 				_KERNEL_LOCK_ABORT("spinout");
    886 #endif
    887 			SPINLOCK_BACKOFF_HOOK;
    888 			SPINLOCK_SPIN_HOOK;
    889 		}
    890 		(void)splbiglock();
    891 	} while (!__cpu_simple_lock_try(&kernel_lock));
    892 
    893 	ci->ci_biglock_wanted = owant;
    894 	ci->ci_biglock_count = nlocks;
    895 	l->l_blcnt = nlocks;
    896 	LOCKSTAT_STOP_TIMER(lsflag, spintime);
    897 	LOCKDEBUG_LOCKED(kernel_lock_id, RETURN_ADDRESS, 0);
    898 	splx(s);
    899 
    900 	/*
    901 	 * Again, another store fence is required (see kern_mutex.c).
    902 	 */
    903 	mb_write();
    904 	if (owant == NULL) {
    905 		LOCKSTAT_EVENT(lsflag, &kernel_lock, LB_KERNEL_LOCK | LB_SPIN,
    906 		    1, spintime);
    907 	}
    908 	LOCKSTAT_EXIT(lsflag);
    909 }
    910 
    911 /*
    912  * Release 'nlocks' holds on the kernel lock.  If 'nlocks' is zero, release
    913  * all holds.  If 'l' is non-null, the release is from process context.
    914  */
    915 void
    916 _kernel_unlock(int nlocks, struct lwp *l, int *countp)
    917 {
    918 	struct cpu_info *ci = curcpu();
    919 	u_int olocks;
    920 	int s;
    921 
    922 	l = curlwp;
    923 
    924 	_KERNEL_LOCK_ASSERT(nlocks < 2);
    925 
    926 	olocks = l->l_blcnt;
    927 
    928 	if (olocks == 0) {
    929 		_KERNEL_LOCK_ASSERT(nlocks <= 0);
    930 		if (countp != NULL)
    931 			*countp = 0;
    932 		return;
    933 	}
    934 
    935 	_KERNEL_LOCK_ASSERT(__SIMPLELOCK_LOCKED_P(&kernel_lock));
    936 
    937 	if (nlocks == 0)
    938 		nlocks = olocks;
    939 	else if (nlocks == -1) {
    940 		nlocks = 1;
    941 		_KERNEL_LOCK_ASSERT(olocks == 1);
    942 	}
    943 
    944 	_KERNEL_LOCK_ASSERT(ci->ci_biglock_count >= l->l_blcnt);
    945 
    946 	l->l_blcnt -= nlocks;
    947 	if (ci->ci_biglock_count == nlocks) {
    948 		s = splbiglock();
    949 		LOCKDEBUG_UNLOCKED(kernel_lock_id, RETURN_ADDRESS, 0);
    950 		ci->ci_biglock_count = 0;
    951 		__cpu_simple_unlock(&kernel_lock);
    952 		splx(s);
    953 	} else
    954 		ci->ci_biglock_count -= nlocks;
    955 
    956 	if (countp != NULL)
    957 		*countp = olocks;
    958 }
    959 
    960 #if defined(DEBUG)
    961 /*
    962  * Assert that the kernel lock is held.
    963  */
    964 void
    965 _kernel_lock_assert_locked(void)
    966 {
    967 
    968 	if (!__SIMPLELOCK_LOCKED_P(&kernel_lock) ||
    969 	    curcpu()->ci_biglock_count == 0)
    970 		_KERNEL_LOCK_ABORT("not locked");
    971 }
    972 
    973 void
    974 _kernel_lock_assert_unlocked()
    975 {
    976 
    977 	if (curcpu()->ci_biglock_count != 0)
    978 		_KERNEL_LOCK_ABORT("locked");
    979 }
    980 #endif
    981 
    982 #endif	/* MULTIPROCESSOR || LOCKDEBUG */
    983