]> git.saurik.com Git - apple/xnu.git/blob - bsd/kern/kern_lockf.c
xnu-2050.9.2.tar.gz
[apple/xnu.git] / bsd / kern / kern_lockf.c
1 /*
2 * Copyright (c) 2006 Apple Computer, Inc. All rights reserved.
3 *
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
14 *
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
25 *
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27 */
28 /*
29 * Copyright (c) 1982, 1986, 1989, 1993
30 * The Regents of the University of California. All rights reserved.
31 *
32 * This code is derived from software contributed to Berkeley by
33 * Scooter Morris at Genentech Inc.
34 *
35 * Redistribution and use in source and binary forms, with or without
36 * modification, are permitted provided that the following conditions
37 * are met:
38 * 1. Redistributions of source code must retain the above copyright
39 * notice, this list of conditions and the following disclaimer.
40 * 2. Redistributions in binary form must reproduce the above copyright
41 * notice, this list of conditions and the following disclaimer in the
42 * documentation and/or other materials provided with the distribution.
43 * 4. Neither the name of the University nor the names of its contributors
44 * may be used to endorse or promote products derived from this software
45 * without specific prior written permission.
46 *
47 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
48 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
49 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
50 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
51 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
52 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
53 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
54 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
55 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
56 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
57 * SUCH DAMAGE.
58 *
59 * @(#)ufs_lockf.c 8.3 (Berkeley) 1/6/94
60 */
61
62 #include <sys/cdefs.h>
63 #include <sys/param.h>
64 #include <sys/systm.h>
65 #include <sys/kernel.h>
66 #include <sys/lock.h>
67 #include <sys/mount.h>
68 #include <sys/proc.h>
69 #include <sys/signalvar.h>
70 #include <sys/unistd.h>
71 #include <sys/user.h>
72 #include <sys/vnode.h>
73 #include <sys/vnode_internal.h>
74 #include <sys/vnode_if.h>
75 #include <sys/malloc.h>
76 #include <sys/fcntl.h>
77 #include <sys/lockf.h>
78
79 /*
80 * This variable controls the maximum number of processes that will
81 * be checked in doing deadlock detection.
82 */
83 static int maxlockdepth = MAXDEPTH;
84
85 #ifdef LOCKF_DEBUGGING
86 #include <sys/sysctl.h>
87 #include <ufs/ufs/quota.h>
88 #include <ufs/ufs/inode.h>
89 void lf_print(const char *tag, struct lockf *lock);
90 void lf_printlist(const char *tag, struct lockf *lock);
91 static int lockf_debug = 2;
92 SYSCTL_INT(_debug, OID_AUTO, lockf_debug, CTLFLAG_RW | CTLFLAG_LOCKED, &lockf_debug, 0, "");
93
94 /*
95 * If there is no mask bit selector, or there is on, and the selector is
96 * set, then output the debugging diagnostic.
97 */
98 #define LOCKF_DEBUG(mask, ...) \
99 do { \
100 if( !(mask) || ((mask) & lockf_debug)) { \
101 printf(__VA_ARGS__); \
102 } \
103 } while(0)
104 #else /* !LOCKF_DEBUGGING */
105 #define LOCKF_DEBUG(mask, ...) /* mask */
106 #endif /* !LOCKF_DEBUGGING */
107
108 MALLOC_DEFINE(M_LOCKF, "lockf", "Byte-range locking structures");
109
110 #define NOLOCKF (struct lockf *)0
111 #define SELF 0x1
112 #define OTHERS 0x2
113 #define OFF_MAX 0x7fffffffffffffffULL /* max off_t */
114
115 /*
116 * Overlapping lock states
117 */
118 typedef enum {
119 OVERLAP_NONE = 0,
120 OVERLAP_EQUALS_LOCK,
121 OVERLAP_CONTAINS_LOCK,
122 OVERLAP_CONTAINED_BY_LOCK,
123 OVERLAP_STARTS_BEFORE_LOCK,
124 OVERLAP_ENDS_AFTER_LOCK
125 } overlap_t;
126
127 static int lf_clearlock(struct lockf *);
128 static overlap_t lf_findoverlap(struct lockf *,
129 struct lockf *, int, struct lockf ***, struct lockf **);
130 static struct lockf *lf_getblock(struct lockf *, pid_t);
131 static int lf_getlock(struct lockf *, struct flock *, pid_t);
132 static int lf_setlock(struct lockf *);
133 static int lf_split(struct lockf *, struct lockf *);
134 static void lf_wakelock(struct lockf *, boolean_t);
135
136 /*
137 * lf_advlock
138 *
139 * Description: Advisory record locking support
140 *
141 * Parameters: ap Argument pointer to a vnop_advlock_args
142 * argument descriptor structure for the
143 * lock operation to be attempted.
144 *
145 * Returns: 0 Success
146 * EOVERFLOW
147 * EINVAL
148 * ENOLCK Number of locked regions exceeds limit
149 * lf_setlock:EAGAIN
150 * lf_setlock:EDEADLK
151 * lf_setlock:EINTR
152 * lf_setlock:ENOLCK
153 * lf_clearlock:ENOLCK
154 * vnode_size:???
155 *
156 * Notes: We return ENOLCK when we run out of memory to support locks; as
157 * such, there is no specific expectation limit other than the
158 * amount of available resources.
159 */
160 int
161 lf_advlock(struct vnop_advlock_args *ap)
162 {
163 struct vnode *vp = ap->a_vp;
164 struct flock *fl = ap->a_fl;
165 vfs_context_t context = ap->a_context;
166 struct lockf *lock;
167 off_t start, end, oadd;
168 u_quad_t size;
169 int error;
170 struct lockf **head = &vp->v_lockf;
171
172 /* XXX HFS may need a !vnode_isreg(vp) EISDIR error here */
173
174 /*
175 * Avoid the common case of unlocking when inode has no locks.
176 */
177 if (*head == (struct lockf *)0) {
178 if (ap->a_op != F_SETLK) {
179 fl->l_type = F_UNLCK;
180 LOCKF_DEBUG(0, "lf_advlock: '%s' unlock without lock\n", vfs_context_proc(context)->p_comm);
181 return (0);
182 }
183 }
184
185 /*
186 * Convert the flock structure into a start and end.
187 */
188 switch (fl->l_whence) {
189
190 case SEEK_SET:
191 case SEEK_CUR:
192 /*
193 * Caller is responsible for adding any necessary offset
194 * when SEEK_CUR is used.
195 */
196 start = fl->l_start;
197 break;
198
199 case SEEK_END:
200
201 /*
202 * It's OK to cast the u_quad_t to and off_t here, since they
203 * are the same storage size, and the value of the returned
204 * contents will never overflow into the sign bit. We need to
205 * do this because we will use size to force range checks.
206 */
207 if ((error = vnode_size(vp, (off_t *)&size, context))) {
208 LOCKF_DEBUG(0, "lf_advlock: vnode_getattr failed: %d\n", error);
209 return (error);
210 }
211
212 if (size > OFF_MAX ||
213 (fl->l_start > 0 &&
214 size > (u_quad_t)(OFF_MAX - fl->l_start)))
215 return (EOVERFLOW);
216 start = size + fl->l_start;
217 break;
218
219 default:
220 LOCKF_DEBUG(0, "lf_advlock: unknown whence %d\n", fl->l_whence);
221 return (EINVAL);
222 }
223 if (start < 0) {
224 LOCKF_DEBUG(0, "lf_advlock: start < 0 (%qd)\n", start);
225 return (EINVAL);
226 }
227 if (fl->l_len < 0) {
228 if (start == 0) {
229 LOCKF_DEBUG(0, "lf_advlock: len < 0 & start == 0\n");
230 return (EINVAL);
231 }
232 end = start - 1;
233 start += fl->l_len;
234 if (start < 0) {
235 LOCKF_DEBUG(0, "lf_advlock: start < 0 (%qd)\n", start);
236 return (EINVAL);
237 }
238 } else if (fl->l_len == 0)
239 end = -1;
240 else {
241 oadd = fl->l_len - 1;
242 if (oadd > (off_t)(OFF_MAX - start)) {
243 LOCKF_DEBUG(0, "lf_advlock: overflow\n");
244 return (EOVERFLOW);
245 }
246 end = start + oadd;
247 }
248 /*
249 * Create the lockf structure
250 */
251 MALLOC(lock, struct lockf *, sizeof *lock, M_LOCKF, M_WAITOK);
252 if (lock == NULL)
253 return (ENOLCK);
254 lock->lf_start = start;
255 lock->lf_end = end;
256 lock->lf_id = ap->a_id;
257 lock->lf_vnode = vp;
258 lock->lf_type = fl->l_type;
259 lock->lf_head = head;
260 lock->lf_next = (struct lockf *)0;
261 TAILQ_INIT(&lock->lf_blkhd);
262 lock->lf_flags = ap->a_flags;
263
264 if (ap->a_flags & F_FLOCK)
265 lock->lf_flags |= F_WAKE1_SAFE;
266
267 lck_mtx_lock(&vp->v_lock); /* protect the lockf list */
268 /*
269 * Do the requested operation.
270 */
271 switch(ap->a_op) {
272 case F_SETLK:
273 error = lf_setlock(lock);
274 break;
275
276 case F_UNLCK:
277 error = lf_clearlock(lock);
278 FREE(lock, M_LOCKF);
279 break;
280
281 case F_GETLK:
282 error = lf_getlock(lock, fl, -1);
283 FREE(lock, M_LOCKF);
284 break;
285
286 #if CONFIG_EMBEDDED
287 case F_GETLKPID:
288 error = lf_getlock(lock, fl, fl->l_pid);
289 FREE(lock, M_LOCKF);
290 break;
291 #endif
292
293 default:
294 FREE(lock, M_LOCKF);
295 error = EINVAL;
296 break;
297 }
298 lck_mtx_unlock(&vp->v_lock); /* done manipulating the list */
299
300 LOCKF_DEBUG(0, "lf_advlock: normal exit: %d\n\n", error);
301 return (error);
302 }
303
304 /*
305 * Empty the queue of msleeping requests for a lock on the given vnode.
306 * Called with the vnode already locked. Used for forced unmount, where
307 * a flock(2) invoker sleeping on a blocked lock holds an iocount reference
308 * that prevents the vnode from ever being drained. Force unmounting wins.
309 */
310 void
311 lf_abort_advlocks(vnode_t vp)
312 {
313 struct lockf *lock;
314
315 if ((lock = vp->v_lockf) == NULL)
316 return;
317
318 lck_mtx_assert(&vp->v_lock, LCK_MTX_ASSERT_OWNED);
319
320 if (!TAILQ_EMPTY(&lock->lf_blkhd)) {
321 struct lockf *tlock;
322
323 TAILQ_FOREACH(tlock, &lock->lf_blkhd, lf_block) {
324 /*
325 * Setting this flag should cause all
326 * currently blocked F_SETLK request to
327 * return to userland with an errno.
328 */
329 tlock->lf_flags |= F_ABORT;
330 }
331 lf_wakelock(lock, TRUE);
332 }
333 }
334
335 /*
336 * Take any lock attempts which are currently blocked by a given lock ("from")
337 * and mark them as blocked by a different lock ("to"). Used in the case
338 * where a byte range currently occupied by "from" is to be occupied by "to."
339 */
340 static void
341 lf_move_blocked(struct lockf *to, struct lockf *from)
342 {
343 struct lockf *tlock;
344
345 TAILQ_FOREACH(tlock, &from->lf_blkhd, lf_block) {
346 tlock->lf_next = to;
347 }
348
349 TAILQ_CONCAT(&to->lf_blkhd, &from->lf_blkhd, lf_block);
350 }
351
352 /*
353 * lf_coalesce_adjacent
354 *
355 * Description: Helper function: when setting a lock, coalesce adjacent
356 * locks. Needed because adjacent locks are not overlapping,
357 * but POSIX requires that they be coalesced.
358 *
359 * Parameters: lock The new lock which may be adjacent
360 * to already locked regions, and which
361 * should therefore be coalesced with them
362 *
363 * Returns: <void>
364 */
365 static void
366 lf_coalesce_adjacent(struct lockf *lock)
367 {
368 struct lockf **lf = lock->lf_head;
369
370 while (*lf != NOLOCKF) {
371 /* reject locks that obviously could not be coalesced */
372 if ((*lf == lock) ||
373 ((*lf)->lf_id != lock->lf_id) ||
374 ((*lf)->lf_type != lock->lf_type)) {
375 lf = &(*lf)->lf_next;
376 continue;
377 }
378
379 /*
380 * NOTE: Assumes that if two locks are adjacent on the number line
381 * and belong to the same owner, then they are adjacent on the list.
382 */
383 if ((*lf)->lf_end != -1 &&
384 ((*lf)->lf_end + 1) == lock->lf_start) {
385 struct lockf *adjacent = *lf;
386
387 LOCKF_DEBUG(0, "lf_coalesce_adjacent: coalesce adjacent previous\n");
388 lock->lf_start = (*lf)->lf_start;
389 *lf = lock;
390 lf = &(*lf)->lf_next;
391
392 lf_move_blocked(lock, adjacent);
393
394 FREE(adjacent, M_LOCKF);
395 continue;
396 }
397 /* If the lock starts adjacent to us, we can coalesce it */
398 if (lock->lf_end != -1 &&
399 (lock->lf_end + 1) == (*lf)->lf_start) {
400 struct lockf *adjacent = *lf;
401
402 LOCKF_DEBUG(0, "lf_coalesce_adjacent: coalesce adjacent following\n");
403 lock->lf_end = (*lf)->lf_end;
404 lock->lf_next = (*lf)->lf_next;
405 lf = &lock->lf_next;
406
407 lf_move_blocked(lock, adjacent);
408
409 FREE(adjacent, M_LOCKF);
410 continue;
411 }
412
413 /* no matching conditions; go on to next lock */
414 lf = &(*lf)->lf_next;
415 }
416 }
417
418
419 /*
420 * lf_setlock
421 *
422 * Description: Set a byte-range lock.
423 *
424 * Parameters: lock The lock structure describing the lock
425 * to be set; allocated by the caller, it
426 * will be linked into the lock list if
427 * the set is successful, and freed if the
428 * set is unsuccessful.
429 *
430 * Returns: 0 Success
431 * EAGAIN
432 * EDEADLK
433 * lf_split:ENOLCK
434 * lf_clearlock:ENOLCK
435 * msleep:EINTR
436 *
437 * Notes: We add the lock to the provisional lock list. We do not
438 * coalesce at this time; this has implications for other lock
439 * requestors in the blocker search mechanism.
440 */
441 static int
442 lf_setlock(struct lockf *lock)
443 {
444 struct lockf *block;
445 struct lockf **head = lock->lf_head;
446 struct lockf **prev, *overlap, *ltmp;
447 static char lockstr[] = "lockf";
448 int priority, needtolink, error;
449 struct vnode *vp = lock->lf_vnode;
450 overlap_t ovcase;
451
452 #ifdef LOCKF_DEBUGGING
453 if (lockf_debug & 1) {
454 lf_print("lf_setlock", lock);
455 lf_printlist("lf_setlock(in)", lock);
456 }
457 #endif /* LOCKF_DEBUGGING */
458
459 /*
460 * Set the priority
461 */
462 priority = PLOCK;
463 if (lock->lf_type == F_WRLCK)
464 priority += 4;
465 priority |= PCATCH;
466 /*
467 * Scan lock list for this file looking for locks that would block us.
468 */
469 while ((block = lf_getblock(lock, -1))) {
470 /*
471 * Free the structure and return if nonblocking.
472 */
473 if ((lock->lf_flags & F_WAIT) == 0) {
474 FREE(lock, M_LOCKF);
475 return (EAGAIN);
476 }
477
478 /*
479 * We are blocked. Since flock style locks cover
480 * the whole file, there is no chance for deadlock.
481 * For byte-range locks we must check for deadlock.
482 *
483 * Deadlock detection is done by looking through the
484 * wait channels to see if there are any cycles that
485 * involve us. MAXDEPTH is set just to make sure we
486 * do not go off into neverland.
487 */
488 if ((lock->lf_flags & F_POSIX) &&
489 (block->lf_flags & F_POSIX)) {
490 struct proc *wproc, *bproc;
491 struct uthread *ut;
492 struct lockf *waitblock;
493 int i = 0;
494
495 /* The block is waiting on something */
496 wproc = (struct proc *)block->lf_id;
497 proc_lock(wproc);
498 TAILQ_FOREACH(ut, &wproc->p_uthlist, uu_list) {
499 /*
500 * While the thread is asleep (uu_wchan != 0)
501 * in this code (uu_wmesg == lockstr)
502 * and we have not exceeded the maximum cycle
503 * depth (i < maxlockdepth), then check for a
504 * cycle to see if the lock is blocked behind
505 * someone blocked behind us.
506 */
507 while (((waitblock = (struct lockf *)ut->uu_wchan) != NULL) &&
508 ut->uu_wmesg == lockstr &&
509 (i++ < maxlockdepth)) {
510 waitblock = (struct lockf *)ut->uu_wchan;
511 /*
512 * Get the lock blocking the lock
513 * which would block us, and make
514 * certain it hasn't come unblocked
515 * (been granted, e.g. between the time
516 * we called lf_getblock, and the time
517 * we successfully acquired the
518 * proc_lock).
519 */
520 waitblock = waitblock->lf_next;
521 if (waitblock == NULL)
522 break;
523
524 /*
525 * Make sure it's an advisory range
526 * lock and not an overall file lock;
527 * if we mix lock types, it's our own
528 * fault.
529 */
530 if ((waitblock->lf_flags & F_POSIX) == 0)
531 break;
532
533 /*
534 * If the owner of the lock that's
535 * blocking a lock that's blocking us
536 * getting the requested lock, then we
537 * would deadlock, so error out.
538 */
539 bproc = (struct proc *)waitblock->lf_id;
540 if (bproc == (struct proc *)lock->lf_id) {
541 proc_unlock(wproc);
542 FREE(lock, M_LOCKF);
543 return (EDEADLK);
544 }
545 }
546 }
547 proc_unlock(wproc);
548 }
549
550 /*
551 * For flock type locks, we must first remove
552 * any shared locks that we hold before we sleep
553 * waiting for an exclusive lock.
554 */
555 if ((lock->lf_flags & F_FLOCK) &&
556 lock->lf_type == F_WRLCK) {
557 lock->lf_type = F_UNLCK;
558 if ((error = lf_clearlock(lock)) != 0) {
559 FREE(lock, M_LOCKF);
560 return (error);
561 }
562 lock->lf_type = F_WRLCK;
563 }
564 /*
565 * Add our lock to the blocked list and sleep until we're free.
566 * Remember who blocked us (for deadlock detection).
567 */
568 lock->lf_next = block;
569 TAILQ_INSERT_TAIL(&block->lf_blkhd, lock, lf_block);
570
571 if ( !(lock->lf_flags & F_FLOCK))
572 block->lf_flags &= ~F_WAKE1_SAFE;
573
574 #ifdef LOCKF_DEBUGGING
575 if (lockf_debug & 1) {
576 lf_print("lf_setlock: blocking on", block);
577 lf_printlist("lf_setlock(block)", block);
578 }
579 #endif /* LOCKF_DEBUGGING */
580 error = msleep(lock, &vp->v_lock, priority, lockstr, 0);
581
582 if (!TAILQ_EMPTY(&lock->lf_blkhd)) {
583 if ((block = lf_getblock(lock, -1))) {
584 lf_move_blocked(block, lock);
585 }
586 }
587
588 if (error == 0 && (lock->lf_flags & F_ABORT) != 0)
589 error = EBADF;
590
591 if (error) { /* XXX */
592 /*
593 * We may have been awakened by a signal and/or by a
594 * debugger continuing us (in which cases we must remove
595 * ourselves from the blocked list) and/or by another
596 * process releasing a lock (in which case we have
597 * already been removed from the blocked list and our
598 * lf_next field set to NOLOCKF).
599 */
600 if (lock->lf_next) {
601 TAILQ_REMOVE(&lock->lf_next->lf_blkhd, lock, lf_block);
602 lock->lf_next = NOLOCKF;
603 }
604 if (!TAILQ_EMPTY(&lock->lf_blkhd))
605 lf_wakelock(lock, TRUE);
606
607 FREE(lock, M_LOCKF);
608 return (error);
609 } /* XXX */
610 }
611 /*
612 * No blocks!! Add the lock. Note that we will
613 * downgrade or upgrade any overlapping locks this
614 * process already owns.
615 *
616 * Skip over locks owned by other processes.
617 * Handle any locks that overlap and are owned by ourselves.
618 */
619 prev = head;
620 block = *head;
621 needtolink = 1;
622 for (;;) {
623 ovcase = lf_findoverlap(block, lock, SELF, &prev, &overlap);
624 if (ovcase)
625 block = overlap->lf_next;
626 /*
627 * Six cases:
628 * 0) no overlap
629 * 1) overlap == lock
630 * 2) overlap contains lock
631 * 3) lock contains overlap
632 * 4) overlap starts before lock
633 * 5) overlap ends after lock
634 */
635 switch (ovcase) {
636 case OVERLAP_NONE:
637 if (needtolink) {
638 *prev = lock;
639 lock->lf_next = overlap;
640 }
641 break;
642
643 case OVERLAP_EQUALS_LOCK:
644 /*
645 * If downgrading lock, others may be
646 * able to acquire it.
647 */
648 if (lock->lf_type == F_RDLCK &&
649 overlap->lf_type == F_WRLCK)
650 lf_wakelock(overlap, TRUE);
651 overlap->lf_type = lock->lf_type;
652 FREE(lock, M_LOCKF);
653 lock = overlap; /* for lf_coalesce_adjacent() */
654 break;
655
656 case OVERLAP_CONTAINS_LOCK:
657 /*
658 * Check for common starting point and different types.
659 */
660 if (overlap->lf_type == lock->lf_type) {
661 FREE(lock, M_LOCKF);
662 lock = overlap; /* for lf_coalesce_adjacent() */
663 break;
664 }
665 if (overlap->lf_start == lock->lf_start) {
666 *prev = lock;
667 lock->lf_next = overlap;
668 overlap->lf_start = lock->lf_end + 1;
669 } else {
670 /*
671 * If we can't split the lock, we can't
672 * grant it. Claim a system limit for the
673 * resource shortage.
674 */
675 if (lf_split(overlap, lock)) {
676 FREE(lock, M_LOCKF);
677 return (ENOLCK);
678 }
679 }
680 lf_wakelock(overlap, TRUE);
681 break;
682
683 case OVERLAP_CONTAINED_BY_LOCK:
684 /*
685 * If downgrading lock, others may be able to
686 * acquire it, otherwise take the list.
687 */
688 if (lock->lf_type == F_RDLCK &&
689 overlap->lf_type == F_WRLCK) {
690 lf_wakelock(overlap, TRUE);
691 } else {
692 while (!TAILQ_EMPTY(&overlap->lf_blkhd)) {
693 ltmp = TAILQ_FIRST(&overlap->lf_blkhd);
694 TAILQ_REMOVE(&overlap->lf_blkhd, ltmp,
695 lf_block);
696 TAILQ_INSERT_TAIL(&lock->lf_blkhd,
697 ltmp, lf_block);
698 ltmp->lf_next = lock;
699 }
700 }
701 /*
702 * Add the new lock if necessary and delete the overlap.
703 */
704 if (needtolink) {
705 *prev = lock;
706 lock->lf_next = overlap->lf_next;
707 prev = &lock->lf_next;
708 needtolink = 0;
709 } else
710 *prev = overlap->lf_next;
711 FREE(overlap, M_LOCKF);
712 continue;
713
714 case OVERLAP_STARTS_BEFORE_LOCK:
715 /*
716 * Add lock after overlap on the list.
717 */
718 lock->lf_next = overlap->lf_next;
719 overlap->lf_next = lock;
720 overlap->lf_end = lock->lf_start - 1;
721 prev = &lock->lf_next;
722 lf_wakelock(overlap, TRUE);
723 needtolink = 0;
724 continue;
725
726 case OVERLAP_ENDS_AFTER_LOCK:
727 /*
728 * Add the new lock before overlap.
729 */
730 if (needtolink) {
731 *prev = lock;
732 lock->lf_next = overlap;
733 }
734 overlap->lf_start = lock->lf_end + 1;
735 lf_wakelock(overlap, TRUE);
736 break;
737 }
738 break;
739 }
740 /* Coalesce adjacent locks with identical attributes */
741 lf_coalesce_adjacent(lock);
742 #ifdef LOCKF_DEBUGGING
743 if (lockf_debug & 1) {
744 lf_print("lf_setlock: got the lock", lock);
745 lf_printlist("lf_setlock(out)", lock);
746 }
747 #endif /* LOCKF_DEBUGGING */
748 return (0);
749 }
750
751
752 /*
753 * lf_clearlock
754 *
755 * Description: Remove a byte-range lock on an vnode. Generally, find the
756 * lock (or an overlap to that lock) and remove it (or shrink
757 * it), then wakeup anyone we can.
758 *
759 * Parameters: unlock The lock to clear
760 *
761 * Returns: 0 Success
762 * lf_split:ENOLCK
763 *
764 * Notes: A caller may unlock all the locks owned by the caller by
765 * specifying the entire file range; locks owned by other
766 * callers are not effected by this operation.
767 */
768 static int
769 lf_clearlock(struct lockf *unlock)
770 {
771 struct lockf **head = unlock->lf_head;
772 struct lockf *lf = *head;
773 struct lockf *overlap, **prev;
774 overlap_t ovcase;
775
776 if (lf == NOLOCKF)
777 return (0);
778 #ifdef LOCKF_DEBUGGING
779 if (unlock->lf_type != F_UNLCK)
780 panic("lf_clearlock: bad type");
781 if (lockf_debug & 1)
782 lf_print("lf_clearlock", unlock);
783 #endif /* LOCKF_DEBUGGING */
784 prev = head;
785 while ((ovcase = lf_findoverlap(lf, unlock, SELF, &prev, &overlap)) != OVERLAP_NONE) {
786 /*
787 * Wakeup the list of locks to be retried.
788 */
789 lf_wakelock(overlap, FALSE);
790
791 switch (ovcase) {
792 case OVERLAP_NONE: /* satisfy compiler enum/switch */
793 break;
794
795 case OVERLAP_EQUALS_LOCK:
796 *prev = overlap->lf_next;
797 FREE(overlap, M_LOCKF);
798 break;
799
800 case OVERLAP_CONTAINS_LOCK: /* split it */
801 if (overlap->lf_start == unlock->lf_start) {
802 overlap->lf_start = unlock->lf_end + 1;
803 break;
804 }
805 /*
806 * If we can't split the lock, we can't grant it.
807 * Claim a system limit for the resource shortage.
808 */
809 if (lf_split(overlap, unlock))
810 return (ENOLCK);
811 overlap->lf_next = unlock->lf_next;
812 break;
813
814 case OVERLAP_CONTAINED_BY_LOCK:
815 *prev = overlap->lf_next;
816 lf = overlap->lf_next;
817 FREE(overlap, M_LOCKF);
818 continue;
819
820 case OVERLAP_STARTS_BEFORE_LOCK:
821 overlap->lf_end = unlock->lf_start - 1;
822 prev = &overlap->lf_next;
823 lf = overlap->lf_next;
824 continue;
825
826 case OVERLAP_ENDS_AFTER_LOCK:
827 overlap->lf_start = unlock->lf_end + 1;
828 break;
829 }
830 break;
831 }
832 #ifdef LOCKF_DEBUGGING
833 if (lockf_debug & 1)
834 lf_printlist("lf_clearlock", unlock);
835 #endif /* LOCKF_DEBUGGING */
836 return (0);
837 }
838
839
840 /*
841 * lf_getlock
842 *
843 * Description: Check whether there is a blocking lock, and if so return
844 * its process identifier into the lock being requested.
845 *
846 * Parameters: lock Pointer to lock to test for blocks
847 * fl Pointer to flock structure to receive
848 * the blocking lock information, if a
849 * blocking lock is found.
850 * matchpid -1, or pid value to match in lookup.
851 *
852 * Returns: 0 Success
853 *
854 * Implicit Returns:
855 * *fl Contents modified to reflect the
856 * blocking lock, if one is found; not
857 * modified otherwise
858 *
859 * Notes: fl->l_pid will be (-1) for file locks and will only be set to
860 * the blocking process ID for advisory record locks.
861 */
862 static int
863 lf_getlock(struct lockf *lock, struct flock *fl, pid_t matchpid)
864 {
865 struct lockf *block;
866
867 #ifdef LOCKF_DEBUGGING
868 if (lockf_debug & 1)
869 lf_print("lf_getlock", lock);
870 #endif /* LOCKF_DEBUGGING */
871
872 if ((block = lf_getblock(lock, matchpid))) {
873 fl->l_type = block->lf_type;
874 fl->l_whence = SEEK_SET;
875 fl->l_start = block->lf_start;
876 if (block->lf_end == -1)
877 fl->l_len = 0;
878 else
879 fl->l_len = block->lf_end - block->lf_start + 1;
880 if (block->lf_flags & F_POSIX)
881 fl->l_pid = proc_pid((struct proc *)(block->lf_id));
882 else
883 fl->l_pid = -1;
884 } else {
885 fl->l_type = F_UNLCK;
886 }
887 return (0);
888 }
889
890 /*
891 * lf_getblock
892 *
893 * Description: Walk the list of locks for an inode and return the first
894 * blocking lock. A lock is considered blocking if we are not
895 * the lock owner; otherwise, we are permitted to upgrade or
896 * downgrade it, and it's not considered blocking.
897 *
898 * Parameters: lock The lock for which we are interested
899 * in obtaining the blocking lock, if any
900 * matchpid -1, or pid value to match in lookup.
901 *
902 * Returns: NOLOCKF No blocking lock exists
903 * !NOLOCKF The address of the blocking lock's
904 * struct lockf.
905 */
906 static struct lockf *
907 lf_getblock(struct lockf *lock, pid_t matchpid)
908 {
909 struct lockf **prev, *overlap, *lf = *(lock->lf_head);
910
911 for (prev = lock->lf_head;
912 lf_findoverlap(lf, lock, OTHERS, &prev, &overlap) != OVERLAP_NONE;
913 lf = overlap->lf_next) {
914 /*
915 * Found an overlap.
916 *
917 * If we're matching pids, and it's a record lock,
918 * but the pid doesn't match, then keep on looking ..
919 */
920 if (matchpid != -1 &&
921 (overlap->lf_flags & F_POSIX) != 0 &&
922 proc_pid((struct proc *)(overlap->lf_id)) != matchpid)
923 continue;
924 /*
925 * does it block us?
926 */
927 if ((lock->lf_type == F_WRLCK || overlap->lf_type == F_WRLCK))
928 return (overlap);
929 }
930 return (NOLOCKF);
931 }
932
933
934 /*
935 * lf_findoverlap
936 *
937 * Description: Walk the list of locks to find an overlapping lock (if any).
938 *
939 * Parameters: lf First lock on lock list
940 * lock The lock we are checking for an overlap
941 * check Check type
942 * prev pointer to pointer pointer to contain
943 * address of pointer to previous lock
944 * pointer to overlapping lock, if overlap
945 * overlap pointer to pointer to contain address
946 * of overlapping lock
947 *
948 * Returns: OVERLAP_NONE
949 * OVERLAP_EQUALS_LOCK
950 * OVERLAP_CONTAINS_LOCK
951 * OVERLAP_CONTAINED_BY_LOCK
952 * OVERLAP_STARTS_BEFORE_LOCK
953 * OVERLAP_ENDS_AFTER_LOCK
954 *
955 * Implicit Returns:
956 * *prev The address of the next pointer in the
957 * lock previous to the overlapping lock;
958 * this is generally used to relink the
959 * lock list, avoiding a second iteration.
960 * *overlap The pointer to the overlapping lock
961 * itself; this is used to return data in
962 * the check == OTHERS case, and for the
963 * caller to modify the overlapping lock,
964 * in the check == SELF case
965 *
966 * Note: This returns only the FIRST overlapping lock. There may be
967 * more than one. lf_getlock will return the first blocking lock,
968 * while lf_setlock will iterate over all overlapping locks to
969 *
970 * The check parameter can be SELF, meaning we are looking for
971 * overlapping locks owned by us, or it can be OTHERS, meaning
972 * we are looking for overlapping locks owned by someone else so
973 * we can report a blocking lock on an F_GETLK request.
974 *
975 * The value of *overlap and *prev are modified, even if there is
976 * no overlapping lock found; always check the return code.
977 */
978 static overlap_t
979 lf_findoverlap(struct lockf *lf, struct lockf *lock, int type,
980 struct lockf ***prev, struct lockf **overlap)
981 {
982 off_t start, end;
983 int found_self = 0;
984
985 *overlap = lf;
986 if (lf == NOLOCKF)
987 return (0);
988 #ifdef LOCKF_DEBUGGING
989 if (lockf_debug & 2)
990 lf_print("lf_findoverlap: looking for overlap in", lock);
991 #endif /* LOCKF_DEBUGGING */
992 start = lock->lf_start;
993 end = lock->lf_end;
994 while (lf != NOLOCKF) {
995 if (((type & SELF) && lf->lf_id != lock->lf_id) ||
996 ((type & OTHERS) && lf->lf_id == lock->lf_id)) {
997 /*
998 * Locks belonging to one process are adjacent on the
999 * list, so if we've found any locks belonging to us,
1000 * and we're now seeing something else, then we've
1001 * examined all "self" locks. Note that bailing out
1002 * here is quite important; for coalescing, we assume
1003 * numerically adjacent locks from the same owner to
1004 * be adjacent on the list.
1005 */
1006 if ((type & SELF) && found_self) {
1007 return OVERLAP_NONE;
1008 }
1009
1010 *prev = &lf->lf_next;
1011 *overlap = lf = lf->lf_next;
1012 continue;
1013 }
1014
1015 if ((type & SELF)) {
1016 found_self = 1;
1017 }
1018
1019 #ifdef LOCKF_DEBUGGING
1020 if (lockf_debug & 2)
1021 lf_print("\tchecking", lf);
1022 #endif /* LOCKF_DEBUGGING */
1023 /*
1024 * OK, check for overlap
1025 */
1026 if ((lf->lf_end != -1 && start > lf->lf_end) ||
1027 (end != -1 && lf->lf_start > end)) {
1028 /* Case 0 */
1029 LOCKF_DEBUG(2, "no overlap\n");
1030
1031 /*
1032 * NOTE: assumes that locks for the same process are
1033 * nonintersecting and ordered.
1034 */
1035 if ((type & SELF) && end != -1 && lf->lf_start > end)
1036 return (OVERLAP_NONE);
1037 *prev = &lf->lf_next;
1038 *overlap = lf = lf->lf_next;
1039 continue;
1040 }
1041 if ((lf->lf_start == start) && (lf->lf_end == end)) {
1042 LOCKF_DEBUG(2, "overlap == lock\n");
1043 return (OVERLAP_EQUALS_LOCK);
1044 }
1045 if ((lf->lf_start <= start) &&
1046 (end != -1) &&
1047 ((lf->lf_end >= end) || (lf->lf_end == -1))) {
1048 LOCKF_DEBUG(2, "overlap contains lock\n");
1049 return (OVERLAP_CONTAINS_LOCK);
1050 }
1051 if (start <= lf->lf_start &&
1052 (end == -1 ||
1053 (lf->lf_end != -1 && end >= lf->lf_end))) {
1054 LOCKF_DEBUG(2, "lock contains overlap\n");
1055 return (OVERLAP_CONTAINED_BY_LOCK);
1056 }
1057 if ((lf->lf_start < start) &&
1058 ((lf->lf_end >= start) || (lf->lf_end == -1))) {
1059 LOCKF_DEBUG(2, "overlap starts before lock\n");
1060 return (OVERLAP_STARTS_BEFORE_LOCK);
1061 }
1062 if ((lf->lf_start > start) &&
1063 (end != -1) &&
1064 ((lf->lf_end > end) || (lf->lf_end == -1))) {
1065 LOCKF_DEBUG(2, "overlap ends after lock\n");
1066 return (OVERLAP_ENDS_AFTER_LOCK);
1067 }
1068 panic("lf_findoverlap: default");
1069 }
1070 return (OVERLAP_NONE);
1071 }
1072
1073
1074 /*
1075 * lf_split
1076 *
1077 * Description: Split a lock and a contained region into two or three locks
1078 * as necessary.
1079 *
1080 * Parameters: lock1 Lock to split
1081 * lock2 Overlapping lock region requiring the
1082 * split (upgrade/downgrade/unlock)
1083 *
1084 * Returns: 0 Success
1085 * ENOLCK No memory for new lock
1086 *
1087 * Implicit Returns:
1088 * *lock1 Modified original lock
1089 * *lock2 Overlapping lock (inserted into list)
1090 * (new lock) Potential new lock inserted into list
1091 * if split results in 3 locks
1092 *
1093 * Notes: This operation can only fail if the split would result in three
1094 * locks, and there is insufficient memory to allocate the third
1095 * lock; in that case, neither of the locks will be modified.
1096 */
1097 static int
1098 lf_split(struct lockf *lock1, struct lockf *lock2)
1099 {
1100 struct lockf *splitlock;
1101
1102 #ifdef LOCKF_DEBUGGING
1103 if (lockf_debug & 2) {
1104 lf_print("lf_split", lock1);
1105 lf_print("splitting from", lock2);
1106 }
1107 #endif /* LOCKF_DEBUGGING */
1108 /*
1109 * Check to see if spliting into only two pieces.
1110 */
1111 if (lock1->lf_start == lock2->lf_start) {
1112 lock1->lf_start = lock2->lf_end + 1;
1113 lock2->lf_next = lock1;
1114 return (0);
1115 }
1116 if (lock1->lf_end == lock2->lf_end) {
1117 lock1->lf_end = lock2->lf_start - 1;
1118 lock2->lf_next = lock1->lf_next;
1119 lock1->lf_next = lock2;
1120 return (0);
1121 }
1122 /*
1123 * Make a new lock consisting of the last part of
1124 * the encompassing lock
1125 */
1126 MALLOC(splitlock, struct lockf *, sizeof *splitlock, M_LOCKF, M_WAITOK);
1127 if (splitlock == NULL)
1128 return (ENOLCK);
1129 bcopy(lock1, splitlock, sizeof *splitlock);
1130 splitlock->lf_start = lock2->lf_end + 1;
1131 TAILQ_INIT(&splitlock->lf_blkhd);
1132 lock1->lf_end = lock2->lf_start - 1;
1133 /*
1134 * OK, now link it in
1135 */
1136 splitlock->lf_next = lock1->lf_next;
1137 lock2->lf_next = splitlock;
1138 lock1->lf_next = lock2;
1139
1140 return (0);
1141 }
1142
1143
1144 /*
1145 * lf_wakelock
1146 *
1147 * Wakeup a blocklist in the case of a downgrade or unlock, since others
1148 * waiting on the lock may now be able to acquire it.
1149 *
1150 * Parameters: listhead Lock list head on which waiters may
1151 * have pending locks
1152 *
1153 * Returns: <void>
1154 *
1155 * Notes: This function iterates a list of locks and wakes all waiters,
1156 * rather than only waiters for the contended regions. Because
1157 * of this, for heavily contended files, this can result in a
1158 * "thundering herd" situation. Refactoring the code could make
1159 * this operation more efficient, if heavy contention ever results
1160 * in a real-world performance problem.
1161 */
1162 static void
1163 lf_wakelock(struct lockf *listhead, boolean_t force_all)
1164 {
1165 struct lockf *wakelock;
1166 boolean_t wake_all = TRUE;
1167
1168 if (force_all == FALSE && (listhead->lf_flags & F_WAKE1_SAFE))
1169 wake_all = FALSE;
1170
1171 while (!TAILQ_EMPTY(&listhead->lf_blkhd)) {
1172 wakelock = TAILQ_FIRST(&listhead->lf_blkhd);
1173 TAILQ_REMOVE(&listhead->lf_blkhd, wakelock, lf_block);
1174
1175 wakelock->lf_next = NOLOCKF;
1176 #ifdef LOCKF_DEBUGGING
1177 if (lockf_debug & 2)
1178 lf_print("lf_wakelock: awakening", wakelock);
1179 #endif /* LOCKF_DEBUGGING */
1180 if (wake_all == FALSE) {
1181 /*
1182 * If there are items on the list head block list,
1183 * move them to the wakelock list instead, and then
1184 * correct their lf_next pointers.
1185 */
1186 if (!TAILQ_EMPTY(&listhead->lf_blkhd)) {
1187 TAILQ_CONCAT(&wakelock->lf_blkhd, &listhead->lf_blkhd, lf_block);
1188
1189 struct lockf *tlock;
1190
1191 TAILQ_FOREACH(tlock, &wakelock->lf_blkhd, lf_block) {
1192 tlock->lf_next = wakelock;
1193 }
1194 }
1195 }
1196 wakeup(wakelock);
1197
1198 if (wake_all == FALSE)
1199 break;
1200 }
1201 }
1202
1203
1204 #ifdef LOCKF_DEBUGGING
1205 /*
1206 * lf_print DEBUG
1207 *
1208 * Print out a lock; lock information is prefixed by the string in 'tag'
1209 *
1210 * Parameters: tag A string tag for debugging
1211 * lock The lock whose information should be
1212 * displayed
1213 *
1214 * Returns: <void>
1215 */
1216 void
1217 lf_print(const char *tag, struct lockf *lock)
1218 {
1219 printf("%s: lock %p for ", tag, (void *)lock);
1220 if (lock->lf_flags & F_POSIX)
1221 printf("proc %ld", (long)((struct proc *)lock->lf_id)->p_pid);
1222 else
1223 printf("id %p", (void *)lock->lf_id);
1224 if (lock->lf_vnode != 0)
1225 printf(" in vno %p, %s, start 0x%016llx, end 0x%016llx",
1226 lock->lf_vnode,
1227 lock->lf_type == F_RDLCK ? "shared" :
1228 lock->lf_type == F_WRLCK ? "exclusive" :
1229 lock->lf_type == F_UNLCK ? "unlock" : "unknown",
1230 (intmax_t)lock->lf_start, (intmax_t)lock->lf_end);
1231 else
1232 printf(" %s, start 0x%016llx, end 0x%016llx",
1233 lock->lf_type == F_RDLCK ? "shared" :
1234 lock->lf_type == F_WRLCK ? "exclusive" :
1235 lock->lf_type == F_UNLCK ? "unlock" : "unknown",
1236 (intmax_t)lock->lf_start, (intmax_t)lock->lf_end);
1237 if (!TAILQ_EMPTY(&lock->lf_blkhd))
1238 printf(" block %p\n", (void *)TAILQ_FIRST(&lock->lf_blkhd));
1239 else
1240 printf("\n");
1241 }
1242
1243
1244 /*
1245 * lf_printlist DEBUG
1246 *
1247 * Print out a lock list for the vnode associated with 'lock'; lock information
1248 * is prefixed by the string in 'tag'
1249 *
1250 * Parameters: tag A string tag for debugging
1251 * lock The lock whose vnode's lock list should
1252 * be displayed
1253 *
1254 * Returns: <void>
1255 */
1256 void
1257 lf_printlist(const char *tag, struct lockf *lock)
1258 {
1259 struct lockf *lf, *blk;
1260
1261 if (lock->lf_vnode == 0)
1262 return;
1263
1264 printf("%s: Lock list for vno %p:\n",
1265 tag, lock->lf_vnode);
1266 for (lf = lock->lf_vnode->v_lockf; lf; lf = lf->lf_next) {
1267 printf("\tlock %p for ",(void *)lf);
1268 if (lf->lf_flags & F_POSIX)
1269 printf("proc %ld",
1270 (long)((struct proc *)lf->lf_id)->p_pid);
1271 else
1272 printf("id %p", (void *)lf->lf_id);
1273 printf(", %s, start 0x%016llx, end 0x%016llx",
1274 lf->lf_type == F_RDLCK ? "shared" :
1275 lf->lf_type == F_WRLCK ? "exclusive" :
1276 lf->lf_type == F_UNLCK ? "unlock" :
1277 "unknown", (intmax_t)lf->lf_start, (intmax_t)lf->lf_end);
1278 TAILQ_FOREACH(blk, &lf->lf_blkhd, lf_block) {
1279 printf("\n\t\tlock request %p for ", (void *)blk);
1280 if (blk->lf_flags & F_POSIX)
1281 printf("proc %ld",
1282 (long)((struct proc *)blk->lf_id)->p_pid);
1283 else
1284 printf("id %p", (void *)blk->lf_id);
1285 printf(", %s, start 0x%016llx, end 0x%016llx",
1286 blk->lf_type == F_RDLCK ? "shared" :
1287 blk->lf_type == F_WRLCK ? "exclusive" :
1288 blk->lf_type == F_UNLCK ? "unlock" :
1289 "unknown", (intmax_t)blk->lf_start,
1290 (intmax_t)blk->lf_end);
1291 if (!TAILQ_EMPTY(&blk->lf_blkhd))
1292 panic("lf_printlist: bad list");
1293 }
1294 printf("\n");
1295 }
1296 }
1297 #endif /* LOCKF_DEBUGGING */