xref: /freebsd/sys/kern/kern_lock.c (revision a1a4f1a0d87b594d3f17a97dc0127eec1417e6f6)
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$
42  */
43 
44 #include "opt_lint.h"
45 
46 #include <sys/param.h>
47 #include <sys/proc.h>
48 #include <sys/lock.h>
49 #include <sys/systm.h>
50 
51 /*
52  * Locking primitives implementation.
53  * Locks provide shared/exclusive sychronization.
54  */
55 
56 #ifdef SIMPLELOCK_DEBUG
57 #define COUNT(p, x) if (p) (p)->p_locks += (x)
58 #else
59 #define COUNT(p, x)
60 #endif
61 
62 #define LOCK_WAIT_TIME 100
63 #define LOCK_SAMPLE_WAIT 7
64 
65 #if defined(DIAGNOSTIC)
66 #define LOCK_INLINE
67 #else
68 #define LOCK_INLINE __inline
69 #endif
70 
71 #define LK_ALL (LK_HAVE_EXCL | LK_WANT_EXCL | LK_WANT_UPGRADE | \
72 	LK_SHARE_NONZERO | LK_WAIT_NONZERO)
73 
74 static int acquire(struct lock *lkp, int extflags, int wanted);
75 static int apause(struct lock *lkp, int flags);
76 static int acquiredrain(struct lock *lkp, int extflags) ;
77 
78 static LOCK_INLINE void
79 sharelock(struct lock *lkp, int incr) {
80 	lkp->lk_flags |= LK_SHARE_NONZERO;
81 	lkp->lk_sharecount += incr;
82 }
83 
84 static LOCK_INLINE void
85 shareunlock(struct lock *lkp, int decr) {
86 
87 	KASSERT(lkp->lk_sharecount >= decr, ("shareunlock: count < decr"));
88 
89 	if (lkp->lk_sharecount == decr) {
90 		lkp->lk_flags &= ~LK_SHARE_NONZERO;
91 		if (lkp->lk_flags & (LK_WANT_UPGRADE | LK_WANT_EXCL)) {
92 			wakeup(lkp);
93 		}
94 		lkp->lk_sharecount = 0;
95 	} else {
96 		lkp->lk_sharecount -= decr;
97 	}
98 }
99 
100 /*
101  * This is the waitloop optimization, and note for this to work
102  * simple_lock and simple_unlock should be subroutines to avoid
103  * optimization troubles.
104  */
105 static int
106 apause(struct lock *lkp, int flags) {
107 	int lock_wait;
108 	lock_wait = LOCK_WAIT_TIME;
109 	for (; lock_wait > 0; lock_wait--) {
110 		int i;
111 		if ((lkp->lk_flags & flags) == 0)
112 			return 0;
113 		simple_unlock(&lkp->lk_interlock);
114 		for (i = LOCK_SAMPLE_WAIT; i > 0; i--) {
115 			if ((lkp->lk_flags & flags) == 0) {
116 				simple_lock(&lkp->lk_interlock);
117 				if ((lkp->lk_flags & flags) == 0)
118 					return 0;
119 				break;
120 			}
121 		}
122 	}
123 	return 1;
124 }
125 
126 static int
127 acquire(struct lock *lkp, int extflags, int wanted) {
128 	int s, error;
129 
130 	if ((extflags & LK_NOWAIT) && (lkp->lk_flags & wanted)) {
131 		return EBUSY;
132 	}
133 
134 	if (((lkp->lk_flags | extflags) & LK_NOPAUSE) == 0) {
135 		error = apause(lkp, wanted);
136 		if (error == 0)
137 			return 0;
138 	}
139 
140 	s = splhigh();
141 	while ((lkp->lk_flags & wanted) != 0) {
142 		lkp->lk_flags |= LK_WAIT_NONZERO;
143 		lkp->lk_waitcount++;
144 		simple_unlock(&lkp->lk_interlock);
145 		error = tsleep(lkp, lkp->lk_prio, lkp->lk_wmesg, lkp->lk_timo);
146 		simple_lock(&lkp->lk_interlock);
147 		if (lkp->lk_waitcount == 1) {
148 			lkp->lk_flags &= ~LK_WAIT_NONZERO;
149 			lkp->lk_waitcount = 0;
150 		} else {
151 			lkp->lk_waitcount--;
152 		}
153 		if (error) {
154 			splx(s);
155 			return error;
156 		}
157 		if (extflags & LK_SLEEPFAIL) {
158 			splx(s);
159 			return ENOLCK;
160 		}
161 	}
162 	splx(s);
163 	return 0;
164 }
165 
166 /*
167  * Set, change, or release a lock.
168  *
169  * Shared requests increment the shared count. Exclusive requests set the
170  * LK_WANT_EXCL flag (preventing further shared locks), and wait for already
171  * accepted shared locks and shared-to-exclusive upgrades to go away.
172  */
173 int
174 #ifndef	DEBUG_LOCKS
175 lockmgr(lkp, flags, interlkp, p)
176 #else
177 debuglockmgr(lkp, flags, interlkp, p, name, file, line)
178 #endif
179 	struct lock *lkp;
180 	u_int flags;
181 	struct simplelock *interlkp;
182 	struct proc *p;
183 #ifdef	DEBUG_LOCKS
184 	const char *name;	/* Name of lock function */
185 	const char *file;	/* Name of file call is from */
186 	int line;		/* Line number in file */
187 #endif
188 {
189 	int error;
190 	pid_t pid;
191 	int extflags;
192 
193 	error = 0;
194 	if (p == NULL)
195 		pid = LK_KERNPROC;
196 	else
197 		pid = p->p_pid;
198 
199 	simple_lock(&lkp->lk_interlock);
200 	if (flags & LK_INTERLOCK)
201 		simple_unlock(interlkp);
202 
203 	extflags = (flags | lkp->lk_flags) & LK_EXTFLG_MASK;
204 
205 	switch (flags & LK_TYPE_MASK) {
206 
207 	case LK_SHARED:
208 		/*
209 		 * If we are not the exclusive lock holder, we have to block
210 		 * while there is an exclusive lock holder or while an
211 		 * exclusive lock request or upgrade request is in progress.
212 		 *
213 		 * However, if P_DEADLKTREAT is set, we override exclusive
214 		 * lock requests or upgrade requests ( but not the exclusive
215 		 * lock itself ).
216 		 */
217 		if (lkp->lk_lockholder != pid) {
218 			if (p && (p->p_flag & P_DEADLKTREAT)) {
219 				error = acquire(
220 					    lkp,
221 					    extflags,
222 					    LK_HAVE_EXCL
223 					);
224 			} else {
225 				error = acquire(
226 					    lkp,
227 					    extflags,
228 					    LK_HAVE_EXCL | LK_WANT_EXCL |
229 					     LK_WANT_UPGRADE
230 					);
231 			}
232 			if (error)
233 				break;
234 			sharelock(lkp, 1);
235 			COUNT(p, 1);
236 			break;
237 		}
238 		/*
239 		 * We hold an exclusive lock, so downgrade it to shared.
240 		 * An alternative would be to fail with EDEADLK.
241 		 */
242 		sharelock(lkp, 1);
243 		COUNT(p, 1);
244 		/* fall into downgrade */
245 
246 	case LK_DOWNGRADE:
247 #if !defined(MAX_PERF)
248 		if (lkp->lk_lockholder != pid || lkp->lk_exclusivecount == 0)
249 			panic("lockmgr: not holding exclusive lock");
250 #endif
251 		sharelock(lkp, lkp->lk_exclusivecount);
252 		lkp->lk_exclusivecount = 0;
253 		lkp->lk_flags &= ~LK_HAVE_EXCL;
254 		lkp->lk_lockholder = LK_NOPROC;
255 		if (lkp->lk_waitcount)
256 			wakeup((void *)lkp);
257 		break;
258 
259 	case LK_EXCLUPGRADE:
260 		/*
261 		 * If another process is ahead of us to get an upgrade,
262 		 * then we want to fail rather than have an intervening
263 		 * exclusive access.
264 		 */
265 		if (lkp->lk_flags & LK_WANT_UPGRADE) {
266 			shareunlock(lkp, 1);
267 			COUNT(p, -1);
268 			error = EBUSY;
269 			break;
270 		}
271 		/* fall into normal upgrade */
272 
273 	case LK_UPGRADE:
274 		/*
275 		 * Upgrade a shared lock to an exclusive one. If another
276 		 * shared lock has already requested an upgrade to an
277 		 * exclusive lock, our shared lock is released and an
278 		 * exclusive lock is requested (which will be granted
279 		 * after the upgrade). If we return an error, the file
280 		 * will always be unlocked.
281 		 */
282 #if !defined(MAX_PERF)
283 		if ((lkp->lk_lockholder == pid) || (lkp->lk_sharecount <= 0))
284 			panic("lockmgr: upgrade exclusive lock");
285 #endif
286 		shareunlock(lkp, 1);
287 		COUNT(p, -1);
288 		/*
289 		 * If we are just polling, check to see if we will block.
290 		 */
291 		if ((extflags & LK_NOWAIT) &&
292 		    ((lkp->lk_flags & LK_WANT_UPGRADE) ||
293 		     lkp->lk_sharecount > 1)) {
294 			error = EBUSY;
295 			break;
296 		}
297 		if ((lkp->lk_flags & LK_WANT_UPGRADE) == 0) {
298 			/*
299 			 * We are first shared lock to request an upgrade, so
300 			 * request upgrade and wait for the shared count to
301 			 * drop to zero, then take exclusive lock.
302 			 */
303 			lkp->lk_flags |= LK_WANT_UPGRADE;
304 			error = acquire(lkp, extflags, LK_SHARE_NONZERO);
305 			lkp->lk_flags &= ~LK_WANT_UPGRADE;
306 
307 			if (error)
308 				break;
309 			lkp->lk_flags |= LK_HAVE_EXCL;
310 			lkp->lk_lockholder = pid;
311 #if !defined(MAX_PERF)
312 			if (lkp->lk_exclusivecount != 0)
313 				panic("lockmgr: non-zero exclusive count");
314 #endif
315 			lkp->lk_exclusivecount = 1;
316 #if defined(DEBUG_LOCKS)
317 			lkp->lk_filename = file;
318 			lkp->lk_lineno = line;
319 			lkp->lk_lockername = name;
320 #endif
321 			COUNT(p, 1);
322 			break;
323 		}
324 		/*
325 		 * Someone else has requested upgrade. Release our shared
326 		 * lock, awaken upgrade requestor if we are the last shared
327 		 * lock, then request an exclusive lock.
328 		 */
329 		if ( (lkp->lk_flags & (LK_SHARE_NONZERO|LK_WAIT_NONZERO)) ==
330 			LK_WAIT_NONZERO)
331 			wakeup((void *)lkp);
332 		/* fall into exclusive request */
333 
334 	case LK_EXCLUSIVE:
335 		if (lkp->lk_lockholder == pid && pid != LK_KERNPROC) {
336 			/*
337 			 *	Recursive lock.
338 			 */
339 #if !defined(MAX_PERF)
340 			if ((extflags & (LK_NOWAIT | LK_CANRECURSE)) == 0)
341 				panic("lockmgr: locking against myself");
342 #endif
343 			if ((extflags & LK_CANRECURSE) != 0) {
344 				lkp->lk_exclusivecount++;
345 				COUNT(p, 1);
346 				break;
347 			}
348 		}
349 		/*
350 		 * If we are just polling, check to see if we will sleep.
351 		 */
352 		if ((extflags & LK_NOWAIT) &&
353 		    (lkp->lk_flags & (LK_HAVE_EXCL | LK_WANT_EXCL | LK_WANT_UPGRADE | LK_SHARE_NONZERO))) {
354 			error = EBUSY;
355 			break;
356 		}
357 		/*
358 		 * Try to acquire the want_exclusive flag.
359 		 */
360 		error = acquire(lkp, extflags, (LK_HAVE_EXCL | LK_WANT_EXCL));
361 		if (error)
362 			break;
363 		lkp->lk_flags |= LK_WANT_EXCL;
364 		/*
365 		 * Wait for shared locks and upgrades to finish.
366 		 */
367 		error = acquire(lkp, extflags, LK_WANT_UPGRADE | LK_SHARE_NONZERO);
368 		lkp->lk_flags &= ~LK_WANT_EXCL;
369 		if (error)
370 			break;
371 		lkp->lk_flags |= LK_HAVE_EXCL;
372 		lkp->lk_lockholder = pid;
373 #if !defined(MAX_PERF)
374 		if (lkp->lk_exclusivecount != 0)
375 			panic("lockmgr: non-zero exclusive count");
376 #endif
377 		lkp->lk_exclusivecount = 1;
378 #if defined(DEBUG_LOCKS)
379 			lkp->lk_filename = file;
380 			lkp->lk_lineno = line;
381 			lkp->lk_lockername = name;
382 #endif
383 		COUNT(p, 1);
384 		break;
385 
386 	case LK_RELEASE:
387 		if (lkp->lk_exclusivecount != 0) {
388 #if !defined(MAX_PERF)
389 			if (lkp->lk_lockholder != pid &&
390 			    lkp->lk_lockholder != LK_KERNPROC)
391 				panic("lockmgr: pid %d, not %s %d unlocking",
392 				    pid, "exclusive lock holder",
393 				    lkp->lk_lockholder);
394 #endif
395 			COUNT(p, -1);
396 			if (lkp->lk_exclusivecount == 1) {
397 				lkp->lk_flags &= ~LK_HAVE_EXCL;
398 				lkp->lk_lockholder = LK_NOPROC;
399 				lkp->lk_exclusivecount = 0;
400 			} else {
401 				lkp->lk_exclusivecount--;
402 			}
403 		} else if (lkp->lk_flags & LK_SHARE_NONZERO) {
404 			shareunlock(lkp, 1);
405 			COUNT(p, -1);
406 		}
407 		if (lkp->lk_flags & LK_WAIT_NONZERO)
408 			wakeup((void *)lkp);
409 		break;
410 
411 	case LK_DRAIN:
412 		/*
413 		 * Check that we do not already hold the lock, as it can
414 		 * never drain if we do. Unfortunately, we have no way to
415 		 * check for holding a shared lock, but at least we can
416 		 * check for an exclusive one.
417 		 */
418 #if !defined(MAX_PERF)
419 		if (lkp->lk_lockholder == pid)
420 			panic("lockmgr: draining against myself");
421 #endif
422 
423 		error = acquiredrain(lkp, extflags);
424 		if (error)
425 			break;
426 		lkp->lk_flags |= LK_DRAINING | LK_HAVE_EXCL;
427 		lkp->lk_lockholder = pid;
428 		lkp->lk_exclusivecount = 1;
429 #if defined(DEBUG_LOCKS)
430 			lkp->lk_filename = file;
431 			lkp->lk_lineno = line;
432 			lkp->lk_lockername = name;
433 #endif
434 		COUNT(p, 1);
435 		break;
436 
437 	default:
438 #if !defined(MAX_PERF)
439 		simple_unlock(&lkp->lk_interlock);
440 		panic("lockmgr: unknown locktype request %d",
441 		    flags & LK_TYPE_MASK);
442 #endif
443 		/* NOTREACHED */
444 	}
445 	if ((lkp->lk_flags & LK_WAITDRAIN) &&
446 	    (lkp->lk_flags & (LK_HAVE_EXCL | LK_WANT_EXCL | LK_WANT_UPGRADE |
447 		LK_SHARE_NONZERO | LK_WAIT_NONZERO)) == 0) {
448 		lkp->lk_flags &= ~LK_WAITDRAIN;
449 		wakeup((void *)&lkp->lk_flags);
450 	}
451 	simple_unlock(&lkp->lk_interlock);
452 	return (error);
453 }
454 
455 static int
456 acquiredrain(struct lock *lkp, int extflags) {
457 	int error;
458 
459 	if ((extflags & LK_NOWAIT) && (lkp->lk_flags & LK_ALL)) {
460 		return EBUSY;
461 	}
462 
463 	error = apause(lkp, LK_ALL);
464 	if (error == 0)
465 		return 0;
466 
467 	while (lkp->lk_flags & LK_ALL) {
468 		lkp->lk_flags |= LK_WAITDRAIN;
469 		simple_unlock(&lkp->lk_interlock);
470 		error = tsleep(&lkp->lk_flags, lkp->lk_prio,
471 			lkp->lk_wmesg, lkp->lk_timo);
472 		simple_lock(&lkp->lk_interlock);
473 		if (error)
474 			return error;
475 		if (extflags & LK_SLEEPFAIL) {
476 			return ENOLCK;
477 		}
478 	}
479 	return 0;
480 }
481 
482 /*
483  * Initialize a lock; required before use.
484  */
485 void
486 lockinit(lkp, prio, wmesg, timo, flags)
487 	struct lock *lkp;
488 	int prio;
489 	char *wmesg;
490 	int timo;
491 	int flags;
492 {
493 
494 	simple_lock_init(&lkp->lk_interlock);
495 	lkp->lk_flags = (flags & LK_EXTFLG_MASK);
496 	lkp->lk_sharecount = 0;
497 	lkp->lk_waitcount = 0;
498 	lkp->lk_exclusivecount = 0;
499 	lkp->lk_prio = prio;
500 	lkp->lk_wmesg = wmesg;
501 	lkp->lk_timo = timo;
502 	lkp->lk_lockholder = LK_NOPROC;
503 }
504 
505 /*
506  * Determine the status of a lock.
507  */
508 int
509 lockstatus(lkp)
510 	struct lock *lkp;
511 {
512 	int lock_type = 0;
513 
514 	simple_lock(&lkp->lk_interlock);
515 	if (lkp->lk_exclusivecount != 0)
516 		lock_type = LK_EXCLUSIVE;
517 	else if (lkp->lk_sharecount != 0)
518 		lock_type = LK_SHARED;
519 	simple_unlock(&lkp->lk_interlock);
520 	return (lock_type);
521 }
522 
523 /*
524  * Determine the number of holders of a lock.
525  */
526 int
527 lockcount(lkp)
528 	struct lock *lkp;
529 {
530 	int count;
531 
532 	simple_lock(&lkp->lk_interlock);
533 	count = lkp->lk_exclusivecount + lkp->lk_sharecount;
534 	simple_unlock(&lkp->lk_interlock);
535 	return (count);
536 }
537 
538 /*
539  * Print out information about state of a lock. Used by VOP_PRINT
540  * routines to display status about contained locks.
541  */
542 void
543 lockmgr_printinfo(lkp)
544 	struct lock *lkp;
545 {
546 
547 	if (lkp->lk_sharecount)
548 		printf(" lock type %s: SHARED (count %d)", lkp->lk_wmesg,
549 		    lkp->lk_sharecount);
550 	else if (lkp->lk_flags & LK_HAVE_EXCL)
551 		printf(" lock type %s: EXCL (count %d) by pid %d",
552 		    lkp->lk_wmesg, lkp->lk_exclusivecount, lkp->lk_lockholder);
553 	if (lkp->lk_waitcount > 0)
554 		printf(" with %d pending", lkp->lk_waitcount);
555 }
556 
557 #if defined(SIMPLELOCK_DEBUG) && (NCPUS == 1 || defined(COMPILING_LINT))
558 #include <sys/kernel.h>
559 #include <sys/sysctl.h>
560 
561 static int lockpausetime = 0;
562 SYSCTL_INT(_debug, OID_AUTO, lockpausetime, CTLFLAG_RW, &lockpausetime, 0, "");
563 
564 static int simplelockrecurse;
565 
566 /*
567  * Simple lock functions so that the debugger can see from whence
568  * they are being called.
569  */
570 void
571 simple_lock_init(alp)
572 	struct simplelock *alp;
573 {
574 
575 	alp->lock_data = 0;
576 }
577 
578 void
579 _simple_lock(alp, id, l)
580 	struct simplelock *alp;
581 	const char *id;
582 	int l;
583 {
584 
585 	if (simplelockrecurse)
586 		return;
587 	if (alp->lock_data == 1) {
588 		if (lockpausetime == -1)
589 			panic("%s:%d: simple_lock: lock held", id, l);
590 		printf("%s:%d: simple_lock: lock held\n", id, l);
591 		if (lockpausetime == 1) {
592 			Debugger("simple_lock");
593 			/*BACKTRACE(curproc); */
594 		} else if (lockpausetime > 1) {
595 			printf("%s:%d: simple_lock: lock held...", id, l);
596 			tsleep(&lockpausetime, PCATCH | PPAUSE, "slock",
597 			    lockpausetime * hz);
598 			printf(" continuing\n");
599 		}
600 	}
601 	alp->lock_data = 1;
602 	if (curproc)
603 		curproc->p_simple_locks++;
604 }
605 
606 int
607 _simple_lock_try(alp, id, l)
608 	struct simplelock *alp;
609 	const char *id;
610 	int l;
611 {
612 
613 	if (alp->lock_data)
614 		return (0);
615 	if (simplelockrecurse)
616 		return (1);
617 	alp->lock_data = 1;
618 	if (curproc)
619 		curproc->p_simple_locks++;
620 	return (1);
621 }
622 
623 void
624 _simple_unlock(alp, id, l)
625 	struct simplelock *alp;
626 	const char *id;
627 	int l;
628 {
629 
630 	if (simplelockrecurse)
631 		return;
632 	if (alp->lock_data == 0) {
633 		if (lockpausetime == -1)
634 			panic("%s:%d: simple_unlock: lock not held", id, l);
635 		printf("%s:%d: simple_unlock: lock not held\n", id, l);
636 		if (lockpausetime == 1) {
637 			Debugger("simple_unlock");
638 			/* BACKTRACE(curproc); */
639 		} else if (lockpausetime > 1) {
640 			printf("%s:%d: simple_unlock: lock not held...", id, l);
641 			tsleep(&lockpausetime, PCATCH | PPAUSE, "sunlock",
642 			    lockpausetime * hz);
643 			printf(" continuing\n");
644 		}
645 	}
646 	alp->lock_data = 0;
647 	if (curproc)
648 		curproc->p_simple_locks--;
649 }
650 #elif defined(SIMPLELOCK_DEBUG)
651 #error "SIMPLELOCK_DEBUG is not compatible with SMP!"
652 #endif /* SIMPLELOCK_DEBUG && NCPUS == 1 */
653