Home | History | Annotate | Line # | Download | only in kern
vfs_lockf.c revision 1.82
      1 /*	$NetBSD: vfs_lockf.c,v 1.82 2024/12/07 02:11:42 riastradh Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1982, 1986, 1989, 1993
      5  *	The Regents of the University of California.  All rights reserved.
      6  *
      7  * This code is derived from software contributed to Berkeley by
      8  * Scooter Morris at Genentech Inc.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  * 3. Neither the name of the University nor the names of its contributors
     19  *    may be used to endorse or promote products derived from this software
     20  *    without specific prior written permission.
     21  *
     22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     32  * SUCH DAMAGE.
     33  *
     34  *	@(#)ufs_lockf.c	8.4 (Berkeley) 10/26/94
     35  */
     36 
     37 #include <sys/cdefs.h>
     38 __KERNEL_RCSID(0, "$NetBSD: vfs_lockf.c,v 1.82 2024/12/07 02:11:42 riastradh Exp $");
     39 
     40 #include <sys/param.h>
     41 #include <sys/types.h>
     42 
     43 #include <sys/atomic.h>
     44 #include <sys/fcntl.h>
     45 #include <sys/file.h>
     46 #include <sys/kauth.h>
     47 #include <sys/kernel.h>
     48 #include <sys/kmem.h>
     49 #include <sys/lockf.h>
     50 #include <sys/proc.h>
     51 #include <sys/systm.h>
     52 #include <sys/uidinfo.h>
     53 #include <sys/vnode.h>
     54 
     55 /*
     56  * The lockf structure is a kernel structure which contains the information
     57  * associated with a byte range lock.  The lockf structures are linked into
     58  * the vnode structure.  Locks are sorted by the starting byte of the lock for
     59  * efficiency.
     60  *
     61  * lf_next is used for two purposes, depending on whether the lock is
     62  * being held, or is in conflict with an existing lock.  If this lock
     63  * is held, it indicates the next lock on the same vnode.
     64  * For pending locks, if lock->lf_next is non-NULL, then lock->lf_block
     65  * must be queued on the lf_blkhd TAILQ of lock->lf_next.
     66  */
     67 
     68 TAILQ_HEAD(locklist, lockf);
     69 
     70 struct lockf {
     71 	kcondvar_t lf_cv;	 /* Signalling */
     72 	short	lf_flags;	 /* Lock semantics: F_POSIX, F_FLOCK, F_WAIT */
     73 	short	lf_type;	 /* Lock type: F_RDLCK, F_WRLCK */
     74 	off_t	lf_start;	 /* The byte # of the start of the lock */
     75 	off_t	lf_end;		 /* The byte # of the end of the lock (-1=EOF)*/
     76 	void	*lf_id;		 /* process or file description holding lock */
     77 	struct	lockf **lf_head; /* Back pointer to the head of lockf list */
     78 	struct	lockf *lf_next;	 /* Next lock on this vnode, or blocking lock */
     79 	struct  locklist lf_blkhd; /* List of requests blocked on this lock */
     80 	TAILQ_ENTRY(lockf) lf_block;/* A request waiting for a lock */
     81 	struct	uidinfo *lf_uip; /* Cached pointer to uidinfo */
     82 };
     83 
     84 /* Maximum length of sleep chains to traverse to try and detect deadlock. */
     85 #define MAXDEPTH 50
     86 
     87 static kmutex_t lockf_lock __cacheline_aligned;
     88 static char lockstr[] = "lockf";
     89 
     90 /*
     91  * This variable controls the maximum number of processes that will
     92  * be checked in doing deadlock detection.
     93  */
     94 int maxlockdepth = MAXDEPTH;
     95 
     96 #ifdef LOCKF_DEBUG
     97 int	lockf_debug = 0;
     98 #endif
     99 
    100 #define SELF	0x1
    101 #define OTHERS	0x2
    102 
    103 /*
    104  * XXX TODO
    105  * Misc cleanups: "void *id" should be visible in the API as a
    106  * "struct proc *".
    107  * (This requires rototilling all VFS's which support advisory locking).
    108  */
    109 
    110 /*
    111  * If there's a lot of lock contention on a single vnode, locking
    112  * schemes which allow for more paralleism would be needed.  Given how
    113  * infrequently byte-range locks are actually used in typical BSD
    114  * code, a more complex approach probably isn't worth it.
    115  */
    116 
    117 /*
    118  * We enforce a limit on locks by uid, so that a single user cannot
    119  * run the kernel out of memory.  For now, the limit is pretty coarse.
    120  * There is no limit on root.
    121  *
    122  * Splitting a lock will always succeed, regardless of current allocations.
    123  * If you're slightly above the limit, we still have to permit an allocation
    124  * so that the unlock can succeed.  If the unlocking causes too many splits,
    125  * however, you're totally cutoff.
    126  */
    127 #define MAXLOCKSPERUID (2 * maxfiles)
    128 
    129 #ifdef LOCKF_DEBUG
    130 /*
    131  * Print out a lock.
    132  */
    133 static void
    134 lf_print(const char *tag, struct lockf *lock)
    135 {
    136 
    137 	printf("%s: lock %p for ", tag, lock);
    138 	if (lock->lf_flags & F_POSIX)
    139 		printf("proc %d", ((struct proc *)lock->lf_id)->p_pid);
    140 	else
    141 		printf("file %p", (struct file *)lock->lf_id);
    142 	printf(" %s, start %jd, end %jd",
    143 		lock->lf_type == F_RDLCK ? "shared" :
    144 		lock->lf_type == F_WRLCK ? "exclusive" :
    145 		lock->lf_type == F_UNLCK ? "unlock" :
    146 		"unknown", (intmax_t)lock->lf_start, (intmax_t)lock->lf_end);
    147 	if (TAILQ_FIRST(&lock->lf_blkhd))
    148 		printf(" block %p\n", TAILQ_FIRST(&lock->lf_blkhd));
    149 	else
    150 		printf("\n");
    151 }
    152 
    153 static void
    154 lf_printlist(const char *tag, struct lockf *lock)
    155 {
    156 	struct lockf *lf, *blk;
    157 
    158 	printf("%s: Lock list:\n", tag);
    159 	for (lf = *lock->lf_head; lf; lf = lf->lf_next) {
    160 		printf("\tlock %p for ", lf);
    161 		if (lf->lf_flags & F_POSIX)
    162 			printf("proc %d", ((struct proc *)lf->lf_id)->p_pid);
    163 		else
    164 			printf("file %p", (struct file *)lf->lf_id);
    165 		printf(", %s, start %jd, end %jd",
    166 		    lf->lf_type == F_RDLCK ? "shared" :
    167 		    lf->lf_type == F_WRLCK ? "exclusive" :
    168 		    lf->lf_type == F_UNLCK ? "unlock" :
    169 		    "unknown", (intmax_t)lf->lf_start, (intmax_t)lf->lf_end);
    170 		TAILQ_FOREACH(blk, &lf->lf_blkhd, lf_block) {
    171 			if (blk->lf_flags & F_POSIX)
    172 				printf("; proc %d",
    173 				    ((struct proc *)blk->lf_id)->p_pid);
    174 			else
    175 				printf("; file %p", (struct file *)blk->lf_id);
    176 			printf(", %s, start %jd, end %jd",
    177 			    blk->lf_type == F_RDLCK ? "shared" :
    178 			    blk->lf_type == F_WRLCK ? "exclusive" :
    179 			    blk->lf_type == F_UNLCK ? "unlock" :
    180 			    "unknown",
    181 			    (intmax_t)blk->lf_start, (intmax_t)blk->lf_end);
    182 			if (TAILQ_FIRST(&blk->lf_blkhd))
    183 				 panic("lf_printlist: bad list");
    184 		}
    185 		printf("\n");
    186 	}
    187 }
    188 #endif /* LOCKF_DEBUG */
    189 
    190 /*
    191  * 3 options for allowfail.
    192  * 0 - always allocate.  1 - cutoff at limit.  2 - cutoff at double limit.
    193  */
    194 static struct lockf *
    195 lf_alloc(int allowfail)
    196 {
    197 	struct uidinfo *uip;
    198 	struct lockf *lock;
    199 	u_long lcnt;
    200 	const uid_t uid = kauth_cred_geteuid(kauth_cred_get());
    201 
    202 	uip = uid_find(uid);
    203 	lcnt = atomic_inc_ulong_nv(&uip->ui_lockcnt);
    204 	if (uid && allowfail && lcnt >
    205 	    (allowfail == 1 ? MAXLOCKSPERUID : (MAXLOCKSPERUID * 2))) {
    206 		atomic_dec_ulong(&uip->ui_lockcnt);
    207 		return NULL;
    208 	}
    209 
    210 	lock = kmem_alloc(sizeof(*lock), KM_SLEEP);
    211 	lock->lf_uip = uip;
    212 	cv_init(&lock->lf_cv, lockstr);
    213 	return lock;
    214 }
    215 
    216 static void
    217 lf_free(struct lockf *lock)
    218 {
    219 
    220 	atomic_dec_ulong(&lock->lf_uip->ui_lockcnt);
    221 	cv_destroy(&lock->lf_cv);
    222 	kmem_free(lock, sizeof(*lock));
    223 }
    224 
    225 /*
    226  * Walk the list of locks for an inode to
    227  * find an overlapping lock (if any).
    228  *
    229  * NOTE: this returns only the FIRST overlapping lock.  There
    230  *	 may be more than one.
    231  */
    232 static int
    233 lf_findoverlap(struct lockf *lf, struct lockf *lock, int type,
    234     struct lockf ***prev, struct lockf **overlap)
    235 {
    236 	off_t start, end;
    237 
    238 	*overlap = lf;
    239 	if (lf == NULL)
    240 		return 0;
    241 #ifdef LOCKF_DEBUG
    242 	if (lockf_debug & 2)
    243 		lf_print("lf_findoverlap: looking for overlap in", lock);
    244 #endif /* LOCKF_DEBUG */
    245 	start = lock->lf_start;
    246 	end = lock->lf_end;
    247 	while (lf != NULL) {
    248 		if (((type == SELF) && lf->lf_id != lock->lf_id) ||
    249 		    ((type == OTHERS) && lf->lf_id == lock->lf_id)) {
    250 			*prev = &lf->lf_next;
    251 			*overlap = lf = lf->lf_next;
    252 			continue;
    253 		}
    254 #ifdef LOCKF_DEBUG
    255 		if (lockf_debug & 2)
    256 			lf_print("\tchecking", lf);
    257 #endif /* LOCKF_DEBUG */
    258 		/*
    259 		 * OK, check for overlap
    260 		 *
    261 		 * Six cases:
    262 		 *	0) no overlap
    263 		 *	1) overlap == lock
    264 		 *	2) overlap contains lock
    265 		 *	3) lock contains overlap
    266 		 *	4) overlap starts before lock
    267 		 *	5) overlap ends after lock
    268 		 */
    269 		if ((lf->lf_end != -1 && start > lf->lf_end) ||
    270 		    (end != -1 && lf->lf_start > end)) {
    271 			/* Case 0 */
    272 #ifdef LOCKF_DEBUG
    273 			if (lockf_debug & 2)
    274 				printf("no overlap\n");
    275 #endif /* LOCKF_DEBUG */
    276 			if ((type & SELF) && end != -1 && lf->lf_start > end)
    277 				return 0;
    278 			*prev = &lf->lf_next;
    279 			*overlap = lf = lf->lf_next;
    280 			continue;
    281 		}
    282 		if ((lf->lf_start == start) && (lf->lf_end == end)) {
    283 			/* Case 1 */
    284 #ifdef LOCKF_DEBUG
    285 			if (lockf_debug & 2)
    286 				printf("overlap == lock\n");
    287 #endif /* LOCKF_DEBUG */
    288 			return 1;
    289 		}
    290 		if ((lf->lf_start <= start) &&
    291 		    (end != -1) &&
    292 		    ((lf->lf_end >= end) || (lf->lf_end == -1))) {
    293 			/* Case 2 */
    294 #ifdef LOCKF_DEBUG
    295 			if (lockf_debug & 2)
    296 				printf("overlap contains lock\n");
    297 #endif /* LOCKF_DEBUG */
    298 			return 2;
    299 		}
    300 		if (start <= lf->lf_start &&
    301 		           (end == -1 ||
    302 			   (lf->lf_end != -1 && end >= lf->lf_end))) {
    303 			/* Case 3 */
    304 #ifdef LOCKF_DEBUG
    305 			if (lockf_debug & 2)
    306 				printf("lock contains overlap\n");
    307 #endif /* LOCKF_DEBUG */
    308 			return 3;
    309 		}
    310 		if ((lf->lf_start < start) &&
    311 			((lf->lf_end >= start) || (lf->lf_end == -1))) {
    312 			/* Case 4 */
    313 #ifdef LOCKF_DEBUG
    314 			if (lockf_debug & 2)
    315 				printf("overlap starts before lock\n");
    316 #endif /* LOCKF_DEBUG */
    317 			return 4;
    318 		}
    319 		if ((lf->lf_start > start) &&
    320 			(end != -1) &&
    321 			((lf->lf_end > end) || (lf->lf_end == -1))) {
    322 			/* Case 5 */
    323 #ifdef LOCKF_DEBUG
    324 			if (lockf_debug & 2)
    325 				printf("overlap ends after lock\n");
    326 #endif /* LOCKF_DEBUG */
    327 			return 5;
    328 		}
    329 		panic("lf_findoverlap: default");
    330 	}
    331 	return 0;
    332 }
    333 
    334 /*
    335  * Split a lock and a contained region into
    336  * two or three locks as necessary.
    337  */
    338 static void
    339 lf_split(struct lockf *lock1, struct lockf *lock2, struct lockf **sparelock)
    340 {
    341 	struct lockf *splitlock;
    342 
    343 #ifdef LOCKF_DEBUG
    344 	if (lockf_debug & 2) {
    345 		lf_print("lf_split", lock1);
    346 		lf_print("splitting from", lock2);
    347 	}
    348 #endif /* LOCKF_DEBUG */
    349 	/*
    350 	 * Check to see if splitting into only two pieces.
    351 	 */
    352 	if (lock1->lf_start == lock2->lf_start) {
    353 		lock1->lf_start = lock2->lf_end + 1;
    354 		lock2->lf_next = lock1;
    355 		return;
    356 	}
    357 	if (lock1->lf_end == lock2->lf_end) {
    358 		lock1->lf_end = lock2->lf_start - 1;
    359 		lock2->lf_next = lock1->lf_next;
    360 		lock1->lf_next = lock2;
    361 		return;
    362 	}
    363 	/*
    364 	 * Make a new lock consisting of the last part of
    365 	 * the encompassing lock
    366 	 */
    367 	splitlock = *sparelock;
    368 	*sparelock = NULL;
    369 	cv_destroy(&splitlock->lf_cv);
    370 	memcpy(splitlock, lock1, sizeof(*splitlock));
    371 	cv_init(&splitlock->lf_cv, lockstr);
    372 
    373 	splitlock->lf_start = lock2->lf_end + 1;
    374 	TAILQ_INIT(&splitlock->lf_blkhd);
    375 	lock1->lf_end = lock2->lf_start - 1;
    376 	/*
    377 	 * OK, now link it in
    378 	 */
    379 	splitlock->lf_next = lock1->lf_next;
    380 	lock2->lf_next = splitlock;
    381 	lock1->lf_next = lock2;
    382 }
    383 
    384 /*
    385  * Wakeup a blocklist
    386  */
    387 static void
    388 lf_wakelock(struct lockf *listhead)
    389 {
    390 	struct lockf *wakelock;
    391 
    392 	while ((wakelock = TAILQ_FIRST(&listhead->lf_blkhd))) {
    393 		KASSERT(wakelock->lf_next == listhead);
    394 		TAILQ_REMOVE(&listhead->lf_blkhd, wakelock, lf_block);
    395 		wakelock->lf_next = NULL;
    396 #ifdef LOCKF_DEBUG
    397 		if (lockf_debug & 2)
    398 			lf_print("lf_wakelock: awakening", wakelock);
    399 #endif
    400 		cv_broadcast(&wakelock->lf_cv);
    401 	}
    402 }
    403 
    404 /*
    405  * Remove a byte-range lock on an inode.
    406  *
    407  * Generally, find the lock (or an overlap to that lock)
    408  * and remove it (or shrink it), then wakeup anyone we can.
    409  */
    410 static int
    411 lf_clearlock(struct lockf *unlock, struct lockf **sparelock)
    412 {
    413 	struct lockf **head = unlock->lf_head;
    414 	struct lockf *lf = *head;
    415 	struct lockf *overlap, **prev;
    416 	int ovcase;
    417 
    418 	if (lf == NULL)
    419 		return 0;
    420 #ifdef LOCKF_DEBUG
    421 	if (unlock->lf_type != F_UNLCK)
    422 		panic("lf_clearlock: bad type");
    423 	if (lockf_debug & 1)
    424 		lf_print("lf_clearlock", unlock);
    425 #endif /* LOCKF_DEBUG */
    426 	prev = head;
    427 	while ((ovcase = lf_findoverlap(lf, unlock, SELF,
    428 	    &prev, &overlap)) != 0) {
    429 		/*
    430 		 * Wakeup the list of locks to be retried.
    431 		 */
    432 		lf_wakelock(overlap);
    433 
    434 		switch (ovcase) {
    435 
    436 		case 1: /* overlap == lock */
    437 			*prev = overlap->lf_next;
    438 			lf_free(overlap);
    439 			break;
    440 
    441 		case 2: /* overlap contains lock: split it */
    442 			if (overlap->lf_start == unlock->lf_start) {
    443 				overlap->lf_start = unlock->lf_end + 1;
    444 				break;
    445 			}
    446 			lf_split(overlap, unlock, sparelock);
    447 			overlap->lf_next = unlock->lf_next;
    448 			break;
    449 
    450 		case 3: /* lock contains overlap */
    451 			*prev = overlap->lf_next;
    452 			lf = overlap->lf_next;
    453 			lf_free(overlap);
    454 			continue;
    455 
    456 		case 4: /* overlap starts before lock */
    457 			overlap->lf_end = unlock->lf_start - 1;
    458 			prev = &overlap->lf_next;
    459 			lf = overlap->lf_next;
    460 			continue;
    461 
    462 		case 5: /* overlap ends after lock */
    463 			overlap->lf_start = unlock->lf_end + 1;
    464 			break;
    465 		}
    466 		break;
    467 	}
    468 #ifdef LOCKF_DEBUG
    469 	if (lockf_debug & 1)
    470 		lf_printlist("lf_clearlock", unlock);
    471 #endif /* LOCKF_DEBUG */
    472 	return 0;
    473 }
    474 
    475 /*
    476  * Walk the list of locks for an inode and
    477  * return the first blocking lock.
    478  */
    479 static struct lockf *
    480 lf_getblock(struct lockf *lock)
    481 {
    482 	struct lockf **prev, *overlap, *lf = *(lock->lf_head);
    483 
    484 	prev = lock->lf_head;
    485 	while (lf_findoverlap(lf, lock, OTHERS, &prev, &overlap) != 0) {
    486 		/*
    487 		 * We've found an overlap, see if it blocks us
    488 		 */
    489 		if ((lock->lf_type == F_WRLCK || overlap->lf_type == F_WRLCK))
    490 			return overlap;
    491 		/*
    492 		 * Nope, point to the next one on the list and
    493 		 * see if it blocks us
    494 		 */
    495 		lf = overlap->lf_next;
    496 	}
    497 	return NULL;
    498 }
    499 
    500 /*
    501  * Set a byte-range lock.
    502  */
    503 static int
    504 lf_setlock(struct lockf *lock, struct lockf **sparelock,
    505     kmutex_t *interlock)
    506 {
    507 	struct lockf *block;
    508 	struct lockf **head = lock->lf_head;
    509 	struct lockf **prev, *overlap, *ltmp;
    510 	int ovcase, needtolink, error;
    511 
    512 #ifdef LOCKF_DEBUG
    513 	if (lockf_debug & 1)
    514 		lf_print("lf_setlock", lock);
    515 #endif /* LOCKF_DEBUG */
    516 
    517 	/*
    518 	 * Scan lock list for this file looking for locks that would block us.
    519 	 */
    520 	while ((block = lf_getblock(lock)) != NULL) {
    521 		/*
    522 		 * Free the structure and return if nonblocking.
    523 		 */
    524 		if ((lock->lf_flags & F_WAIT) == 0) {
    525 			lf_free(lock);
    526 			return EAGAIN;
    527 		}
    528 		/*
    529 		 * We are blocked. Since flock style locks cover
    530 		 * the whole file, there is no chance for deadlock.
    531 		 * For byte-range locks we must check for deadlock.
    532 		 *
    533 		 * Deadlock detection is done by looking through the
    534 		 * wait channels to see if there are any cycles that
    535 		 * involve us. MAXDEPTH is set just to make sure we
    536 		 * do not go off into neverneverland.
    537 		 */
    538 		if ((lock->lf_flags & F_POSIX) &&
    539 		    (block->lf_flags & F_POSIX)) {
    540 			struct lwp *wlwp;
    541 			volatile const struct lockf *waitblock;
    542 			int i = 0;
    543 			struct proc *p;
    544 
    545 			p = (struct proc *)block->lf_id;
    546 			KASSERT(p != NULL);
    547 			while (i++ < maxlockdepth) {
    548 				mutex_enter(p->p_lock);
    549 				if (p->p_nlwps > 1) {
    550 					mutex_exit(p->p_lock);
    551 					break;
    552 				}
    553 				wlwp = LIST_FIRST(&p->p_lwps);
    554 				lwp_lock(wlwp);
    555 				if (wlwp->l_wchan == NULL ||
    556 				    wlwp->l_wmesg != lockstr) {
    557 					lwp_unlock(wlwp);
    558 					mutex_exit(p->p_lock);
    559 					break;
    560 				}
    561 				waitblock = wlwp->l_wchan;
    562 				lwp_unlock(wlwp);
    563 				mutex_exit(p->p_lock);
    564 				/* Get the owner of the blocking lock */
    565 				waitblock = waitblock->lf_next;
    566 				if ((waitblock->lf_flags & F_POSIX) == 0)
    567 					break;
    568 				p = (struct proc *)waitblock->lf_id;
    569 				if (p == curproc) {
    570 					lf_free(lock);
    571 					return EDEADLK;
    572 				}
    573 			}
    574 			/*
    575 			 * If we're still following a dependency chain
    576 			 * after maxlockdepth iterations, assume we're in
    577 			 * a cycle to be safe.
    578 			 */
    579 			if (i >= maxlockdepth) {
    580 				lf_free(lock);
    581 				return EDEADLK;
    582 			}
    583 		}
    584 		/*
    585 		 * For flock type locks, we must first remove
    586 		 * any shared locks that we hold before we sleep
    587 		 * waiting for an exclusive lock.
    588 		 */
    589 		if ((lock->lf_flags & F_FLOCK) &&
    590 		    lock->lf_type == F_WRLCK) {
    591 			lock->lf_type = F_UNLCK;
    592 			(void) lf_clearlock(lock, NULL);
    593 			lock->lf_type = F_WRLCK;
    594 		}
    595 		/*
    596 		 * Add our lock to the blocked list and sleep until we're free.
    597 		 * Remember who blocked us (for deadlock detection).
    598 		 */
    599 		lock->lf_next = block;
    600 		TAILQ_INSERT_TAIL(&block->lf_blkhd, lock, lf_block);
    601 #ifdef LOCKF_DEBUG
    602 		if (lockf_debug & 1) {
    603 			lf_print("lf_setlock: blocking on", block);
    604 			lf_printlist("lf_setlock", block);
    605 		}
    606 #endif /* LOCKF_DEBUG */
    607 		error = cv_wait_sig(&lock->lf_cv, interlock);
    608 
    609 		/*
    610 		 * We may have been awoken by a signal (in
    611 		 * which case we must remove ourselves from the
    612 		 * blocked list) and/or by another process
    613 		 * releasing a lock (in which case we have already
    614 		 * been removed from the blocked list and our
    615 		 * lf_next field set to NULL).
    616 		 */
    617 		if (lock->lf_next != NULL) {
    618 			TAILQ_REMOVE(&lock->lf_next->lf_blkhd, lock, lf_block);
    619 			lock->lf_next = NULL;
    620 		}
    621 		if (error) {
    622 			lf_free(lock);
    623 			return error;
    624 		}
    625 	}
    626 	/*
    627 	 * No blocks!!  Add the lock.  Note that we will
    628 	 * downgrade or upgrade any overlapping locks this
    629 	 * process already owns.
    630 	 *
    631 	 * Skip over locks owned by other processes.
    632 	 * Handle any locks that overlap and are owned by ourselves.
    633 	 */
    634 	prev = head;
    635 	block = *head;
    636 	needtolink = 1;
    637 	for (;;) {
    638 		ovcase = lf_findoverlap(block, lock, SELF, &prev, &overlap);
    639 		if (ovcase)
    640 			block = overlap->lf_next;
    641 		/*
    642 		 * Six cases:
    643 		 *	0) no overlap
    644 		 *	1) overlap == lock
    645 		 *	2) overlap contains lock
    646 		 *	3) lock contains overlap
    647 		 *	4) overlap starts before lock
    648 		 *	5) overlap ends after lock
    649 		 */
    650 		switch (ovcase) {
    651 		case 0: /* no overlap */
    652 			if (needtolink) {
    653 				*prev = lock;
    654 				lock->lf_next = overlap;
    655 			}
    656 			break;
    657 
    658 		case 1: /* overlap == lock */
    659 			/*
    660 			 * If downgrading lock, others may be
    661 			 * able to acquire it.
    662 			 */
    663 			if (lock->lf_type == F_RDLCK &&
    664 			    overlap->lf_type == F_WRLCK)
    665 				lf_wakelock(overlap);
    666 			overlap->lf_type = lock->lf_type;
    667 			lf_free(lock);
    668 			lock = overlap; /* for debug output below */
    669 			break;
    670 
    671 		case 2: /* overlap contains lock */
    672 			/*
    673 			 * Check for common starting point and different types.
    674 			 */
    675 			if (overlap->lf_type == lock->lf_type) {
    676 				lf_free(lock);
    677 				lock = overlap; /* for debug output below */
    678 				break;
    679 			}
    680 			if (overlap->lf_start == lock->lf_start) {
    681 				*prev = lock;
    682 				lock->lf_next = overlap;
    683 				overlap->lf_start = lock->lf_end + 1;
    684 			} else
    685 				lf_split(overlap, lock, sparelock);
    686 			lf_wakelock(overlap);
    687 			break;
    688 
    689 		case 3: /* lock contains overlap */
    690 			/*
    691 			 * If downgrading lock, others may be able to
    692 			 * acquire it, otherwise take the list.
    693 			 */
    694 			if (lock->lf_type == F_RDLCK &&
    695 			    overlap->lf_type == F_WRLCK) {
    696 				lf_wakelock(overlap);
    697 			} else {
    698 				while ((ltmp =
    699 					TAILQ_FIRST(&overlap->lf_blkhd))
    700 				    != NULL) {
    701 					KASSERT(ltmp->lf_next == overlap);
    702 					TAILQ_REMOVE(&overlap->lf_blkhd, ltmp,
    703 					    lf_block);
    704 					ltmp->lf_next = lock;
    705 					TAILQ_INSERT_TAIL(&lock->lf_blkhd,
    706 					    ltmp, lf_block);
    707 				}
    708 			}
    709 			/*
    710 			 * Add the new lock if necessary and delete the
    711 			 * overlap.
    712 			 */
    713 			if (needtolink) {
    714 				*prev = lock;
    715 				lock->lf_next = overlap->lf_next;
    716 				prev = &lock->lf_next;
    717 				needtolink = 0;
    718 			} else
    719 				*prev = overlap->lf_next;
    720 			lf_free(overlap);
    721 			continue;
    722 
    723 		case 4: /* overlap starts before lock */
    724 			/*
    725 			 * Add lock after overlap on the list.
    726 			 */
    727 			lock->lf_next = overlap->lf_next;
    728 			overlap->lf_next = lock;
    729 			overlap->lf_end = lock->lf_start - 1;
    730 			prev = &lock->lf_next;
    731 			lf_wakelock(overlap);
    732 			needtolink = 0;
    733 			continue;
    734 
    735 		case 5: /* overlap ends after lock */
    736 			/*
    737 			 * Add the new lock before overlap.
    738 			 */
    739 			if (needtolink) {
    740 				*prev = lock;
    741 				lock->lf_next = overlap;
    742 			}
    743 			overlap->lf_start = lock->lf_end + 1;
    744 			lf_wakelock(overlap);
    745 			break;
    746 		}
    747 		break;
    748 	}
    749 #ifdef LOCKF_DEBUG
    750 	if (lockf_debug & 1) {
    751 		lf_print("lf_setlock: got the lock", lock);
    752 		lf_printlist("lf_setlock", lock);
    753 	}
    754 #endif /* LOCKF_DEBUG */
    755 	return 0;
    756 }
    757 
    758 /*
    759  * Check whether there is a blocking lock,
    760  * and if so return its process identifier.
    761  */
    762 static int
    763 lf_getlock(struct lockf *lock, struct flock *fl)
    764 {
    765 	struct lockf *block;
    766 
    767 #ifdef LOCKF_DEBUG
    768 	if (lockf_debug & 1)
    769 		lf_print("lf_getlock", lock);
    770 #endif /* LOCKF_DEBUG */
    771 
    772 	if ((block = lf_getblock(lock)) != NULL) {
    773 		fl->l_type = block->lf_type;
    774 		fl->l_whence = SEEK_SET;
    775 		fl->l_start = block->lf_start;
    776 		if (block->lf_end == -1)
    777 			fl->l_len = 0;
    778 		else
    779 			fl->l_len = block->lf_end - block->lf_start + 1;
    780 		if (block->lf_flags & F_POSIX)
    781 			fl->l_pid = ((struct proc *)block->lf_id)->p_pid;
    782 		else
    783 			fl->l_pid = -1;
    784 	} else {
    785 		fl->l_type = F_UNLCK;
    786 	}
    787 	return 0;
    788 }
    789 
    790 /*
    791  * Do an advisory lock operation.
    792  */
    793 int
    794 lf_advlock(struct vop_advlock_args *ap, struct lockf **head, off_t size)
    795 {
    796 	struct flock *fl = ap->a_fl;
    797 	struct lockf *lock = NULL;
    798 	struct lockf *sparelock;
    799 	kmutex_t *interlock = &lockf_lock;
    800 	off_t start, end;
    801 	int error = 0;
    802 
    803 	KASSERTMSG(size >= 0, "size=%jd", (intmax_t)size);
    804 
    805 	/*
    806 	 * Convert the flock structure into a start and end.
    807 	 */
    808 	switch (fl->l_whence) {
    809 	case SEEK_SET:
    810 	case SEEK_CUR:
    811 		/*
    812 		 * Caller is responsible for adding any necessary offset
    813 		 * when SEEK_CUR is used.
    814 		 */
    815 		start = fl->l_start;
    816 		break;
    817 
    818 	case SEEK_END:
    819 		if (fl->l_start > __type_max(off_t) - size)
    820 			return EINVAL;
    821 		start = size + fl->l_start;
    822 		break;
    823 
    824 	default:
    825 		return EINVAL;
    826 	}
    827 
    828 	if (fl->l_len == 0)
    829 		end = -1;
    830 	else {
    831 		if (fl->l_len >= 0) {
    832 			if (start >= 0 &&
    833 			    fl->l_len - 1 > __type_max(off_t) - start)
    834 				return EINVAL;
    835 			end = start + (fl->l_len - 1);
    836 		} else {
    837 			/* lockf() allows -ve lengths */
    838 			if (start < 0)
    839 				return EINVAL;
    840 			end = start - 1;
    841 			start += fl->l_len;
    842 		}
    843 	}
    844 	if (start < 0)
    845 		return EINVAL;
    846 
    847 	/*
    848 	 * Allocate locks before acquiring the interlock.  We need two
    849 	 * locks in the worst case.
    850 	 */
    851 	switch (ap->a_op) {
    852 	case F_SETLK:
    853 	case F_UNLCK:
    854 		/*
    855 		 * XXX For F_UNLCK case, we can re-use the lock.
    856 		 */
    857 		if ((ap->a_flags & F_FLOCK) == 0) {
    858 			/*
    859 			 * Byte-range lock might need one more lock.
    860 			 */
    861 			sparelock = lf_alloc(0);
    862 			if (sparelock == NULL) {
    863 				error = ENOMEM;
    864 				goto quit;
    865 			}
    866 			break;
    867 		}
    868 		/* FALLTHROUGH */
    869 
    870 	case F_GETLK:
    871 		sparelock = NULL;
    872 		break;
    873 
    874 	default:
    875 		return EINVAL;
    876 	}
    877 
    878 	switch (ap->a_op) {
    879 	case F_SETLK:
    880 		lock = lf_alloc(1);
    881 		break;
    882 	case F_UNLCK:
    883 		if (start == 0 || end == -1) {
    884 			/* never split */
    885 			lock = lf_alloc(0);
    886 		} else {
    887 			/* might split */
    888 			lock = lf_alloc(2);
    889 		}
    890 		break;
    891 	case F_GETLK:
    892 		lock = lf_alloc(0);
    893 		break;
    894 	}
    895 	if (lock == NULL) {
    896 		error = ENOMEM;
    897 		goto quit;
    898 	}
    899 
    900 	mutex_enter(interlock);
    901 
    902 	/*
    903 	 * Avoid the common case of unlocking when inode has no locks.
    904 	 */
    905 	if (*head == (struct lockf *)0) {
    906 		if (ap->a_op != F_SETLK) {
    907 			fl->l_type = F_UNLCK;
    908 			error = 0;
    909 			goto quit_unlock;
    910 		}
    911 	}
    912 
    913 	/*
    914 	 * Create the lockf structure.
    915 	 */
    916 	lock->lf_start = start;
    917 	lock->lf_end = end;
    918 	lock->lf_head = head;
    919 	lock->lf_type = fl->l_type;
    920 	lock->lf_next = (struct lockf *)0;
    921 	TAILQ_INIT(&lock->lf_blkhd);
    922 	lock->lf_flags = ap->a_flags;
    923 	if (lock->lf_flags & F_POSIX) {
    924 		KASSERT(curproc == (struct proc *)ap->a_id);
    925 	}
    926 	lock->lf_id = ap->a_id;
    927 
    928 	/*
    929 	 * Do the requested operation.
    930 	 */
    931 	switch (ap->a_op) {
    932 
    933 	case F_SETLK:
    934 		error = lf_setlock(lock, &sparelock, interlock);
    935 		lock = NULL; /* lf_setlock freed it */
    936 		break;
    937 
    938 	case F_UNLCK:
    939 		error = lf_clearlock(lock, &sparelock);
    940 		break;
    941 
    942 	case F_GETLK:
    943 		error = lf_getlock(lock, fl);
    944 		break;
    945 
    946 	default:
    947 		break;
    948 		/* NOTREACHED */
    949 	}
    950 
    951 quit_unlock:
    952 	mutex_exit(interlock);
    953 quit:
    954 	if (lock)
    955 		lf_free(lock);
    956 	if (sparelock)
    957 		lf_free(sparelock);
    958 
    959 	return error;
    960 }
    961 
    962 /*
    963  * Initialize subsystem.
    964  *
    965  * XXX We use a global lock.  This could be the vnode interlock, but
    966  * the deadlock detection code may need to inspect locks belonging to
    967  * other files.
    968  */
    969 void
    970 lf_init(void)
    971 {
    972 
    973 	mutex_init(&lockf_lock, MUTEX_DEFAULT, IPL_NONE);
    974 }
    975