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