2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 2008 Isilon Inc http://www.isilon.com/
5 * Authors: Doug Rabson <dfr@rabson.org>
6 * Developed with Red Inc: Alfred Perlstein <alfred@freebsd.org>
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * Copyright (c) 1982, 1986, 1989, 1993
31 * The Regents of the University of California. All rights reserved.
33 * This code is derived from software contributed to Berkeley by
34 * Scooter Morris at Genentech Inc.
36 * Redistribution and use in source and binary forms, with or without
37 * modification, are permitted provided that the following conditions
39 * 1. Redistributions of source code must retain the above copyright
40 * notice, this list of conditions and the following disclaimer.
41 * 2. Redistributions in binary form must reproduce the above copyright
42 * notice, this list of conditions and the following disclaimer in the
43 * documentation and/or other materials provided with the distribution.
44 * 3. Neither the name of the University nor the names of its contributors
45 * may be used to endorse or promote products derived from this software
46 * without specific prior written permission.
48 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
49 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
50 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
51 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
52 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
53 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
54 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
55 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
56 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
57 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
60 * @(#)ufs_lockf.c 8.3 (Berkeley) 1/6/94
63 #include <sys/cdefs.h>
64 __FBSDID("$FreeBSD$");
66 #include "opt_debug_lockf.h"
68 #include <sys/param.h>
69 #include <sys/systm.h>
72 #include <sys/kernel.h>
73 #include <sys/limits.h>
75 #include <sys/mount.h>
76 #include <sys/mutex.h>
81 #include <sys/unistd.h>
83 #include <sys/vnode.h>
84 #include <sys/malloc.h>
85 #include <sys/fcntl.h>
86 #include <sys/lockf.h>
87 #include <sys/taskqueue.h>
90 #include <sys/sysctl.h>
92 static int lockf_debug = 0; /* control debug output */
93 SYSCTL_INT(_debug, OID_AUTO, lockf_debug, CTLFLAG_RW, &lockf_debug, 0, "");
96 static MALLOC_DEFINE(M_LOCKF, "lockf", "Byte-range locking structures");
100 struct owner_vertex_list;
103 #define NOLOCKF (struct lockf_entry *)0
106 static void lf_init(void *);
107 static int lf_hash_owner(caddr_t, struct vnode *, struct flock *, int);
108 static int lf_owner_matches(struct lock_owner *, caddr_t, struct flock *,
110 static struct lockf_entry *
111 lf_alloc_lock(struct lock_owner *);
112 static int lf_free_lock(struct lockf_entry *);
113 static int lf_clearlock(struct lockf *, struct lockf_entry *);
114 static int lf_overlaps(struct lockf_entry *, struct lockf_entry *);
115 static int lf_blocks(struct lockf_entry *, struct lockf_entry *);
116 static void lf_free_edge(struct lockf_edge *);
117 static struct lockf_edge *
119 static void lf_alloc_vertex(struct lockf_entry *);
120 static int lf_add_edge(struct lockf_entry *, struct lockf_entry *);
121 static void lf_remove_edge(struct lockf_edge *);
122 static void lf_remove_outgoing(struct lockf_entry *);
123 static void lf_remove_incoming(struct lockf_entry *);
124 static int lf_add_outgoing(struct lockf *, struct lockf_entry *);
125 static int lf_add_incoming(struct lockf *, struct lockf_entry *);
126 static int lf_findoverlap(struct lockf_entry **, struct lockf_entry *,
128 static struct lockf_entry *
129 lf_getblock(struct lockf *, struct lockf_entry *);
130 static int lf_getlock(struct lockf *, struct lockf_entry *, struct flock *);
131 static void lf_insert_lock(struct lockf *, struct lockf_entry *);
132 static void lf_wakeup_lock(struct lockf *, struct lockf_entry *);
133 static void lf_update_dependancies(struct lockf *, struct lockf_entry *,
134 int all, struct lockf_entry_list *);
135 static void lf_set_start(struct lockf *, struct lockf_entry *, off_t,
136 struct lockf_entry_list*);
137 static void lf_set_end(struct lockf *, struct lockf_entry *, off_t,
138 struct lockf_entry_list*);
139 static int lf_setlock(struct lockf *, struct lockf_entry *,
140 struct vnode *, void **cookiep);
141 static int lf_cancel(struct lockf *, struct lockf_entry *, void *);
142 static void lf_split(struct lockf *, struct lockf_entry *,
143 struct lockf_entry *, struct lockf_entry_list *);
145 static int graph_reaches(struct owner_vertex *x, struct owner_vertex *y,
146 struct owner_vertex_list *path);
147 static void graph_check(struct owner_graph *g, int checkorder);
148 static void graph_print_vertices(struct owner_vertex_list *set);
150 static int graph_delta_forward(struct owner_graph *g,
151 struct owner_vertex *x, struct owner_vertex *y,
152 struct owner_vertex_list *delta);
153 static int graph_delta_backward(struct owner_graph *g,
154 struct owner_vertex *x, struct owner_vertex *y,
155 struct owner_vertex_list *delta);
156 static int graph_add_indices(int *indices, int n,
157 struct owner_vertex_list *set);
158 static int graph_assign_indices(struct owner_graph *g, int *indices,
159 int nextunused, struct owner_vertex_list *set);
160 static int graph_add_edge(struct owner_graph *g,
161 struct owner_vertex *x, struct owner_vertex *y);
162 static void graph_remove_edge(struct owner_graph *g,
163 struct owner_vertex *x, struct owner_vertex *y);
164 static struct owner_vertex *graph_alloc_vertex(struct owner_graph *g,
165 struct lock_owner *lo);
166 static void graph_free_vertex(struct owner_graph *g,
167 struct owner_vertex *v);
168 static struct owner_graph * graph_init(struct owner_graph *g);
170 static void lf_print(char *, struct lockf_entry *);
171 static void lf_printlist(char *, struct lockf_entry *);
172 static void lf_print_owner(struct lock_owner *);
176 * This structure is used to keep track of both local and remote lock
177 * owners. The lf_owner field of the struct lockf_entry points back at
178 * the lock owner structure. Each possible lock owner (local proc for
179 * POSIX fcntl locks, local file for BSD flock locks or <pid,sysid>
180 * pair for remote locks) is represented by a unique instance of
183 * If a lock owner has a lock that blocks some other lock or a lock
184 * that is waiting for some other lock, it also has a vertex in the
188 * (s) locked by state->ls_lock
189 * (S) locked by lf_lock_states_lock
190 * (g) locked by lf_owner_graph_lock
191 * (c) const until freeing
193 #define LOCK_OWNER_HASH_SIZE 256
196 LIST_ENTRY(lock_owner) lo_link; /* (l) hash chain */
197 int lo_refs; /* (l) Number of locks referring to this */
198 int lo_flags; /* (c) Flags passwd to lf_advlock */
199 caddr_t lo_id; /* (c) Id value passed to lf_advlock */
200 pid_t lo_pid; /* (c) Process Id of the lock owner */
201 int lo_sysid; /* (c) System Id of the lock owner */
202 int lo_hash; /* (c) Used to lock the appropriate chain */
203 struct owner_vertex *lo_vertex; /* (g) entry in deadlock graph */
206 LIST_HEAD(lock_owner_list, lock_owner);
208 struct lock_owner_chain {
210 struct lock_owner_list list;
213 static struct sx lf_lock_states_lock;
214 static struct lockf_list lf_lock_states; /* (S) */
215 static struct lock_owner_chain lf_lock_owners[LOCK_OWNER_HASH_SIZE];
218 * Structures for deadlock detection.
220 * We have two types of directed graph, the first is the set of locks,
221 * both active and pending on a vnode. Within this graph, active locks
222 * are terminal nodes in the graph (i.e. have no out-going
223 * edges). Pending locks have out-going edges to each blocking active
224 * lock that prevents the lock from being granted and also to each
225 * older pending lock that would block them if it was active. The
226 * graph for each vnode is naturally acyclic; new edges are only ever
227 * added to or from new nodes (either new pending locks which only add
228 * out-going edges or new active locks which only add in-coming edges)
229 * therefore they cannot create loops in the lock graph.
231 * The second graph is a global graph of lock owners. Each lock owner
232 * is a vertex in that graph and an edge is added to the graph
233 * whenever an edge is added to a vnode graph, with end points
234 * corresponding to owner of the new pending lock and the owner of the
235 * lock upon which it waits. In order to prevent deadlock, we only add
236 * an edge to this graph if the new edge would not create a cycle.
238 * The lock owner graph is topologically sorted, i.e. if a node has
239 * any outgoing edges, then it has an order strictly less than any
240 * node to which it has an outgoing edge. We preserve this ordering
241 * (and detect cycles) on edge insertion using Algorithm PK from the
242 * paper "A Dynamic Topological Sort Algorithm for Directed Acyclic
243 * Graphs" (ACM Journal of Experimental Algorithms, Vol 11, Article
249 LIST_ENTRY(owner_edge) e_outlink; /* (g) link from's out-edge list */
250 LIST_ENTRY(owner_edge) e_inlink; /* (g) link to's in-edge list */
251 int e_refs; /* (g) number of times added */
252 struct owner_vertex *e_from; /* (c) out-going from here */
253 struct owner_vertex *e_to; /* (c) in-coming to here */
255 LIST_HEAD(owner_edge_list, owner_edge);
257 struct owner_vertex {
258 TAILQ_ENTRY(owner_vertex) v_link; /* (g) workspace for edge insertion */
259 uint32_t v_gen; /* (g) workspace for edge insertion */
260 int v_order; /* (g) order of vertex in graph */
261 struct owner_edge_list v_outedges;/* (g) list of out-edges */
262 struct owner_edge_list v_inedges; /* (g) list of in-edges */
263 struct lock_owner *v_owner; /* (c) corresponding lock owner */
265 TAILQ_HEAD(owner_vertex_list, owner_vertex);
268 struct owner_vertex** g_vertices; /* (g) pointers to vertices */
269 int g_size; /* (g) number of vertices */
270 int g_space; /* (g) space allocated for vertices */
271 int *g_indexbuf; /* (g) workspace for loop detection */
272 uint32_t g_gen; /* (g) increment when re-ordering */
275 static struct sx lf_owner_graph_lock;
276 static struct owner_graph lf_owner_graph;
279 * Initialise various structures and locks.
286 sx_init(&lf_lock_states_lock, "lock states lock");
287 LIST_INIT(&lf_lock_states);
289 for (i = 0; i < LOCK_OWNER_HASH_SIZE; i++) {
290 sx_init(&lf_lock_owners[i].lock, "lock owners lock");
291 LIST_INIT(&lf_lock_owners[i].list);
294 sx_init(&lf_owner_graph_lock, "owner graph lock");
295 graph_init(&lf_owner_graph);
297 SYSINIT(lf_init, SI_SUB_LOCK, SI_ORDER_FIRST, lf_init, NULL);
300 * Generate a hash value for a lock owner.
303 lf_hash_owner(caddr_t id, struct vnode *vp, struct flock *fl, int flags)
307 if (flags & F_REMOTE) {
308 h = HASHSTEP(0, fl->l_pid);
309 h = HASHSTEP(h, fl->l_sysid);
310 } else if (flags & F_FLOCK) {
311 h = ((uintptr_t) id) >> 7;
313 h = ((uintptr_t) vp) >> 7;
316 return (h % LOCK_OWNER_HASH_SIZE);
320 * Return true if a lock owner matches the details passed to
324 lf_owner_matches(struct lock_owner *lo, caddr_t id, struct flock *fl,
327 if (flags & F_REMOTE) {
328 return lo->lo_pid == fl->l_pid
329 && lo->lo_sysid == fl->l_sysid;
331 return lo->lo_id == id;
335 static struct lockf_entry *
336 lf_alloc_lock(struct lock_owner *lo)
338 struct lockf_entry *lf;
340 lf = malloc(sizeof(struct lockf_entry), M_LOCKF, M_WAITOK|M_ZERO);
344 printf("Allocated lock %p\n", lf);
347 sx_xlock(&lf_lock_owners[lo->lo_hash].lock);
349 sx_xunlock(&lf_lock_owners[lo->lo_hash].lock);
357 lf_free_lock(struct lockf_entry *lock)
359 struct sx *chainlock;
361 KASSERT(lock->lf_refs > 0, ("lockf_entry negative ref count %p", lock));
362 if (--lock->lf_refs > 0)
365 * Adjust the lock_owner reference count and
366 * reclaim the entry if this is the last lock
369 struct lock_owner *lo = lock->lf_owner;
371 KASSERT(LIST_EMPTY(&lock->lf_outedges),
372 ("freeing lock with dependencies"));
373 KASSERT(LIST_EMPTY(&lock->lf_inedges),
374 ("freeing lock with dependants"));
375 chainlock = &lf_lock_owners[lo->lo_hash].lock;
377 KASSERT(lo->lo_refs > 0, ("lock owner refcount"));
379 if (lo->lo_refs == 0) {
382 printf("lf_free_lock: freeing lock owner %p\n",
386 sx_xlock(&lf_owner_graph_lock);
387 graph_free_vertex(&lf_owner_graph,
389 sx_xunlock(&lf_owner_graph_lock);
391 LIST_REMOVE(lo, lo_link);
395 printf("Freed lock owner %p\n", lo);
398 sx_unlock(chainlock);
400 if ((lock->lf_flags & F_REMOTE) && lock->lf_vnode) {
401 vrele(lock->lf_vnode);
402 lock->lf_vnode = NULL;
406 printf("Freed lock %p\n", lock);
413 * Advisory record locking support
416 lf_advlockasync(struct vop_advlockasync_args *ap, struct lockf **statep,
420 struct flock *fl = ap->a_fl;
421 struct lockf_entry *lock;
422 struct vnode *vp = ap->a_vp;
423 caddr_t id = ap->a_id;
424 int flags = ap->a_flags;
426 struct lock_owner *lo;
427 off_t start, end, oadd;
431 * Handle the F_UNLKSYS case first - no need to mess about
432 * creating a lock owner for this one.
434 if (ap->a_op == F_UNLCKSYS) {
435 lf_clearremotesys(fl->l_sysid);
440 * Convert the flock structure into a start and end.
442 switch (fl->l_whence) {
446 * Caller is responsible for adding any necessary offset
447 * when SEEK_CUR is used.
453 if (size > OFF_MAX ||
454 (fl->l_start > 0 && size > OFF_MAX - fl->l_start))
456 start = size + fl->l_start;
471 } else if (fl->l_len == 0) {
474 oadd = fl->l_len - 1;
475 if (oadd > OFF_MAX - start)
483 * Avoid the common case of unlocking when inode has no locks.
485 if (ap->a_op != F_SETLK && (*statep) == NULL) {
487 if ((*statep) == NULL) {
488 fl->l_type = F_UNLCK;
496 * Map our arguments to an existing lock owner or create one
497 * if this is the first time we have seen this owner.
499 hash = lf_hash_owner(id, vp, fl, flags);
500 sx_xlock(&lf_lock_owners[hash].lock);
501 LIST_FOREACH(lo, &lf_lock_owners[hash].list, lo_link)
502 if (lf_owner_matches(lo, id, fl, flags))
506 * We initialise the lock with a reference
507 * count which matches the new lockf_entry
508 * structure created below.
510 lo = malloc(sizeof(struct lock_owner), M_LOCKF,
514 printf("Allocated lock owner %p\n", lo);
518 lo->lo_flags = flags;
521 if (flags & F_REMOTE) {
522 lo->lo_pid = fl->l_pid;
523 lo->lo_sysid = fl->l_sysid;
524 } else if (flags & F_FLOCK) {
528 struct proc *p = (struct proc *) id;
529 lo->lo_pid = p->p_pid;
532 lo->lo_vertex = NULL;
535 if (lockf_debug & 1) {
536 printf("lf_advlockasync: new lock owner %p ", lo);
542 LIST_INSERT_HEAD(&lf_lock_owners[hash].list, lo, lo_link);
545 * We have seen this lock owner before, increase its
546 * reference count to account for the new lockf_entry
547 * structure we create below.
551 sx_xunlock(&lf_lock_owners[hash].lock);
554 * Create the lockf structure. We initialise the lf_owner
555 * field here instead of in lf_alloc_lock() to avoid paying
556 * the lf_lock_owners_lock tax twice.
558 lock = lf_alloc_lock(NULL);
560 lock->lf_start = start;
564 if (flags & F_REMOTE) {
566 * For remote locks, the caller may release its ref to
567 * the vnode at any time - we have to ref it here to
568 * prevent it from being recycled unexpectedly.
573 lock->lf_type = fl->l_type;
574 LIST_INIT(&lock->lf_outedges);
575 LIST_INIT(&lock->lf_inedges);
576 lock->lf_async_task = ap->a_task;
577 lock->lf_flags = ap->a_flags;
580 * Do the requested operation. First find our state structure
581 * and create a new one if necessary - the caller's *statep
582 * variable and the state's ls_threads count is protected by
583 * the vnode interlock.
586 if (VN_IS_DOOMED(vp)) {
593 * Allocate a state structure if necessary.
601 ls = malloc(sizeof(struct lockf), M_LOCKF, M_WAITOK|M_ZERO);
602 sx_init(&ls->ls_lock, "ls_lock");
603 LIST_INIT(&ls->ls_active);
604 LIST_INIT(&ls->ls_pending);
607 sx_xlock(&lf_lock_states_lock);
608 LIST_INSERT_HEAD(&lf_lock_states, ls, ls_link);
609 sx_xunlock(&lf_lock_states_lock);
612 * Cope if we lost a race with some other thread while
613 * trying to allocate memory.
616 if (VN_IS_DOOMED(vp)) {
618 sx_xlock(&lf_lock_states_lock);
619 LIST_REMOVE(ls, ls_link);
620 sx_xunlock(&lf_lock_states_lock);
621 sx_destroy(&ls->ls_lock);
626 if ((*statep) == NULL) {
627 state = *statep = ls;
631 MPASS(state->ls_threads >= 0);
635 sx_xlock(&lf_lock_states_lock);
636 LIST_REMOVE(ls, ls_link);
637 sx_xunlock(&lf_lock_states_lock);
638 sx_destroy(&ls->ls_lock);
642 MPASS(state->ls_threads >= 0);
647 sx_xlock(&state->ls_lock);
649 * Recheck the doomed vnode after state->ls_lock is
650 * locked. lf_purgelocks() requires that no new threads add
651 * pending locks when vnode is marked by VIRF_DOOMED flag.
653 if (VN_IS_DOOMED(vp)) {
655 MPASS(state->ls_threads > 0);
659 sx_xunlock(&state->ls_lock);
666 error = lf_setlock(state, lock, vp, ap->a_cookiep);
670 error = lf_clearlock(state, lock);
675 error = lf_getlock(state, lock, fl);
681 error = lf_cancel(state, lock, *ap->a_cookiep);
695 * Check for some can't happen stuff. In this case, the active
696 * lock list becoming disordered or containing mutually
697 * blocking locks. We also check the pending list for locks
698 * which should be active (i.e. have no out-going edges).
700 LIST_FOREACH(lock, &state->ls_active, lf_link) {
701 struct lockf_entry *lf;
702 if (LIST_NEXT(lock, lf_link))
703 KASSERT((lock->lf_start
704 <= LIST_NEXT(lock, lf_link)->lf_start),
705 ("locks disordered"));
706 LIST_FOREACH(lf, &state->ls_active, lf_link) {
709 KASSERT(!lf_blocks(lock, lf),
710 ("two conflicting active locks"));
711 if (lock->lf_owner == lf->lf_owner)
712 KASSERT(!lf_overlaps(lock, lf),
713 ("two overlapping locks from same owner"));
716 LIST_FOREACH(lock, &state->ls_pending, lf_link) {
717 KASSERT(!LIST_EMPTY(&lock->lf_outedges),
718 ("pending lock which should be active"));
721 sx_xunlock(&state->ls_lock);
724 MPASS(state->ls_threads > 0);
726 if (state->ls_threads != 0) {
731 if (error == EDOOFUS) {
732 KASSERT(ap->a_op == F_SETLK, ("EDOOFUS"));
739 lf_advlock(struct vop_advlock_args *ap, struct lockf **statep, u_quad_t size)
741 struct vop_advlockasync_args a;
747 a.a_flags = ap->a_flags;
751 return (lf_advlockasync(&a, statep, size));
755 lf_purgelocks(struct vnode *vp, struct lockf **statep)
758 struct lockf_entry *lock, *nlock;
761 * For this to work correctly, the caller must ensure that no
762 * other threads enter the locking system for this vnode,
763 * e.g. by checking VIRF_DOOMED. We wake up any threads that are
764 * sleeping waiting for locks on this vnode and then free all
765 * the remaining locks.
768 KASSERT(VN_IS_DOOMED(vp),
769 ("lf_purgelocks: vp %p has not vgone yet", vp));
776 if (LIST_EMPTY(&state->ls_active) && state->ls_threads == 0) {
777 KASSERT(LIST_EMPTY(&state->ls_pending),
778 ("freeing state with pending locks"));
782 MPASS(state->ls_threads >= 0);
786 sx_xlock(&state->ls_lock);
787 sx_xlock(&lf_owner_graph_lock);
788 LIST_FOREACH_SAFE(lock, &state->ls_pending, lf_link, nlock) {
789 LIST_REMOVE(lock, lf_link);
790 lf_remove_outgoing(lock);
791 lf_remove_incoming(lock);
794 * If its an async lock, we can just free it
795 * here, otherwise we let the sleeping thread
798 if (lock->lf_async_task) {
801 lock->lf_flags |= F_INTR;
805 sx_xunlock(&lf_owner_graph_lock);
806 sx_xunlock(&state->ls_lock);
809 * Wait for all other threads, sleeping and otherwise
813 while (state->ls_threads > 1)
814 msleep(state, VI_MTX(vp), 0, "purgelocks", 0);
818 * We can just free all the active locks since they
819 * will have no dependencies (we removed them all
820 * above). We don't need to bother locking since we
821 * are the last thread using this state structure.
823 KASSERT(LIST_EMPTY(&state->ls_pending),
824 ("lock pending for %p", state));
825 LIST_FOREACH_SAFE(lock, &state->ls_active, lf_link, nlock) {
826 LIST_REMOVE(lock, lf_link);
830 sx_xlock(&lf_lock_states_lock);
831 LIST_REMOVE(state, ls_link);
832 sx_xunlock(&lf_lock_states_lock);
833 sx_destroy(&state->ls_lock);
834 free(state, M_LOCKF);
838 * Return non-zero if locks 'x' and 'y' overlap.
841 lf_overlaps(struct lockf_entry *x, struct lockf_entry *y)
844 return (x->lf_start <= y->lf_end && x->lf_end >= y->lf_start);
848 * Return non-zero if lock 'x' is blocked by lock 'y' (or vice versa).
851 lf_blocks(struct lockf_entry *x, struct lockf_entry *y)
854 return x->lf_owner != y->lf_owner
855 && (x->lf_type == F_WRLCK || y->lf_type == F_WRLCK)
856 && lf_overlaps(x, y);
860 * Allocate a lock edge from the free list
862 static struct lockf_edge *
866 return (malloc(sizeof(struct lockf_edge), M_LOCKF, M_WAITOK|M_ZERO));
873 lf_free_edge(struct lockf_edge *e)
880 * Ensure that the lock's owner has a corresponding vertex in the
884 lf_alloc_vertex(struct lockf_entry *lock)
886 struct owner_graph *g = &lf_owner_graph;
888 if (!lock->lf_owner->lo_vertex)
889 lock->lf_owner->lo_vertex =
890 graph_alloc_vertex(g, lock->lf_owner);
894 * Attempt to record an edge from lock x to lock y. Return EDEADLK if
895 * the new edge would cause a cycle in the owner graph.
898 lf_add_edge(struct lockf_entry *x, struct lockf_entry *y)
900 struct owner_graph *g = &lf_owner_graph;
901 struct lockf_edge *e;
905 LIST_FOREACH(e, &x->lf_outedges, le_outlink)
906 KASSERT(e->le_to != y, ("adding lock edge twice"));
910 * Make sure the two owners have entries in the owner graph.
915 error = graph_add_edge(g, x->lf_owner->lo_vertex,
916 y->lf_owner->lo_vertex);
921 LIST_INSERT_HEAD(&x->lf_outedges, e, le_outlink);
922 LIST_INSERT_HEAD(&y->lf_inedges, e, le_inlink);
930 * Remove an edge from the lock graph.
933 lf_remove_edge(struct lockf_edge *e)
935 struct owner_graph *g = &lf_owner_graph;
936 struct lockf_entry *x = e->le_from;
937 struct lockf_entry *y = e->le_to;
939 graph_remove_edge(g, x->lf_owner->lo_vertex, y->lf_owner->lo_vertex);
940 LIST_REMOVE(e, le_outlink);
941 LIST_REMOVE(e, le_inlink);
948 * Remove all out-going edges from lock x.
951 lf_remove_outgoing(struct lockf_entry *x)
953 struct lockf_edge *e;
955 while ((e = LIST_FIRST(&x->lf_outedges)) != NULL) {
961 * Remove all in-coming edges from lock x.
964 lf_remove_incoming(struct lockf_entry *x)
966 struct lockf_edge *e;
968 while ((e = LIST_FIRST(&x->lf_inedges)) != NULL) {
974 * Walk the list of locks for the file and create an out-going edge
975 * from lock to each blocking lock.
978 lf_add_outgoing(struct lockf *state, struct lockf_entry *lock)
980 struct lockf_entry *overlap;
983 LIST_FOREACH(overlap, &state->ls_active, lf_link) {
985 * We may assume that the active list is sorted by
988 if (overlap->lf_start > lock->lf_end)
990 if (!lf_blocks(lock, overlap))
994 * We've found a blocking lock. Add the corresponding
995 * edge to the graphs and see if it would cause a
998 error = lf_add_edge(lock, overlap);
1001 * The only error that lf_add_edge returns is EDEADLK.
1002 * Remove any edges we added and return the error.
1005 lf_remove_outgoing(lock);
1011 * We also need to add edges to sleeping locks that block
1012 * us. This ensures that lf_wakeup_lock cannot grant two
1013 * mutually blocking locks simultaneously and also enforces a
1014 * 'first come, first served' fairness model. Note that this
1015 * only happens if we are blocked by at least one active lock
1016 * due to the call to lf_getblock in lf_setlock below.
1018 LIST_FOREACH(overlap, &state->ls_pending, lf_link) {
1019 if (!lf_blocks(lock, overlap))
1022 * We've found a blocking lock. Add the corresponding
1023 * edge to the graphs and see if it would cause a
1026 error = lf_add_edge(lock, overlap);
1029 * The only error that lf_add_edge returns is EDEADLK.
1030 * Remove any edges we added and return the error.
1033 lf_remove_outgoing(lock);
1042 * Walk the list of pending locks for the file and create an in-coming
1043 * edge from lock to each blocking lock.
1046 lf_add_incoming(struct lockf *state, struct lockf_entry *lock)
1048 struct lockf_entry *overlap;
1051 sx_assert(&state->ls_lock, SX_XLOCKED);
1052 if (LIST_EMPTY(&state->ls_pending))
1056 sx_xlock(&lf_owner_graph_lock);
1057 LIST_FOREACH(overlap, &state->ls_pending, lf_link) {
1058 if (!lf_blocks(lock, overlap))
1062 * We've found a blocking lock. Add the corresponding
1063 * edge to the graphs and see if it would cause a
1066 error = lf_add_edge(overlap, lock);
1069 * The only error that lf_add_edge returns is EDEADLK.
1070 * Remove any edges we added and return the error.
1073 lf_remove_incoming(lock);
1077 sx_xunlock(&lf_owner_graph_lock);
1082 * Insert lock into the active list, keeping list entries ordered by
1083 * increasing values of lf_start.
1086 lf_insert_lock(struct lockf *state, struct lockf_entry *lock)
1088 struct lockf_entry *lf, *lfprev;
1090 if (LIST_EMPTY(&state->ls_active)) {
1091 LIST_INSERT_HEAD(&state->ls_active, lock, lf_link);
1096 LIST_FOREACH(lf, &state->ls_active, lf_link) {
1097 if (lf->lf_start > lock->lf_start) {
1098 LIST_INSERT_BEFORE(lf, lock, lf_link);
1103 LIST_INSERT_AFTER(lfprev, lock, lf_link);
1107 * Wake up a sleeping lock and remove it from the pending list now
1108 * that all its dependencies have been resolved. The caller should
1109 * arrange for the lock to be added to the active list, adjusting any
1110 * existing locks for the same owner as needed.
1113 lf_wakeup_lock(struct lockf *state, struct lockf_entry *wakelock)
1117 * Remove from ls_pending list and wake up the caller
1118 * or start the async notification, as appropriate.
1120 LIST_REMOVE(wakelock, lf_link);
1122 if (lockf_debug & 1)
1123 lf_print("lf_wakeup_lock: awakening", wakelock);
1124 #endif /* LOCKF_DEBUG */
1125 if (wakelock->lf_async_task) {
1126 taskqueue_enqueue(taskqueue_thread, wakelock->lf_async_task);
1133 * Re-check all dependent locks and remove edges to locks that we no
1134 * longer block. If 'all' is non-zero, the lock has been removed and
1135 * we must remove all the dependencies, otherwise it has simply been
1136 * reduced but remains active. Any pending locks which have been been
1137 * unblocked are added to 'granted'
1140 lf_update_dependancies(struct lockf *state, struct lockf_entry *lock, int all,
1141 struct lockf_entry_list *granted)
1143 struct lockf_edge *e, *ne;
1144 struct lockf_entry *deplock;
1146 LIST_FOREACH_SAFE(e, &lock->lf_inedges, le_inlink, ne) {
1147 deplock = e->le_from;
1148 if (all || !lf_blocks(lock, deplock)) {
1149 sx_xlock(&lf_owner_graph_lock);
1151 sx_xunlock(&lf_owner_graph_lock);
1152 if (LIST_EMPTY(&deplock->lf_outedges)) {
1153 lf_wakeup_lock(state, deplock);
1154 LIST_INSERT_HEAD(granted, deplock, lf_link);
1161 * Set the start of an existing active lock, updating dependencies and
1162 * adding any newly woken locks to 'granted'.
1165 lf_set_start(struct lockf *state, struct lockf_entry *lock, off_t new_start,
1166 struct lockf_entry_list *granted)
1169 KASSERT(new_start >= lock->lf_start, ("can't increase lock"));
1170 lock->lf_start = new_start;
1171 LIST_REMOVE(lock, lf_link);
1172 lf_insert_lock(state, lock);
1173 lf_update_dependancies(state, lock, FALSE, granted);
1177 * Set the end of an existing active lock, updating dependencies and
1178 * adding any newly woken locks to 'granted'.
1181 lf_set_end(struct lockf *state, struct lockf_entry *lock, off_t new_end,
1182 struct lockf_entry_list *granted)
1185 KASSERT(new_end <= lock->lf_end, ("can't increase lock"));
1186 lock->lf_end = new_end;
1187 lf_update_dependancies(state, lock, FALSE, granted);
1191 * Add a lock to the active list, updating or removing any current
1192 * locks owned by the same owner and processing any pending locks that
1193 * become unblocked as a result. This code is also used for unlock
1194 * since the logic for updating existing locks is identical.
1196 * As a result of processing the new lock, we may unblock existing
1197 * pending locks as a result of downgrading/unlocking. We simply
1198 * activate the newly granted locks by looping.
1200 * Since the new lock already has its dependencies set up, we always
1201 * add it to the list (unless its an unlock request). This may
1202 * fragment the lock list in some pathological cases but its probably
1203 * not a real problem.
1206 lf_activate_lock(struct lockf *state, struct lockf_entry *lock)
1208 struct lockf_entry *overlap, *lf;
1209 struct lockf_entry_list granted;
1212 LIST_INIT(&granted);
1213 LIST_INSERT_HEAD(&granted, lock, lf_link);
1215 while (!LIST_EMPTY(&granted)) {
1216 lock = LIST_FIRST(&granted);
1217 LIST_REMOVE(lock, lf_link);
1220 * Skip over locks owned by other processes. Handle
1221 * any locks that overlap and are owned by ourselves.
1223 overlap = LIST_FIRST(&state->ls_active);
1225 ovcase = lf_findoverlap(&overlap, lock, SELF);
1228 if (ovcase && (lockf_debug & 2)) {
1229 printf("lf_setlock: overlap %d", ovcase);
1230 lf_print("", overlap);
1236 * 1) overlap == lock
1237 * 2) overlap contains lock
1238 * 3) lock contains overlap
1239 * 4) overlap starts before lock
1240 * 5) overlap ends after lock
1243 case 0: /* no overlap */
1246 case 1: /* overlap == lock */
1248 * We have already setup the
1249 * dependants for the new lock, taking
1250 * into account a possible downgrade
1251 * or unlock. Remove the old lock.
1253 LIST_REMOVE(overlap, lf_link);
1254 lf_update_dependancies(state, overlap, TRUE,
1256 lf_free_lock(overlap);
1259 case 2: /* overlap contains lock */
1261 * Just split the existing lock.
1263 lf_split(state, overlap, lock, &granted);
1266 case 3: /* lock contains overlap */
1268 * Delete the overlap and advance to
1269 * the next entry in the list.
1271 lf = LIST_NEXT(overlap, lf_link);
1272 LIST_REMOVE(overlap, lf_link);
1273 lf_update_dependancies(state, overlap, TRUE,
1275 lf_free_lock(overlap);
1279 case 4: /* overlap starts before lock */
1281 * Just update the overlap end and
1284 lf_set_end(state, overlap, lock->lf_start - 1,
1286 overlap = LIST_NEXT(overlap, lf_link);
1289 case 5: /* overlap ends after lock */
1291 * Change the start of overlap and
1294 lf_set_start(state, overlap, lock->lf_end + 1,
1301 if (lockf_debug & 1) {
1302 if (lock->lf_type != F_UNLCK)
1303 lf_print("lf_activate_lock: activated", lock);
1305 lf_print("lf_activate_lock: unlocked", lock);
1306 lf_printlist("lf_activate_lock", lock);
1308 #endif /* LOCKF_DEBUG */
1309 if (lock->lf_type != F_UNLCK)
1310 lf_insert_lock(state, lock);
1315 * Cancel a pending lock request, either as a result of a signal or a
1316 * cancel request for an async lock.
1319 lf_cancel_lock(struct lockf *state, struct lockf_entry *lock)
1321 struct lockf_entry_list granted;
1324 * Note it is theoretically possible that cancelling this lock
1325 * may allow some other pending lock to become
1326 * active. Consider this case:
1328 * Owner Action Result Dependencies
1330 * A: lock [0..0] succeeds
1331 * B: lock [2..2] succeeds
1332 * C: lock [1..2] blocked C->B
1333 * D: lock [0..1] blocked C->B,D->A,D->C
1334 * A: unlock [0..0] C->B,D->C
1338 LIST_REMOVE(lock, lf_link);
1341 * Removing out-going edges is simple.
1343 sx_xlock(&lf_owner_graph_lock);
1344 lf_remove_outgoing(lock);
1345 sx_xunlock(&lf_owner_graph_lock);
1348 * Removing in-coming edges may allow some other lock to
1349 * become active - we use lf_update_dependancies to figure
1352 LIST_INIT(&granted);
1353 lf_update_dependancies(state, lock, TRUE, &granted);
1357 * Feed any newly active locks to lf_activate_lock.
1359 while (!LIST_EMPTY(&granted)) {
1360 lock = LIST_FIRST(&granted);
1361 LIST_REMOVE(lock, lf_link);
1362 lf_activate_lock(state, lock);
1367 * Set a byte-range lock.
1370 lf_setlock(struct lockf *state, struct lockf_entry *lock, struct vnode *vp,
1373 static char lockstr[] = "lockf";
1374 int error, priority, stops_deferred;
1377 if (lockf_debug & 1)
1378 lf_print("lf_setlock", lock);
1379 #endif /* LOCKF_DEBUG */
1385 if (lock->lf_type == F_WRLCK)
1387 if (!(lock->lf_flags & F_NOINTR))
1390 * Scan lock list for this file looking for locks that would block us.
1392 if (lf_getblock(state, lock)) {
1394 * Free the structure and return if nonblocking.
1396 if ((lock->lf_flags & F_WAIT) == 0
1397 && lock->lf_async_task == NULL) {
1404 * For flock type locks, we must first remove
1405 * any shared locks that we hold before we sleep
1406 * waiting for an exclusive lock.
1408 if ((lock->lf_flags & F_FLOCK) &&
1409 lock->lf_type == F_WRLCK) {
1410 lock->lf_type = F_UNLCK;
1411 lf_activate_lock(state, lock);
1412 lock->lf_type = F_WRLCK;
1416 * We are blocked. Create edges to each blocking lock,
1417 * checking for deadlock using the owner graph. For
1418 * simplicity, we run deadlock detection for all
1419 * locks, posix and otherwise.
1421 sx_xlock(&lf_owner_graph_lock);
1422 error = lf_add_outgoing(state, lock);
1423 sx_xunlock(&lf_owner_graph_lock);
1427 if (lockf_debug & 1)
1428 lf_print("lf_setlock: deadlock", lock);
1435 * We have added edges to everything that blocks
1436 * us. Sleep until they all go away.
1438 LIST_INSERT_HEAD(&state->ls_pending, lock, lf_link);
1440 if (lockf_debug & 1) {
1441 struct lockf_edge *e;
1442 LIST_FOREACH(e, &lock->lf_outedges, le_outlink) {
1443 lf_print("lf_setlock: blocking on", e->le_to);
1444 lf_printlist("lf_setlock", e->le_to);
1447 #endif /* LOCKF_DEBUG */
1449 if ((lock->lf_flags & F_WAIT) == 0) {
1451 * The caller requested async notification -
1452 * this callback happens when the blocking
1453 * lock is released, allowing the caller to
1454 * make another attempt to take the lock.
1456 *cookiep = (void *) lock;
1457 error = EINPROGRESS;
1462 stops_deferred = sigdeferstop(SIGDEFERSTOP_ERESTART);
1463 error = sx_sleep(lock, &state->ls_lock, priority, lockstr, 0);
1464 sigallowstop(stops_deferred);
1465 if (lf_free_lock(lock)) {
1471 * We may have been awakened by a signal and/or by a
1472 * debugger continuing us (in which cases we must
1473 * remove our lock graph edges) and/or by another
1474 * process releasing a lock (in which case our edges
1475 * have already been removed and we have been moved to
1476 * the active list). We may also have been woken by
1477 * lf_purgelocks which we report to the caller as
1478 * EINTR. In that case, lf_purgelocks will have
1479 * removed our lock graph edges.
1481 * Note that it is possible to receive a signal after
1482 * we were successfully woken (and moved to the active
1483 * list) but before we resumed execution. In this
1484 * case, our lf_outedges list will be clear. We
1485 * pretend there was no error.
1487 * Note also, if we have been sleeping long enough, we
1488 * may now have incoming edges from some newer lock
1489 * which is waiting behind us in the queue.
1491 if (lock->lf_flags & F_INTR) {
1496 if (LIST_EMPTY(&lock->lf_outedges)) {
1499 lf_cancel_lock(state, lock);
1503 if (lockf_debug & 1) {
1504 lf_print("lf_setlock: granted", lock);
1510 * It looks like we are going to grant the lock. First add
1511 * edges from any currently pending lock that the new lock
1514 error = lf_add_incoming(state, lock);
1517 if (lockf_debug & 1)
1518 lf_print("lf_setlock: deadlock", lock);
1525 * No blocks!! Add the lock. Note that we will
1526 * downgrade or upgrade any overlapping locks this
1527 * process already owns.
1529 lf_activate_lock(state, lock);
1536 * Remove a byte-range lock on an inode.
1538 * Generally, find the lock (or an overlap to that lock)
1539 * and remove it (or shrink it), then wakeup anyone we can.
1542 lf_clearlock(struct lockf *state, struct lockf_entry *unlock)
1544 struct lockf_entry *overlap;
1546 overlap = LIST_FIRST(&state->ls_active);
1548 if (overlap == NOLOCKF)
1551 if (unlock->lf_type != F_UNLCK)
1552 panic("lf_clearlock: bad type");
1553 if (lockf_debug & 1)
1554 lf_print("lf_clearlock", unlock);
1555 #endif /* LOCKF_DEBUG */
1557 lf_activate_lock(state, unlock);
1563 * Check whether there is a blocking lock, and if so return its
1567 lf_getlock(struct lockf *state, struct lockf_entry *lock, struct flock *fl)
1569 struct lockf_entry *block;
1572 if (lockf_debug & 1)
1573 lf_print("lf_getlock", lock);
1574 #endif /* LOCKF_DEBUG */
1576 if ((block = lf_getblock(state, lock))) {
1577 fl->l_type = block->lf_type;
1578 fl->l_whence = SEEK_SET;
1579 fl->l_start = block->lf_start;
1580 if (block->lf_end == OFF_MAX)
1583 fl->l_len = block->lf_end - block->lf_start + 1;
1584 fl->l_pid = block->lf_owner->lo_pid;
1585 fl->l_sysid = block->lf_owner->lo_sysid;
1587 fl->l_type = F_UNLCK;
1593 * Cancel an async lock request.
1596 lf_cancel(struct lockf *state, struct lockf_entry *lock, void *cookie)
1598 struct lockf_entry *reallock;
1601 * We need to match this request with an existing lock
1604 LIST_FOREACH(reallock, &state->ls_pending, lf_link) {
1605 if ((void *) reallock == cookie) {
1607 * Double-check that this lock looks right
1608 * (maybe use a rolling ID for the cancel
1611 if (!(reallock->lf_vnode == lock->lf_vnode
1612 && reallock->lf_start == lock->lf_start
1613 && reallock->lf_end == lock->lf_end)) {
1618 * Make sure this lock was async and then just
1619 * remove it from its wait lists.
1621 if (!reallock->lf_async_task) {
1626 * Note that since any other thread must take
1627 * state->ls_lock before it can possibly
1628 * trigger the async callback, we are safe
1629 * from a race with lf_wakeup_lock, i.e. we
1630 * can free the lock (actually our caller does
1633 lf_cancel_lock(state, reallock);
1639 * We didn't find a matching lock - not much we can do here.
1645 * Walk the list of locks for an inode and
1646 * return the first blocking lock.
1648 static struct lockf_entry *
1649 lf_getblock(struct lockf *state, struct lockf_entry *lock)
1651 struct lockf_entry *overlap;
1653 LIST_FOREACH(overlap, &state->ls_active, lf_link) {
1655 * We may assume that the active list is sorted by
1658 if (overlap->lf_start > lock->lf_end)
1660 if (!lf_blocks(lock, overlap))
1668 * Walk the list of locks for an inode to find an overlapping lock (if
1669 * any) and return a classification of that overlap.
1672 * *overlap The place in the lock list to start looking
1673 * lock The lock which is being tested
1674 * type Pass 'SELF' to test only locks with the same
1675 * owner as lock, or 'OTHER' to test only locks
1676 * with a different owner
1678 * Returns one of six values:
1680 * 1) overlap == lock
1681 * 2) overlap contains lock
1682 * 3) lock contains overlap
1683 * 4) overlap starts before lock
1684 * 5) overlap ends after lock
1686 * If there is an overlapping lock, '*overlap' is set to point at the
1689 * NOTE: this returns only the FIRST overlapping lock. There
1690 * may be more than one.
1693 lf_findoverlap(struct lockf_entry **overlap, struct lockf_entry *lock, int type)
1695 struct lockf_entry *lf;
1699 if ((*overlap) == NOLOCKF) {
1703 if (lockf_debug & 2)
1704 lf_print("lf_findoverlap: looking for overlap in", lock);
1705 #endif /* LOCKF_DEBUG */
1706 start = lock->lf_start;
1711 if (lf->lf_start > end)
1713 if (((type & SELF) && lf->lf_owner != lock->lf_owner) ||
1714 ((type & OTHERS) && lf->lf_owner == lock->lf_owner)) {
1715 *overlap = LIST_NEXT(lf, lf_link);
1719 if (lockf_debug & 2)
1720 lf_print("\tchecking", lf);
1721 #endif /* LOCKF_DEBUG */
1723 * OK, check for overlap
1727 * 1) overlap == lock
1728 * 2) overlap contains lock
1729 * 3) lock contains overlap
1730 * 4) overlap starts before lock
1731 * 5) overlap ends after lock
1733 if (start > lf->lf_end) {
1736 if (lockf_debug & 2)
1737 printf("no overlap\n");
1738 #endif /* LOCKF_DEBUG */
1739 *overlap = LIST_NEXT(lf, lf_link);
1742 if (lf->lf_start == start && lf->lf_end == end) {
1745 if (lockf_debug & 2)
1746 printf("overlap == lock\n");
1747 #endif /* LOCKF_DEBUG */
1751 if (lf->lf_start <= start && lf->lf_end >= end) {
1754 if (lockf_debug & 2)
1755 printf("overlap contains lock\n");
1756 #endif /* LOCKF_DEBUG */
1760 if (start <= lf->lf_start && end >= lf->lf_end) {
1763 if (lockf_debug & 2)
1764 printf("lock contains overlap\n");
1765 #endif /* LOCKF_DEBUG */
1769 if (lf->lf_start < start && lf->lf_end >= start) {
1772 if (lockf_debug & 2)
1773 printf("overlap starts before lock\n");
1774 #endif /* LOCKF_DEBUG */
1778 if (lf->lf_start > start && lf->lf_end > end) {
1781 if (lockf_debug & 2)
1782 printf("overlap ends after lock\n");
1783 #endif /* LOCKF_DEBUG */
1787 panic("lf_findoverlap: default");
1793 * Split an the existing 'lock1', based on the extent of the lock
1794 * described by 'lock2'. The existing lock should cover 'lock2'
1797 * Any pending locks which have been been unblocked are added to
1801 lf_split(struct lockf *state, struct lockf_entry *lock1,
1802 struct lockf_entry *lock2, struct lockf_entry_list *granted)
1804 struct lockf_entry *splitlock;
1807 if (lockf_debug & 2) {
1808 lf_print("lf_split", lock1);
1809 lf_print("splitting from", lock2);
1811 #endif /* LOCKF_DEBUG */
1813 * Check to see if we don't need to split at all.
1815 if (lock1->lf_start == lock2->lf_start) {
1816 lf_set_start(state, lock1, lock2->lf_end + 1, granted);
1819 if (lock1->lf_end == lock2->lf_end) {
1820 lf_set_end(state, lock1, lock2->lf_start - 1, granted);
1824 * Make a new lock consisting of the last part of
1825 * the encompassing lock.
1827 splitlock = lf_alloc_lock(lock1->lf_owner);
1828 memcpy(splitlock, lock1, sizeof *splitlock);
1829 splitlock->lf_refs = 1;
1830 if (splitlock->lf_flags & F_REMOTE)
1831 vref(splitlock->lf_vnode);
1834 * This cannot cause a deadlock since any edges we would add
1835 * to splitlock already exist in lock1. We must be sure to add
1836 * necessary dependencies to splitlock before we reduce lock1
1837 * otherwise we may accidentally grant a pending lock that
1838 * was blocked by the tail end of lock1.
1840 splitlock->lf_start = lock2->lf_end + 1;
1841 LIST_INIT(&splitlock->lf_outedges);
1842 LIST_INIT(&splitlock->lf_inedges);
1843 lf_add_incoming(state, splitlock);
1845 lf_set_end(state, lock1, lock2->lf_start - 1, granted);
1848 * OK, now link it in
1850 lf_insert_lock(state, splitlock);
1854 STAILQ_ENTRY(lockdesc) link;
1858 STAILQ_HEAD(lockdesclist, lockdesc);
1861 lf_iteratelocks_sysid(int sysid, lf_iterator *fn, void *arg)
1864 struct lockf_entry *lf;
1865 struct lockdesc *ldesc;
1866 struct lockdesclist locks;
1870 * In order to keep the locking simple, we iterate over the
1871 * active lock lists to build a list of locks that need
1872 * releasing. We then call the iterator for each one in turn.
1874 * We take an extra reference to the vnode for the duration to
1875 * make sure it doesn't go away before we are finished.
1877 STAILQ_INIT(&locks);
1878 sx_xlock(&lf_lock_states_lock);
1879 LIST_FOREACH(ls, &lf_lock_states, ls_link) {
1880 sx_xlock(&ls->ls_lock);
1881 LIST_FOREACH(lf, &ls->ls_active, lf_link) {
1882 if (lf->lf_owner->lo_sysid != sysid)
1885 ldesc = malloc(sizeof(struct lockdesc), M_LOCKF,
1887 ldesc->vp = lf->lf_vnode;
1889 ldesc->fl.l_start = lf->lf_start;
1890 if (lf->lf_end == OFF_MAX)
1891 ldesc->fl.l_len = 0;
1894 lf->lf_end - lf->lf_start + 1;
1895 ldesc->fl.l_whence = SEEK_SET;
1896 ldesc->fl.l_type = F_UNLCK;
1897 ldesc->fl.l_pid = lf->lf_owner->lo_pid;
1898 ldesc->fl.l_sysid = sysid;
1899 STAILQ_INSERT_TAIL(&locks, ldesc, link);
1901 sx_xunlock(&ls->ls_lock);
1903 sx_xunlock(&lf_lock_states_lock);
1906 * Call the iterator function for each lock in turn. If the
1907 * iterator returns an error code, just free the rest of the
1908 * lockdesc structures.
1911 while ((ldesc = STAILQ_FIRST(&locks)) != NULL) {
1912 STAILQ_REMOVE_HEAD(&locks, link);
1914 error = fn(ldesc->vp, &ldesc->fl, arg);
1916 free(ldesc, M_LOCKF);
1923 lf_iteratelocks_vnode(struct vnode *vp, lf_iterator *fn, void *arg)
1926 struct lockf_entry *lf;
1927 struct lockdesc *ldesc;
1928 struct lockdesclist locks;
1932 * In order to keep the locking simple, we iterate over the
1933 * active lock lists to build a list of locks that need
1934 * releasing. We then call the iterator for each one in turn.
1936 * We take an extra reference to the vnode for the duration to
1937 * make sure it doesn't go away before we are finished.
1939 STAILQ_INIT(&locks);
1946 MPASS(ls->ls_threads >= 0);
1950 sx_xlock(&ls->ls_lock);
1951 LIST_FOREACH(lf, &ls->ls_active, lf_link) {
1952 ldesc = malloc(sizeof(struct lockdesc), M_LOCKF,
1954 ldesc->vp = lf->lf_vnode;
1956 ldesc->fl.l_start = lf->lf_start;
1957 if (lf->lf_end == OFF_MAX)
1958 ldesc->fl.l_len = 0;
1961 lf->lf_end - lf->lf_start + 1;
1962 ldesc->fl.l_whence = SEEK_SET;
1963 ldesc->fl.l_type = F_UNLCK;
1964 ldesc->fl.l_pid = lf->lf_owner->lo_pid;
1965 ldesc->fl.l_sysid = lf->lf_owner->lo_sysid;
1966 STAILQ_INSERT_TAIL(&locks, ldesc, link);
1968 sx_xunlock(&ls->ls_lock);
1970 MPASS(ls->ls_threads > 0);
1976 * Call the iterator function for each lock in turn. If the
1977 * iterator returns an error code, just free the rest of the
1978 * lockdesc structures.
1981 while ((ldesc = STAILQ_FIRST(&locks)) != NULL) {
1982 STAILQ_REMOVE_HEAD(&locks, link);
1984 error = fn(ldesc->vp, &ldesc->fl, arg);
1986 free(ldesc, M_LOCKF);
1993 lf_clearremotesys_iterator(struct vnode *vp, struct flock *fl, void *arg)
1996 VOP_ADVLOCK(vp, 0, F_UNLCK, fl, F_REMOTE);
2001 lf_clearremotesys(int sysid)
2004 KASSERT(sysid != 0, ("Can't clear local locks with F_UNLCKSYS"));
2005 lf_iteratelocks_sysid(sysid, lf_clearremotesys_iterator, NULL);
2009 lf_countlocks(int sysid)
2012 struct lock_owner *lo;
2016 for (i = 0; i < LOCK_OWNER_HASH_SIZE; i++) {
2017 sx_xlock(&lf_lock_owners[i].lock);
2018 LIST_FOREACH(lo, &lf_lock_owners[i].list, lo_link)
2019 if (lo->lo_sysid == sysid)
2020 count += lo->lo_refs;
2021 sx_xunlock(&lf_lock_owners[i].lock);
2030 * Return non-zero if y is reachable from x using a brute force
2031 * search. If reachable and path is non-null, return the route taken
2035 graph_reaches(struct owner_vertex *x, struct owner_vertex *y,
2036 struct owner_vertex_list *path)
2038 struct owner_edge *e;
2042 TAILQ_INSERT_HEAD(path, x, v_link);
2046 LIST_FOREACH(e, &x->v_outedges, e_outlink) {
2047 if (graph_reaches(e->e_to, y, path)) {
2049 TAILQ_INSERT_HEAD(path, x, v_link);
2057 * Perform consistency checks on the graph. Make sure the values of
2058 * v_order are correct. If checkorder is non-zero, check no vertex can
2059 * reach any other vertex with a smaller order.
2062 graph_check(struct owner_graph *g, int checkorder)
2066 for (i = 0; i < g->g_size; i++) {
2067 if (!g->g_vertices[i]->v_owner)
2069 KASSERT(g->g_vertices[i]->v_order == i,
2070 ("lock graph vertices disordered"));
2072 for (j = 0; j < i; j++) {
2073 if (!g->g_vertices[j]->v_owner)
2075 KASSERT(!graph_reaches(g->g_vertices[i],
2076 g->g_vertices[j], NULL),
2077 ("lock graph vertices disordered"));
2084 graph_print_vertices(struct owner_vertex_list *set)
2086 struct owner_vertex *v;
2089 TAILQ_FOREACH(v, set, v_link) {
2090 printf("%d:", v->v_order);
2091 lf_print_owner(v->v_owner);
2092 if (TAILQ_NEXT(v, v_link))
2101 * Calculate the sub-set of vertices v from the affected region [y..x]
2102 * where v is reachable from y. Return -1 if a loop was detected
2103 * (i.e. x is reachable from y, otherwise the number of vertices in
2107 graph_delta_forward(struct owner_graph *g, struct owner_vertex *x,
2108 struct owner_vertex *y, struct owner_vertex_list *delta)
2111 struct owner_vertex *v;
2112 struct owner_edge *e;
2116 * We start with a set containing just y. Then for each vertex
2117 * v in the set so far unprocessed, we add each vertex that v
2118 * has an out-edge to and that is within the affected region
2119 * [y..x]. If we see the vertex x on our travels, stop
2123 TAILQ_INSERT_TAIL(delta, y, v_link);
2128 LIST_FOREACH(e, &v->v_outedges, e_outlink) {
2131 if (e->e_to->v_order < x->v_order
2132 && e->e_to->v_gen != gen) {
2133 e->e_to->v_gen = gen;
2134 TAILQ_INSERT_TAIL(delta, e->e_to, v_link);
2138 v = TAILQ_NEXT(v, v_link);
2145 * Calculate the sub-set of vertices v from the affected region [y..x]
2146 * where v reaches x. Return the number of vertices in this subset.
2149 graph_delta_backward(struct owner_graph *g, struct owner_vertex *x,
2150 struct owner_vertex *y, struct owner_vertex_list *delta)
2153 struct owner_vertex *v;
2154 struct owner_edge *e;
2158 * We start with a set containing just x. Then for each vertex
2159 * v in the set so far unprocessed, we add each vertex that v
2160 * has an in-edge from and that is within the affected region
2164 TAILQ_INSERT_TAIL(delta, x, v_link);
2169 LIST_FOREACH(e, &v->v_inedges, e_inlink) {
2170 if (e->e_from->v_order > y->v_order
2171 && e->e_from->v_gen != gen) {
2172 e->e_from->v_gen = gen;
2173 TAILQ_INSERT_HEAD(delta, e->e_from, v_link);
2177 v = TAILQ_PREV(v, owner_vertex_list, v_link);
2184 graph_add_indices(int *indices, int n, struct owner_vertex_list *set)
2186 struct owner_vertex *v;
2189 TAILQ_FOREACH(v, set, v_link) {
2191 i > 0 && indices[i - 1] > v->v_order; i--)
2193 for (j = n - 1; j >= i; j--)
2194 indices[j + 1] = indices[j];
2195 indices[i] = v->v_order;
2203 graph_assign_indices(struct owner_graph *g, int *indices, int nextunused,
2204 struct owner_vertex_list *set)
2206 struct owner_vertex *v, *vlowest;
2208 while (!TAILQ_EMPTY(set)) {
2210 TAILQ_FOREACH(v, set, v_link) {
2211 if (!vlowest || v->v_order < vlowest->v_order)
2214 TAILQ_REMOVE(set, vlowest, v_link);
2215 vlowest->v_order = indices[nextunused];
2216 g->g_vertices[vlowest->v_order] = vlowest;
2220 return (nextunused);
2224 graph_add_edge(struct owner_graph *g, struct owner_vertex *x,
2225 struct owner_vertex *y)
2227 struct owner_edge *e;
2228 struct owner_vertex_list deltaF, deltaB;
2233 sx_assert(&lf_owner_graph_lock, SX_XLOCKED);
2235 LIST_FOREACH(e, &x->v_outedges, e_outlink) {
2243 if (lockf_debug & 8) {
2244 printf("adding edge %d:", x->v_order);
2245 lf_print_owner(x->v_owner);
2246 printf(" -> %d:", y->v_order);
2247 lf_print_owner(y->v_owner);
2251 if (y->v_order < x->v_order) {
2253 * The new edge violates the order. First find the set
2254 * of affected vertices reachable from y (deltaF) and
2255 * the set of affect vertices affected that reach x
2256 * (deltaB), using the graph generation number to
2257 * detect whether we have visited a given vertex
2258 * already. We re-order the graph so that each vertex
2259 * in deltaB appears before each vertex in deltaF.
2261 * If x is a member of deltaF, then the new edge would
2262 * create a cycle. Otherwise, we may assume that
2263 * deltaF and deltaB are disjoint.
2266 if (g->g_gen == 0) {
2270 for (vi = 0; vi < g->g_size; vi++) {
2271 g->g_vertices[vi]->v_gen = 0;
2275 nF = graph_delta_forward(g, x, y, &deltaF);
2278 if (lockf_debug & 8) {
2279 struct owner_vertex_list path;
2280 printf("deadlock: ");
2282 graph_reaches(y, x, &path);
2283 graph_print_vertices(&path);
2290 if (lockf_debug & 8) {
2291 printf("re-ordering graph vertices\n");
2292 printf("deltaF = ");
2293 graph_print_vertices(&deltaF);
2297 nB = graph_delta_backward(g, x, y, &deltaB);
2300 if (lockf_debug & 8) {
2301 printf("deltaB = ");
2302 graph_print_vertices(&deltaB);
2307 * We first build a set of vertex indices (vertex
2308 * order values) that we may use, then we re-assign
2309 * orders first to those vertices in deltaB, then to
2310 * deltaF. Note that the contents of deltaF and deltaB
2311 * may be partially disordered - we perform an
2312 * insertion sort while building our index set.
2314 indices = g->g_indexbuf;
2315 n = graph_add_indices(indices, 0, &deltaF);
2316 graph_add_indices(indices, n, &deltaB);
2319 * We must also be sure to maintain the relative
2320 * ordering of deltaF and deltaB when re-assigning
2321 * vertices. We do this by iteratively removing the
2322 * lowest ordered element from the set and assigning
2323 * it the next value from our new ordering.
2325 i = graph_assign_indices(g, indices, 0, &deltaB);
2326 graph_assign_indices(g, indices, i, &deltaF);
2329 if (lockf_debug & 8) {
2330 struct owner_vertex_list set;
2332 for (i = 0; i < nB + nF; i++)
2333 TAILQ_INSERT_TAIL(&set,
2334 g->g_vertices[indices[i]], v_link);
2335 printf("new ordering = ");
2336 graph_print_vertices(&set);
2341 KASSERT(x->v_order < y->v_order, ("Failed to re-order graph"));
2344 if (lockf_debug & 8) {
2345 graph_check(g, TRUE);
2349 e = malloc(sizeof(struct owner_edge), M_LOCKF, M_WAITOK);
2351 LIST_INSERT_HEAD(&x->v_outedges, e, e_outlink);
2352 LIST_INSERT_HEAD(&y->v_inedges, e, e_inlink);
2361 * Remove an edge x->y from the graph.
2364 graph_remove_edge(struct owner_graph *g, struct owner_vertex *x,
2365 struct owner_vertex *y)
2367 struct owner_edge *e;
2369 sx_assert(&lf_owner_graph_lock, SX_XLOCKED);
2371 LIST_FOREACH(e, &x->v_outedges, e_outlink) {
2375 KASSERT(e, ("Removing non-existent edge from deadlock graph"));
2378 if (e->e_refs == 0) {
2380 if (lockf_debug & 8) {
2381 printf("removing edge %d:", x->v_order);
2382 lf_print_owner(x->v_owner);
2383 printf(" -> %d:", y->v_order);
2384 lf_print_owner(y->v_owner);
2388 LIST_REMOVE(e, e_outlink);
2389 LIST_REMOVE(e, e_inlink);
2395 * Allocate a vertex from the free list. Return ENOMEM if there are
2398 static struct owner_vertex *
2399 graph_alloc_vertex(struct owner_graph *g, struct lock_owner *lo)
2401 struct owner_vertex *v;
2403 sx_assert(&lf_owner_graph_lock, SX_XLOCKED);
2405 v = malloc(sizeof(struct owner_vertex), M_LOCKF, M_WAITOK);
2406 if (g->g_size == g->g_space) {
2407 g->g_vertices = realloc(g->g_vertices,
2408 2 * g->g_space * sizeof(struct owner_vertex *),
2410 free(g->g_indexbuf, M_LOCKF);
2411 g->g_indexbuf = malloc(2 * g->g_space * sizeof(int),
2413 g->g_space = 2 * g->g_space;
2415 v->v_order = g->g_size;
2416 v->v_gen = g->g_gen;
2417 g->g_vertices[g->g_size] = v;
2420 LIST_INIT(&v->v_outedges);
2421 LIST_INIT(&v->v_inedges);
2428 graph_free_vertex(struct owner_graph *g, struct owner_vertex *v)
2430 struct owner_vertex *w;
2433 sx_assert(&lf_owner_graph_lock, SX_XLOCKED);
2435 KASSERT(LIST_EMPTY(&v->v_outedges), ("Freeing vertex with edges"));
2436 KASSERT(LIST_EMPTY(&v->v_inedges), ("Freeing vertex with edges"));
2439 * Remove from the graph's array and close up the gap,
2440 * renumbering the other vertices.
2442 for (i = v->v_order + 1; i < g->g_size; i++) {
2443 w = g->g_vertices[i];
2445 g->g_vertices[i - 1] = w;
2452 static struct owner_graph *
2453 graph_init(struct owner_graph *g)
2456 g->g_vertices = malloc(10 * sizeof(struct owner_vertex *),
2460 g->g_indexbuf = malloc(g->g_space * sizeof(int), M_LOCKF, M_WAITOK);
2466 struct kinfo_lockf_linked {
2467 struct kinfo_lockf kl;
2469 STAILQ_ENTRY(kinfo_lockf_linked) link;
2473 vfs_report_lockf(struct mount *mp, struct sbuf *sb)
2476 struct lockf_entry *lf;
2477 struct kinfo_lockf_linked *klf;
2479 struct ucred *ucred;
2480 char *fullpath, *freepath;
2482 STAILQ_HEAD(, kinfo_lockf_linked) locks;
2485 STAILQ_INIT(&locks);
2486 sx_slock(&lf_lock_states_lock);
2487 LIST_FOREACH(ls, &lf_lock_states, ls_link) {
2488 sx_slock(&ls->ls_lock);
2489 LIST_FOREACH(lf, &ls->ls_active, lf_link) {
2491 if (VN_IS_DOOMED(vp) || vp->v_mount != mp)
2494 klf = malloc(sizeof(struct kinfo_lockf_linked),
2495 M_LOCKF, M_WAITOK | M_ZERO);
2497 klf->kl.kl_structsize = sizeof(struct kinfo_lockf);
2498 klf->kl.kl_start = lf->lf_start;
2499 klf->kl.kl_len = lf->lf_end == OFF_MAX ? 0 :
2500 lf->lf_end - lf->lf_start + 1;
2501 klf->kl.kl_rw = lf->lf_type == F_RDLCK ?
2502 KLOCKF_RW_READ : KLOCKF_RW_WRITE;
2503 if (lf->lf_owner->lo_sysid != 0) {
2504 klf->kl.kl_pid = lf->lf_owner->lo_pid;
2505 klf->kl.kl_sysid = lf->lf_owner->lo_sysid;
2506 klf->kl.kl_type = KLOCKF_TYPE_REMOTE;
2507 } else if (lf->lf_owner->lo_pid == -1) {
2508 klf->kl.kl_pid = -1;
2509 klf->kl.kl_sysid = 0;
2510 klf->kl.kl_type = KLOCKF_TYPE_FLOCK;
2512 klf->kl.kl_pid = lf->lf_owner->lo_pid;
2513 klf->kl.kl_sysid = 0;
2514 klf->kl.kl_type = KLOCKF_TYPE_PID;
2516 STAILQ_INSERT_TAIL(&locks, klf, link);
2518 sx_sunlock(&ls->ls_lock);
2520 sx_sunlock(&lf_lock_states_lock);
2523 ucred = curthread->td_ucred;
2524 while ((klf = STAILQ_FIRST(&locks)) != NULL) {
2525 STAILQ_REMOVE_HEAD(&locks, link);
2527 if (gerror == 0 && vn_lock(vp, LK_SHARED) == 0) {
2528 error = prison_canseemount(ucred, vp->v_mount);
2530 error = VOP_STAT(vp, &stt, ucred, NOCRED,
2534 klf->kl.kl_file_fsid = stt.st_dev;
2535 klf->kl.kl_file_rdev = stt.st_rdev;
2536 klf->kl.kl_file_fileid = stt.st_ino;
2539 error = vn_fullpath(vp, &fullpath, &freepath);
2541 strlcpy(klf->kl.kl_path, fullpath,
2542 sizeof(klf->kl.kl_path));
2543 free(freepath, M_TEMP);
2544 if (sbuf_bcat(sb, &klf->kl,
2545 klf->kl.kl_structsize) != 0) {
2546 gerror = sbuf_error(sb);
2558 sysctl_kern_lockf_run(struct sbuf *sb)
2564 mtx_lock(&mountlist_mtx);
2565 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
2566 error = vfs_busy(mp, MBF_MNTLSTLOCK);
2569 error = mp->mnt_op->vfs_report_lockf(mp, sb);
2570 mtx_lock(&mountlist_mtx);
2575 mtx_unlock(&mountlist_mtx);
2580 sysctl_kern_lockf(SYSCTL_HANDLER_ARGS)
2585 sbuf_new_for_sysctl(&sb, NULL, sizeof(struct kinfo_lockf) * 5, req);
2586 sbuf_clear_flags(&sb, SBUF_INCLUDENUL);
2587 error = sysctl_kern_lockf_run(&sb);
2588 error2 = sbuf_finish(&sb);
2590 return (error != 0 ? error : error2);
2592 SYSCTL_PROC(_kern, KERN_LOCKF, lockf,
2593 CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
2594 0, 0, sysctl_kern_lockf, "S,lockf",
2595 "Advisory locks table");
2599 * Print description of a lock owner
2602 lf_print_owner(struct lock_owner *lo)
2605 if (lo->lo_flags & F_REMOTE) {
2606 printf("remote pid %d, system %d",
2607 lo->lo_pid, lo->lo_sysid);
2608 } else if (lo->lo_flags & F_FLOCK) {
2609 printf("file %p", lo->lo_id);
2611 printf("local pid %d", lo->lo_pid);
2619 lf_print(char *tag, struct lockf_entry *lock)
2622 printf("%s: lock %p for ", tag, (void *)lock);
2623 lf_print_owner(lock->lf_owner);
2624 printf("\nvnode %p", lock->lf_vnode);
2625 VOP_PRINT(lock->lf_vnode);
2626 printf(" %s, start %jd, end ",
2627 lock->lf_type == F_RDLCK ? "shared" :
2628 lock->lf_type == F_WRLCK ? "exclusive" :
2629 lock->lf_type == F_UNLCK ? "unlock" : "unknown",
2630 (intmax_t)lock->lf_start);
2631 if (lock->lf_end == OFF_MAX)
2634 printf("%jd", (intmax_t)lock->lf_end);
2635 if (!LIST_EMPTY(&lock->lf_outedges))
2636 printf(" block %p\n",
2637 (void *)LIST_FIRST(&lock->lf_outedges)->le_to);
2643 lf_printlist(char *tag, struct lockf_entry *lock)
2645 struct lockf_entry *lf, *blk;
2646 struct lockf_edge *e;
2648 printf("%s: Lock list for vnode %p:\n", tag, lock->lf_vnode);
2649 LIST_FOREACH(lf, &lock->lf_vnode->v_lockf->ls_active, lf_link) {
2650 printf("\tlock %p for ",(void *)lf);
2651 lf_print_owner(lock->lf_owner);
2652 printf(", %s, start %jd, end %jd",
2653 lf->lf_type == F_RDLCK ? "shared" :
2654 lf->lf_type == F_WRLCK ? "exclusive" :
2655 lf->lf_type == F_UNLCK ? "unlock" :
2656 "unknown", (intmax_t)lf->lf_start, (intmax_t)lf->lf_end);
2657 LIST_FOREACH(e, &lf->lf_outedges, le_outlink) {
2659 printf("\n\t\tlock request %p for ", (void *)blk);
2660 lf_print_owner(blk->lf_owner);
2661 printf(", %s, start %jd, end %jd",
2662 blk->lf_type == F_RDLCK ? "shared" :
2663 blk->lf_type == F_WRLCK ? "exclusive" :
2664 blk->lf_type == F_UNLCK ? "unlock" :
2665 "unknown", (intmax_t)blk->lf_start,
2666 (intmax_t)blk->lf_end);
2667 if (!LIST_EMPTY(&blk->lf_inedges))
2668 panic("lf_printlist: bad list");
2673 #endif /* LOCKF_DEBUG */