kern_lock.c revision 91698
1/*
2 * Copyright (c) 1995
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * Copyright (C) 1997
6 *	John S. Dyson.  All rights reserved.
7 *
8 * This code contains ideas from software contributed to Berkeley by
9 * Avadis Tevanian, Jr., Michael Wayne Young, and the Mach Operating
10 * System project at Carnegie-Mellon University.
11 *
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
14 * are met:
15 * 1. Redistributions of source code must retain the above copyright
16 *    notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 *    notice, this list of conditions and the following disclaimer in the
19 *    documentation and/or other materials provided with the distribution.
20 * 3. All advertising materials mentioning features or use of this software
21 *    must display the following acknowledgement:
22 *	This product includes software developed by the University of
23 *	California, Berkeley and its contributors.
24 * 4. Neither the name of the University nor the names of its contributors
25 *    may be used to endorse or promote products derived from this software
26 *    without specific prior written permission.
27 *
28 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
29 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
30 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
32 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
33 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
34 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
35 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
36 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
37 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38 * SUCH DAMAGE.
39 *
40 *	@(#)kern_lock.c	8.18 (Berkeley) 5/21/95
41 * $FreeBSD: head/sys/kern/kern_lock.c 91698 2002-03-05 17:45:12Z eivind $
42 */
43
44#include <sys/param.h>
45#include <sys/proc.h>
46#include <sys/kernel.h>
47#include <sys/ktr.h>
48#include <sys/lock.h>
49#include <sys/malloc.h>
50#include <sys/mutex.h>
51#include <sys/systm.h>
52
53/*
54 * Locking primitives implementation.
55 * Locks provide shared/exclusive sychronization.
56 */
57
58#define LOCK_WAIT_TIME 100
59#define LOCK_SAMPLE_WAIT 7
60
61#if defined(DIAGNOSTIC)
62#define LOCK_INLINE
63#else
64#define LOCK_INLINE __inline
65#endif
66
67#define LK_ALL (LK_HAVE_EXCL | LK_WANT_EXCL | LK_WANT_UPGRADE | \
68	LK_SHARE_NONZERO | LK_WAIT_NONZERO)
69
70/*
71 * Mutex array variables.  Rather than each lockmgr lock having its own mutex,
72 * share a fixed (at boot time) number of mutexes across all lockmgr locks in
73 * order to keep sizeof(struct lock) down.
74 */
75int lock_mtx_valid;
76static struct mtx lock_mtx;
77
78static int acquire(struct lock *lkp, int extflags, int wanted);
79static int apause(struct lock *lkp, int flags);
80static int acquiredrain(struct lock *lkp, int extflags) ;
81
82static void
83lockmgr_init(void *dummy __unused)
84{
85	/*
86	 * Initialize the lockmgr protection mutex if it hasn't already been
87	 * done.  Unless something changes about kernel startup order, VM
88	 * initialization will always cause this mutex to already be
89	 * initialized in a call to lockinit().
90	 */
91	if (lock_mtx_valid == 0) {
92		mtx_init(&lock_mtx, "lockmgr", MTX_DEF);
93		lock_mtx_valid = 1;
94	}
95}
96SYSINIT(lmgrinit, SI_SUB_LOCK, SI_ORDER_FIRST, lockmgr_init, NULL)
97
98static LOCK_INLINE void
99sharelock(struct lock *lkp, int incr) {
100	lkp->lk_flags |= LK_SHARE_NONZERO;
101	lkp->lk_sharecount += incr;
102}
103
104static LOCK_INLINE void
105shareunlock(struct lock *lkp, int decr) {
106
107	KASSERT(lkp->lk_sharecount >= decr, ("shareunlock: count < decr"));
108
109	if (lkp->lk_sharecount == decr) {
110		lkp->lk_flags &= ~LK_SHARE_NONZERO;
111		if (lkp->lk_flags & (LK_WANT_UPGRADE | LK_WANT_EXCL)) {
112			wakeup(lkp);
113		}
114		lkp->lk_sharecount = 0;
115	} else {
116		lkp->lk_sharecount -= decr;
117	}
118}
119
120/*
121 * This is the waitloop optimization.
122 */
123static int
124apause(struct lock *lkp, int flags)
125{
126#ifdef SMP
127	int i, lock_wait;
128#endif
129
130	if ((lkp->lk_flags & flags) == 0)
131		return 0;
132#ifdef SMP
133	for (lock_wait = LOCK_WAIT_TIME; lock_wait > 0; lock_wait--) {
134		mtx_unlock(lkp->lk_interlock);
135		for (i = LOCK_SAMPLE_WAIT; i > 0; i--)
136			if ((lkp->lk_flags & flags) == 0)
137				break;
138		mtx_lock(lkp->lk_interlock);
139		if ((lkp->lk_flags & flags) == 0)
140			return 0;
141	}
142#endif
143	return 1;
144}
145
146static int
147acquire(struct lock *lkp, int extflags, int wanted) {
148	int s, error;
149
150	CTR3(KTR_LOCKMGR,
151	    "acquire(): lkp == %p, extflags == 0x%x, wanted == 0x%x\n",
152	    lkp, extflags, wanted);
153
154	if ((extflags & LK_NOWAIT) && (lkp->lk_flags & wanted)) {
155		return EBUSY;
156	}
157
158	if (((lkp->lk_flags | extflags) & LK_NOPAUSE) == 0) {
159		error = apause(lkp, wanted);
160		if (error == 0)
161			return 0;
162	}
163
164	s = splhigh();
165	while ((lkp->lk_flags & wanted) != 0) {
166		lkp->lk_flags |= LK_WAIT_NONZERO;
167		lkp->lk_waitcount++;
168		error = msleep(lkp, lkp->lk_interlock, lkp->lk_prio,
169		    lkp->lk_wmesg,
170		    ((extflags & LK_TIMELOCK) ? lkp->lk_timo : 0));
171		if (lkp->lk_waitcount == 1) {
172			lkp->lk_flags &= ~LK_WAIT_NONZERO;
173			lkp->lk_waitcount = 0;
174		} else {
175			lkp->lk_waitcount--;
176		}
177		if (error) {
178			splx(s);
179			return error;
180		}
181		if (extflags & LK_SLEEPFAIL) {
182			splx(s);
183			return ENOLCK;
184		}
185	}
186	splx(s);
187	return 0;
188}
189
190/*
191 * Set, change, or release a lock.
192 *
193 * Shared requests increment the shared count. Exclusive requests set the
194 * LK_WANT_EXCL flag (preventing further shared locks), and wait for already
195 * accepted shared locks and shared-to-exclusive upgrades to go away.
196 */
197int
198#ifndef	DEBUG_LOCKS
199lockmgr(lkp, flags, interlkp, td)
200#else
201debuglockmgr(lkp, flags, interlkp, td, name, file, line)
202#endif
203	struct lock *lkp;
204	u_int flags;
205	struct mtx *interlkp;
206	struct thread *td;
207#ifdef	DEBUG_LOCKS
208	const char *name;	/* Name of lock function */
209	const char *file;	/* Name of file call is from */
210	int line;		/* Line number in file */
211#endif
212{
213	int error;
214	pid_t pid;
215	int extflags, lockflags;
216
217	CTR5(KTR_LOCKMGR,
218	    "lockmgr(): lkp == %p (lk_wmesg == \"%s\"), flags == 0x%x, "
219	    "interlkp == %p, td == %p", lkp, lkp->lk_wmesg, flags, interlkp, td);
220
221	error = 0;
222	if (td == NULL)
223		pid = LK_KERNPROC;
224	else
225		pid = td->td_proc->p_pid;
226
227	mtx_lock(lkp->lk_interlock);
228	if (flags & LK_INTERLOCK) {
229		mtx_assert(interlkp, MA_OWNED | MA_NOTRECURSED);
230		mtx_unlock(interlkp);
231	}
232
233	if (panicstr != NULL) {
234		mtx_unlock(lkp->lk_interlock);
235		return (0);
236	}
237
238	extflags = (flags | lkp->lk_flags) & LK_EXTFLG_MASK;
239
240	switch (flags & LK_TYPE_MASK) {
241
242	case LK_SHARED:
243		/*
244		 * If we are not the exclusive lock holder, we have to block
245		 * while there is an exclusive lock holder or while an
246		 * exclusive lock request or upgrade request is in progress.
247		 *
248		 * However, if TDF_DEADLKTREAT is set, we override exclusive
249		 * lock requests or upgrade requests ( but not the exclusive
250		 * lock itself ).
251		 */
252		if (lkp->lk_lockholder != pid) {
253			lockflags = LK_HAVE_EXCL;
254			mtx_lock_spin(&sched_lock);
255			if (td != NULL && !(td->td_flags & TDF_DEADLKTREAT))
256				lockflags |= LK_WANT_EXCL | LK_WANT_UPGRADE;
257			mtx_unlock_spin(&sched_lock);
258			error = acquire(lkp, extflags, lockflags);
259			if (error)
260				break;
261			sharelock(lkp, 1);
262			break;
263		}
264		/*
265		 * We hold an exclusive lock, so downgrade it to shared.
266		 * An alternative would be to fail with EDEADLK.
267		 */
268		sharelock(lkp, 1);
269		/* fall into downgrade */
270
271	case LK_DOWNGRADE:
272		KASSERT(lkp->lk_lockholder == pid && lkp->lk_exclusivecount != 0,
273			("lockmgr: not holding exclusive lock "
274			"(owner pid (%d) != pid (%d), exlcnt (%d) != 0",
275			lkp->lk_lockholder, pid, lkp->lk_exclusivecount));
276		sharelock(lkp, lkp->lk_exclusivecount);
277		lkp->lk_exclusivecount = 0;
278		lkp->lk_flags &= ~LK_HAVE_EXCL;
279		lkp->lk_lockholder = LK_NOPROC;
280		if (lkp->lk_waitcount)
281			wakeup((void *)lkp);
282		break;
283
284	case LK_EXCLUPGRADE:
285		/*
286		 * If another process is ahead of us to get an upgrade,
287		 * then we want to fail rather than have an intervening
288		 * exclusive access.
289		 */
290		if (lkp->lk_flags & LK_WANT_UPGRADE) {
291			shareunlock(lkp, 1);
292			error = EBUSY;
293			break;
294		}
295		/* fall into normal upgrade */
296
297	case LK_UPGRADE:
298		/*
299		 * Upgrade a shared lock to an exclusive one. If another
300		 * shared lock has already requested an upgrade to an
301		 * exclusive lock, our shared lock is released and an
302		 * exclusive lock is requested (which will be granted
303		 * after the upgrade). If we return an error, the file
304		 * will always be unlocked.
305		 */
306		if ((lkp->lk_lockholder == pid) || (lkp->lk_sharecount <= 0))
307			panic("lockmgr: upgrade exclusive lock");
308		shareunlock(lkp, 1);
309		/*
310		 * If we are just polling, check to see if we will block.
311		 */
312		if ((extflags & LK_NOWAIT) &&
313		    ((lkp->lk_flags & LK_WANT_UPGRADE) ||
314		     lkp->lk_sharecount > 1)) {
315			error = EBUSY;
316			break;
317		}
318		if ((lkp->lk_flags & LK_WANT_UPGRADE) == 0) {
319			/*
320			 * We are first shared lock to request an upgrade, so
321			 * request upgrade and wait for the shared count to
322			 * drop to zero, then take exclusive lock.
323			 */
324			lkp->lk_flags |= LK_WANT_UPGRADE;
325			error = acquire(lkp, extflags, LK_SHARE_NONZERO);
326			lkp->lk_flags &= ~LK_WANT_UPGRADE;
327
328			if (error)
329				break;
330			lkp->lk_flags |= LK_HAVE_EXCL;
331			lkp->lk_lockholder = pid;
332			if (lkp->lk_exclusivecount != 0)
333				panic("lockmgr: non-zero exclusive count");
334			lkp->lk_exclusivecount = 1;
335#if defined(DEBUG_LOCKS)
336			lkp->lk_filename = file;
337			lkp->lk_lineno = line;
338			lkp->lk_lockername = name;
339#endif
340			break;
341		}
342		/*
343		 * Someone else has requested upgrade. Release our shared
344		 * lock, awaken upgrade requestor if we are the last shared
345		 * lock, then request an exclusive lock.
346		 */
347		if ( (lkp->lk_flags & (LK_SHARE_NONZERO|LK_WAIT_NONZERO)) ==
348			LK_WAIT_NONZERO)
349			wakeup((void *)lkp);
350		/* fall into exclusive request */
351
352	case LK_EXCLUSIVE:
353		if (lkp->lk_lockholder == pid && pid != LK_KERNPROC) {
354			/*
355			 *	Recursive lock.
356			 */
357			if ((extflags & (LK_NOWAIT | LK_CANRECURSE)) == 0)
358				panic("lockmgr: locking against myself");
359			if ((extflags & LK_CANRECURSE) != 0) {
360				lkp->lk_exclusivecount++;
361				break;
362			}
363		}
364		/*
365		 * If we are just polling, check to see if we will sleep.
366		 */
367		if ((extflags & LK_NOWAIT) &&
368		    (lkp->lk_flags & (LK_HAVE_EXCL | LK_WANT_EXCL | LK_WANT_UPGRADE | LK_SHARE_NONZERO))) {
369			error = EBUSY;
370			break;
371		}
372		/*
373		 * Try to acquire the want_exclusive flag.
374		 */
375		error = acquire(lkp, extflags, (LK_HAVE_EXCL | LK_WANT_EXCL));
376		if (error)
377			break;
378		lkp->lk_flags |= LK_WANT_EXCL;
379		/*
380		 * Wait for shared locks and upgrades to finish.
381		 */
382		error = acquire(lkp, extflags, LK_WANT_UPGRADE | LK_SHARE_NONZERO);
383		lkp->lk_flags &= ~LK_WANT_EXCL;
384		if (error)
385			break;
386		lkp->lk_flags |= LK_HAVE_EXCL;
387		lkp->lk_lockholder = pid;
388		if (lkp->lk_exclusivecount != 0)
389			panic("lockmgr: non-zero exclusive count");
390		lkp->lk_exclusivecount = 1;
391#if defined(DEBUG_LOCKS)
392			lkp->lk_filename = file;
393			lkp->lk_lineno = line;
394			lkp->lk_lockername = name;
395#endif
396		break;
397
398	case LK_RELEASE:
399		if (lkp->lk_exclusivecount != 0) {
400			if (lkp->lk_lockholder != pid &&
401			    lkp->lk_lockholder != LK_KERNPROC) {
402				panic("lockmgr: pid %d, not %s %d unlocking",
403				    pid, "exclusive lock holder",
404				    lkp->lk_lockholder);
405			}
406			if (lkp->lk_exclusivecount == 1) {
407				lkp->lk_flags &= ~LK_HAVE_EXCL;
408				lkp->lk_lockholder = LK_NOPROC;
409				lkp->lk_exclusivecount = 0;
410			} else {
411				lkp->lk_exclusivecount--;
412			}
413		} else if (lkp->lk_flags & LK_SHARE_NONZERO)
414			shareunlock(lkp, 1);
415		if (lkp->lk_flags & LK_WAIT_NONZERO)
416			wakeup((void *)lkp);
417		break;
418
419	case LK_DRAIN:
420		/*
421		 * Check that we do not already hold the lock, as it can
422		 * never drain if we do. Unfortunately, we have no way to
423		 * check for holding a shared lock, but at least we can
424		 * check for an exclusive one.
425		 */
426		if (lkp->lk_lockholder == pid)
427			panic("lockmgr: draining against myself");
428
429		error = acquiredrain(lkp, extflags);
430		if (error)
431			break;
432		lkp->lk_flags |= LK_DRAINING | LK_HAVE_EXCL;
433		lkp->lk_lockholder = pid;
434		lkp->lk_exclusivecount = 1;
435#if defined(DEBUG_LOCKS)
436			lkp->lk_filename = file;
437			lkp->lk_lineno = line;
438			lkp->lk_lockername = name;
439#endif
440		break;
441
442	default:
443		mtx_unlock(lkp->lk_interlock);
444		panic("lockmgr: unknown locktype request %d",
445		    flags & LK_TYPE_MASK);
446		/* NOTREACHED */
447	}
448	if ((lkp->lk_flags & LK_WAITDRAIN) &&
449	    (lkp->lk_flags & (LK_HAVE_EXCL | LK_WANT_EXCL | LK_WANT_UPGRADE |
450		LK_SHARE_NONZERO | LK_WAIT_NONZERO)) == 0) {
451		lkp->lk_flags &= ~LK_WAITDRAIN;
452		wakeup((void *)&lkp->lk_flags);
453	}
454	mtx_unlock(lkp->lk_interlock);
455	return (error);
456}
457
458static int
459acquiredrain(struct lock *lkp, int extflags) {
460	int error;
461
462	if ((extflags & LK_NOWAIT) && (lkp->lk_flags & LK_ALL)) {
463		return EBUSY;
464	}
465
466	error = apause(lkp, LK_ALL);
467	if (error == 0)
468		return 0;
469
470	while (lkp->lk_flags & LK_ALL) {
471		lkp->lk_flags |= LK_WAITDRAIN;
472		error = msleep(&lkp->lk_flags, lkp->lk_interlock, lkp->lk_prio,
473			lkp->lk_wmesg,
474			((extflags & LK_TIMELOCK) ? lkp->lk_timo : 0));
475		if (error)
476			return error;
477		if (extflags & LK_SLEEPFAIL) {
478			return ENOLCK;
479		}
480	}
481	return 0;
482}
483
484/*
485 * Initialize a lock; required before use.
486 */
487void
488lockinit(lkp, prio, wmesg, timo, flags)
489	struct lock *lkp;
490	int prio;
491	const char *wmesg;
492	int timo;
493	int flags;
494{
495	CTR5(KTR_LOCKMGR, "lockinit(): lkp == %p, prio == %d, wmesg == \"%s\", "
496	    "timo == %d, flags = 0x%x\n", lkp, prio, wmesg, timo, flags);
497
498	if (lock_mtx_valid == 0) {
499		mtx_init(&lock_mtx, "lockmgr", MTX_DEF);
500		lock_mtx_valid = 1;
501	}
502	/*
503	 * XXX cleanup - make sure mtxpool is always initialized before
504	 * this is ever called.
505	 */
506	if (mtx_pool_valid) {
507		mtx_lock(&lock_mtx);
508		lkp->lk_interlock = mtx_pool_alloc();
509		mtx_unlock(&lock_mtx);
510	} else {
511		lkp->lk_interlock = &lock_mtx;
512	}
513	lkp->lk_flags = (flags & LK_EXTFLG_MASK);
514	lkp->lk_sharecount = 0;
515	lkp->lk_waitcount = 0;
516	lkp->lk_exclusivecount = 0;
517	lkp->lk_prio = prio;
518	lkp->lk_wmesg = wmesg;
519	lkp->lk_timo = timo;
520	lkp->lk_lockholder = LK_NOPROC;
521}
522
523/*
524 * Destroy a lock.
525 */
526void
527lockdestroy(lkp)
528	struct lock *lkp;
529{
530	CTR2(KTR_LOCKMGR, "lockdestroy(): lkp == %p (lk_wmesg == \"%s\")",
531	    lkp, lkp->lk_wmesg);
532}
533
534/*
535 * Determine the status of a lock.
536 */
537int
538lockstatus(lkp, td)
539	struct lock *lkp;
540	struct thread *td;
541{
542	int lock_type = 0;
543
544	mtx_lock(lkp->lk_interlock);
545	if (lkp->lk_exclusivecount != 0) {
546		if (td == NULL || lkp->lk_lockholder == td->td_proc->p_pid)
547			lock_type = LK_EXCLUSIVE;
548		else
549			lock_type = LK_EXCLOTHER;
550	} else if (lkp->lk_sharecount != 0)
551		lock_type = LK_SHARED;
552	mtx_unlock(lkp->lk_interlock);
553	return (lock_type);
554}
555
556/*
557 * Determine the number of holders of a lock.
558 */
559int
560lockcount(lkp)
561	struct lock *lkp;
562{
563	int count;
564
565	mtx_lock(lkp->lk_interlock);
566	count = lkp->lk_exclusivecount + lkp->lk_sharecount;
567	mtx_unlock(lkp->lk_interlock);
568	return (count);
569}
570
571/*
572 * Print out information about state of a lock. Used by VOP_PRINT
573 * routines to display status about contained locks.
574 */
575void
576lockmgr_printinfo(lkp)
577	struct lock *lkp;
578{
579
580	if (lkp->lk_sharecount)
581		printf(" lock type %s: SHARED (count %d)", lkp->lk_wmesg,
582		    lkp->lk_sharecount);
583	else if (lkp->lk_flags & LK_HAVE_EXCL)
584		printf(" lock type %s: EXCL (count %d) by pid %d",
585		    lkp->lk_wmesg, lkp->lk_exclusivecount, lkp->lk_lockholder);
586	if (lkp->lk_waitcount > 0)
587		printf(" with %d pending", lkp->lk_waitcount);
588}
589