xref: /freebsd-13-stable/sys/kern/kern_lockf.c (revision 3bc80996974a61a4223eae4c1ccd47b6ee32a48a)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
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>
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
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.
16  *
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
27  * SUCH DAMAGE.
28  */
29 /*-
30  * Copyright (c) 1982, 1986, 1989, 1993
31  *	The Regents of the University of California.  All rights reserved.
32  *
33  * This code is derived from software contributed to Berkeley by
34  * Scooter Morris at Genentech Inc.
35  *
36  * Redistribution and use in source and binary forms, with or without
37  * modification, are permitted provided that the following conditions
38  * are met:
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.
47  *
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
58  * SUCH DAMAGE.
59  *
60  *	@(#)ufs_lockf.c	8.3 (Berkeley) 1/6/94
61  */
62 
63 #include <sys/cdefs.h>
64 #include "opt_debug_lockf.h"
65 
66 #include <sys/param.h>
67 #include <sys/systm.h>
68 #include <sys/hash.h>
69 #include <sys/jail.h>
70 #include <sys/kernel.h>
71 #include <sys/limits.h>
72 #include <sys/lock.h>
73 #include <sys/mount.h>
74 #include <sys/mutex.h>
75 #include <sys/proc.h>
76 #include <sys/sbuf.h>
77 #include <sys/stat.h>
78 #include <sys/sx.h>
79 #include <sys/unistd.h>
80 #include <sys/user.h>
81 #include <sys/vnode.h>
82 #include <sys/malloc.h>
83 #include <sys/fcntl.h>
84 #include <sys/lockf.h>
85 #include <sys/taskqueue.h>
86 
87 #ifdef LOCKF_DEBUG
88 #include <sys/sysctl.h>
89 
90 static int	lockf_debug = 0; /* control debug output */
91 SYSCTL_INT(_debug, OID_AUTO, lockf_debug, CTLFLAG_RW, &lockf_debug, 0, "");
92 #endif
93 
94 static MALLOC_DEFINE(M_LOCKF, "lockf", "Byte-range locking structures");
95 
96 struct owner_edge;
97 struct owner_vertex;
98 struct owner_vertex_list;
99 struct owner_graph;
100 
101 #define NOLOCKF (struct lockf_entry *)0
102 #define SELF	0x1
103 #define OTHERS	0x2
104 static void	 lf_init(void *);
105 static int	 lf_hash_owner(caddr_t, struct vnode *, struct flock *, int);
106 static int	 lf_owner_matches(struct lock_owner *, caddr_t, struct flock *,
107     int);
108 static struct lockf_entry *
109 		 lf_alloc_lock(struct lock_owner *);
110 static int	 lf_free_lock(struct lockf_entry *);
111 static int	 lf_clearlock(struct lockf *, struct lockf_entry *);
112 static int	 lf_overlaps(struct lockf_entry *, struct lockf_entry *);
113 static int	 lf_blocks(struct lockf_entry *, struct lockf_entry *);
114 static void	 lf_free_edge(struct lockf_edge *);
115 static struct lockf_edge *
116 		 lf_alloc_edge(void);
117 static void	 lf_alloc_vertex(struct lockf_entry *);
118 static int	 lf_add_edge(struct lockf_entry *, struct lockf_entry *);
119 static void	 lf_remove_edge(struct lockf_edge *);
120 static void	 lf_remove_outgoing(struct lockf_entry *);
121 static void	 lf_remove_incoming(struct lockf_entry *);
122 static int	 lf_add_outgoing(struct lockf *, struct lockf_entry *);
123 static int	 lf_add_incoming(struct lockf *, struct lockf_entry *);
124 static int	 lf_findoverlap(struct lockf_entry **, struct lockf_entry *,
125     int);
126 static struct lockf_entry *
127 		 lf_getblock(struct lockf *, struct lockf_entry *);
128 static int	 lf_getlock(struct lockf *, struct lockf_entry *, struct flock *);
129 static void	 lf_insert_lock(struct lockf *, struct lockf_entry *);
130 static void	 lf_wakeup_lock(struct lockf *, struct lockf_entry *);
131 static void	 lf_update_dependancies(struct lockf *, struct lockf_entry *,
132     int all, struct lockf_entry_list *);
133 static void	 lf_set_start(struct lockf *, struct lockf_entry *, off_t,
134 	struct lockf_entry_list*);
135 static void	 lf_set_end(struct lockf *, struct lockf_entry *, off_t,
136 	struct lockf_entry_list*);
137 static int	 lf_setlock(struct lockf *, struct lockf_entry *,
138     struct vnode *, void **cookiep);
139 static int	 lf_cancel(struct lockf *, struct lockf_entry *, void *);
140 static void	 lf_split(struct lockf *, struct lockf_entry *,
141     struct lockf_entry *, struct lockf_entry_list *);
142 #ifdef LOCKF_DEBUG
143 static int	 graph_reaches(struct owner_vertex *x, struct owner_vertex *y,
144     struct owner_vertex_list *path);
145 static void	 graph_check(struct owner_graph *g, int checkorder);
146 static void	 graph_print_vertices(struct owner_vertex_list *set);
147 #endif
148 static int	 graph_delta_forward(struct owner_graph *g,
149     struct owner_vertex *x, struct owner_vertex *y,
150     struct owner_vertex_list *delta);
151 static int	 graph_delta_backward(struct owner_graph *g,
152     struct owner_vertex *x, struct owner_vertex *y,
153     struct owner_vertex_list *delta);
154 static int	 graph_add_indices(int *indices, int n,
155     struct owner_vertex_list *set);
156 static int	 graph_assign_indices(struct owner_graph *g, int *indices,
157     int nextunused, struct owner_vertex_list *set);
158 static int	 graph_add_edge(struct owner_graph *g,
159     struct owner_vertex *x, struct owner_vertex *y);
160 static void	 graph_remove_edge(struct owner_graph *g,
161     struct owner_vertex *x, struct owner_vertex *y);
162 static struct owner_vertex *graph_alloc_vertex(struct owner_graph *g,
163     struct lock_owner *lo);
164 static void	 graph_free_vertex(struct owner_graph *g,
165     struct owner_vertex *v);
166 static struct owner_graph * graph_init(struct owner_graph *g);
167 #ifdef LOCKF_DEBUG
168 static void	 lf_print(char *, struct lockf_entry *);
169 static void	 lf_printlist(char *, struct lockf_entry *);
170 static void	 lf_print_owner(struct lock_owner *);
171 #endif
172 
173 /*
174  * This structure is used to keep track of both local and remote lock
175  * owners. The lf_owner field of the struct lockf_entry points back at
176  * the lock owner structure. Each possible lock owner (local proc for
177  * POSIX fcntl locks, local file for BSD flock locks or <pid,sysid>
178  * pair for remote locks) is represented by a unique instance of
179  * struct lock_owner.
180  *
181  * If a lock owner has a lock that blocks some other lock or a lock
182  * that is waiting for some other lock, it also has a vertex in the
183  * owner_graph below.
184  *
185  * Locks:
186  * (s)		locked by state->ls_lock
187  * (S)		locked by lf_lock_states_lock
188  * (g)		locked by lf_owner_graph_lock
189  * (c)		const until freeing
190  */
191 #define	LOCK_OWNER_HASH_SIZE	256
192 
193 struct lock_owner {
194 	LIST_ENTRY(lock_owner) lo_link; /* (l) hash chain */
195 	int	lo_refs;	    /* (l) Number of locks referring to this */
196 	int	lo_flags;	    /* (c) Flags passed to lf_advlock */
197 	caddr_t	lo_id;		    /* (c) Id value passed to lf_advlock */
198 	pid_t	lo_pid;		    /* (c) Process Id of the lock owner */
199 	int	lo_sysid;	    /* (c) System Id of the lock owner */
200 	int	lo_hash;	    /* (c) Used to lock the appropriate chain */
201 	struct owner_vertex *lo_vertex; /* (g) entry in deadlock graph */
202 };
203 
204 LIST_HEAD(lock_owner_list, lock_owner);
205 
206 struct lock_owner_chain {
207 	struct sx		lock;
208 	struct lock_owner_list	list;
209 };
210 
211 static struct sx		lf_lock_states_lock;
212 static struct lockf_list	lf_lock_states; /* (S) */
213 static struct lock_owner_chain	lf_lock_owners[LOCK_OWNER_HASH_SIZE];
214 
215 /*
216  * Structures for deadlock detection.
217  *
218  * We have two types of directed graph, the first is the set of locks,
219  * both active and pending on a vnode. Within this graph, active locks
220  * are terminal nodes in the graph (i.e. have no out-going
221  * edges). Pending locks have out-going edges to each blocking active
222  * lock that prevents the lock from being granted and also to each
223  * older pending lock that would block them if it was active. The
224  * graph for each vnode is naturally acyclic; new edges are only ever
225  * added to or from new nodes (either new pending locks which only add
226  * out-going edges or new active locks which only add in-coming edges)
227  * therefore they cannot create loops in the lock graph.
228  *
229  * The second graph is a global graph of lock owners. Each lock owner
230  * is a vertex in that graph and an edge is added to the graph
231  * whenever an edge is added to a vnode graph, with end points
232  * corresponding to owner of the new pending lock and the owner of the
233  * lock upon which it waits. In order to prevent deadlock, we only add
234  * an edge to this graph if the new edge would not create a cycle.
235  *
236  * The lock owner graph is topologically sorted, i.e. if a node has
237  * any outgoing edges, then it has an order strictly less than any
238  * node to which it has an outgoing edge. We preserve this ordering
239  * (and detect cycles) on edge insertion using Algorithm PK from the
240  * paper "A Dynamic Topological Sort Algorithm for Directed Acyclic
241  * Graphs" (ACM Journal of Experimental Algorithms, Vol 11, Article
242  * No. 1.7)
243  */
244 struct owner_vertex;
245 
246 struct owner_edge {
247 	LIST_ENTRY(owner_edge) e_outlink; /* (g) link from's out-edge list */
248 	LIST_ENTRY(owner_edge) e_inlink;  /* (g) link to's in-edge list */
249 	int		e_refs;		  /* (g) number of times added */
250 	struct owner_vertex *e_from;	  /* (c) out-going from here */
251 	struct owner_vertex *e_to;	  /* (c) in-coming to here */
252 };
253 LIST_HEAD(owner_edge_list, owner_edge);
254 
255 struct owner_vertex {
256 	TAILQ_ENTRY(owner_vertex) v_link; /* (g) workspace for edge insertion */
257 	uint32_t	v_gen;		  /* (g) workspace for edge insertion */
258 	int		v_order;	  /* (g) order of vertex in graph */
259 	struct owner_edge_list v_outedges;/* (g) list of out-edges */
260 	struct owner_edge_list v_inedges; /* (g) list of in-edges */
261 	struct lock_owner *v_owner;	  /* (c) corresponding lock owner */
262 };
263 TAILQ_HEAD(owner_vertex_list, owner_vertex);
264 
265 struct owner_graph {
266 	struct owner_vertex** g_vertices; /* (g) pointers to vertices */
267 	int		g_size;		  /* (g) number of vertices */
268 	int		g_space;	  /* (g) space allocated for vertices */
269 	int		*g_indexbuf;	  /* (g) workspace for loop detection */
270 	uint32_t	g_gen;		  /* (g) increment when re-ordering */
271 };
272 
273 static struct sx		lf_owner_graph_lock;
274 static struct owner_graph	lf_owner_graph;
275 
276 /*
277  * Initialise various structures and locks.
278  */
279 static void
lf_init(void * dummy)280 lf_init(void *dummy)
281 {
282 	int i;
283 
284 	sx_init(&lf_lock_states_lock, "lock states lock");
285 	LIST_INIT(&lf_lock_states);
286 
287 	for (i = 0; i < LOCK_OWNER_HASH_SIZE; i++) {
288 		sx_init(&lf_lock_owners[i].lock, "lock owners lock");
289 		LIST_INIT(&lf_lock_owners[i].list);
290 	}
291 
292 	sx_init(&lf_owner_graph_lock, "owner graph lock");
293 	graph_init(&lf_owner_graph);
294 }
295 SYSINIT(lf_init, SI_SUB_LOCK, SI_ORDER_FIRST, lf_init, NULL);
296 
297 /*
298  * Generate a hash value for a lock owner.
299  */
300 static int
lf_hash_owner(caddr_t id,struct vnode * vp,struct flock * fl,int flags)301 lf_hash_owner(caddr_t id, struct vnode *vp, struct flock *fl, int flags)
302 {
303 	uint32_t h;
304 
305 	if (flags & F_REMOTE) {
306 		h = HASHSTEP(0, fl->l_pid);
307 		h = HASHSTEP(h, fl->l_sysid);
308 	} else if (flags & F_FLOCK) {
309 		h = ((uintptr_t) id) >> 7;
310 	} else {
311 		h = ((uintptr_t) vp) >> 7;
312 	}
313 
314 	return (h % LOCK_OWNER_HASH_SIZE);
315 }
316 
317 /*
318  * Return true if a lock owner matches the details passed to
319  * lf_advlock.
320  */
321 static int
lf_owner_matches(struct lock_owner * lo,caddr_t id,struct flock * fl,int flags)322 lf_owner_matches(struct lock_owner *lo, caddr_t id, struct flock *fl,
323     int flags)
324 {
325 	if (flags & F_REMOTE) {
326 		return lo->lo_pid == fl->l_pid
327 			&& lo->lo_sysid == fl->l_sysid;
328 	} else {
329 		return lo->lo_id == id;
330 	}
331 }
332 
333 static struct lockf_entry *
lf_alloc_lock(struct lock_owner * lo)334 lf_alloc_lock(struct lock_owner *lo)
335 {
336 	struct lockf_entry *lf;
337 
338 	lf = malloc(sizeof(struct lockf_entry), M_LOCKF, M_WAITOK|M_ZERO);
339 
340 #ifdef LOCKF_DEBUG
341 	if (lockf_debug & 4)
342 		printf("Allocated lock %p\n", lf);
343 #endif
344 	if (lo) {
345 		sx_xlock(&lf_lock_owners[lo->lo_hash].lock);
346 		lo->lo_refs++;
347 		sx_xunlock(&lf_lock_owners[lo->lo_hash].lock);
348 		lf->lf_owner = lo;
349 	}
350 
351 	return (lf);
352 }
353 
354 static int
lf_free_lock(struct lockf_entry * lock)355 lf_free_lock(struct lockf_entry *lock)
356 {
357 	struct sx *chainlock;
358 
359 	KASSERT(lock->lf_refs > 0, ("lockf_entry negative ref count %p", lock));
360 	if (--lock->lf_refs > 0)
361 		return (0);
362 	/*
363 	 * Adjust the lock_owner reference count and
364 	 * reclaim the entry if this is the last lock
365 	 * for that owner.
366 	 */
367 	struct lock_owner *lo = lock->lf_owner;
368 	if (lo) {
369 		KASSERT(LIST_EMPTY(&lock->lf_outedges),
370 		    ("freeing lock with dependencies"));
371 		KASSERT(LIST_EMPTY(&lock->lf_inedges),
372 		    ("freeing lock with dependants"));
373 		chainlock = &lf_lock_owners[lo->lo_hash].lock;
374 		sx_xlock(chainlock);
375 		KASSERT(lo->lo_refs > 0, ("lock owner refcount"));
376 		lo->lo_refs--;
377 		if (lo->lo_refs == 0) {
378 #ifdef LOCKF_DEBUG
379 			if (lockf_debug & 1)
380 				printf("lf_free_lock: freeing lock owner %p\n",
381 				    lo);
382 #endif
383 			if (lo->lo_vertex) {
384 				sx_xlock(&lf_owner_graph_lock);
385 				graph_free_vertex(&lf_owner_graph,
386 				    lo->lo_vertex);
387 				sx_xunlock(&lf_owner_graph_lock);
388 			}
389 			LIST_REMOVE(lo, lo_link);
390 			free(lo, M_LOCKF);
391 #ifdef LOCKF_DEBUG
392 			if (lockf_debug & 4)
393 				printf("Freed lock owner %p\n", lo);
394 #endif
395 		}
396 		sx_unlock(chainlock);
397 	}
398 	if ((lock->lf_flags & F_REMOTE) && lock->lf_vnode) {
399 		vrele(lock->lf_vnode);
400 		lock->lf_vnode = NULL;
401 	}
402 #ifdef LOCKF_DEBUG
403 	if (lockf_debug & 4)
404 		printf("Freed lock %p\n", lock);
405 #endif
406 	free(lock, M_LOCKF);
407 	return (1);
408 }
409 
410 /*
411  * Advisory record locking support
412  */
413 int
lf_advlockasync(struct vop_advlockasync_args * ap,struct lockf ** statep,u_quad_t size)414 lf_advlockasync(struct vop_advlockasync_args *ap, struct lockf **statep,
415     u_quad_t size)
416 {
417 	struct lockf *state;
418 	struct flock *fl = ap->a_fl;
419 	struct lockf_entry *lock;
420 	struct vnode *vp = ap->a_vp;
421 	caddr_t id = ap->a_id;
422 	int flags = ap->a_flags;
423 	int hash;
424 	struct lock_owner *lo;
425 	off_t start, end, oadd;
426 	int error;
427 
428 	/*
429 	 * Handle the F_UNLKSYS case first - no need to mess about
430 	 * creating a lock owner for this one.
431 	 */
432 	if (ap->a_op == F_UNLCKSYS) {
433 		lf_clearremotesys(fl->l_sysid);
434 		return (0);
435 	}
436 
437 	/*
438 	 * Convert the flock structure into a start and end.
439 	 */
440 	switch (fl->l_whence) {
441 	case SEEK_SET:
442 	case SEEK_CUR:
443 		/*
444 		 * Caller is responsible for adding any necessary offset
445 		 * when SEEK_CUR is used.
446 		 */
447 		start = fl->l_start;
448 		break;
449 
450 	case SEEK_END:
451 		if (size > OFF_MAX ||
452 		    (fl->l_start > 0 && size > OFF_MAX - fl->l_start))
453 			return (EOVERFLOW);
454 		start = size + fl->l_start;
455 		break;
456 
457 	default:
458 		return (EINVAL);
459 	}
460 	if (start < 0)
461 		return (EINVAL);
462 	if (fl->l_len < 0) {
463 		if (start == 0)
464 			return (EINVAL);
465 		end = start - 1;
466 		start += fl->l_len;
467 		if (start < 0)
468 			return (EINVAL);
469 	} else if (fl->l_len == 0) {
470 		end = OFF_MAX;
471 	} else {
472 		oadd = fl->l_len - 1;
473 		if (oadd > OFF_MAX - start)
474 			return (EOVERFLOW);
475 		end = start + oadd;
476 	}
477 
478 retry_setlock:
479 
480 	/*
481 	 * Avoid the common case of unlocking when inode has no locks.
482 	 */
483 	if (ap->a_op != F_SETLK && (*statep) == NULL) {
484 		VI_LOCK(vp);
485 		if ((*statep) == NULL) {
486 			fl->l_type = F_UNLCK;
487 			VI_UNLOCK(vp);
488 			return (0);
489 		}
490 		VI_UNLOCK(vp);
491 	}
492 
493 	/*
494 	 * Map our arguments to an existing lock owner or create one
495 	 * if this is the first time we have seen this owner.
496 	 */
497 	hash = lf_hash_owner(id, vp, fl, flags);
498 	sx_xlock(&lf_lock_owners[hash].lock);
499 	LIST_FOREACH(lo, &lf_lock_owners[hash].list, lo_link)
500 		if (lf_owner_matches(lo, id, fl, flags))
501 			break;
502 	if (!lo) {
503 		/*
504 		 * We initialise the lock with a reference
505 		 * count which matches the new lockf_entry
506 		 * structure created below.
507 		 */
508 		lo = malloc(sizeof(struct lock_owner), M_LOCKF,
509 		    M_WAITOK|M_ZERO);
510 #ifdef LOCKF_DEBUG
511 		if (lockf_debug & 4)
512 			printf("Allocated lock owner %p\n", lo);
513 #endif
514 
515 		lo->lo_refs = 1;
516 		lo->lo_flags = flags;
517 		lo->lo_id = id;
518 		lo->lo_hash = hash;
519 		if (flags & F_REMOTE) {
520 			lo->lo_pid = fl->l_pid;
521 			lo->lo_sysid = fl->l_sysid;
522 		} else if (flags & F_FLOCK) {
523 			lo->lo_pid = -1;
524 			lo->lo_sysid = 0;
525 		} else {
526 			struct proc *p = (struct proc *) id;
527 			lo->lo_pid = p->p_pid;
528 			lo->lo_sysid = 0;
529 		}
530 		lo->lo_vertex = NULL;
531 
532 #ifdef LOCKF_DEBUG
533 		if (lockf_debug & 1) {
534 			printf("lf_advlockasync: new lock owner %p ", lo);
535 			lf_print_owner(lo);
536 			printf("\n");
537 		}
538 #endif
539 
540 		LIST_INSERT_HEAD(&lf_lock_owners[hash].list, lo, lo_link);
541 	} else {
542 		/*
543 		 * We have seen this lock owner before, increase its
544 		 * reference count to account for the new lockf_entry
545 		 * structure we create below.
546 		 */
547 		lo->lo_refs++;
548 	}
549 	sx_xunlock(&lf_lock_owners[hash].lock);
550 
551 	/*
552 	 * Create the lockf structure. We initialise the lf_owner
553 	 * field here instead of in lf_alloc_lock() to avoid paying
554 	 * the lf_lock_owners_lock tax twice.
555 	 */
556 	lock = lf_alloc_lock(NULL);
557 	lock->lf_refs = 1;
558 	lock->lf_start = start;
559 	lock->lf_end = end;
560 	lock->lf_owner = lo;
561 	lock->lf_vnode = vp;
562 	if (flags & F_REMOTE) {
563 		/*
564 		 * For remote locks, the caller may release its ref to
565 		 * the vnode at any time - we have to ref it here to
566 		 * prevent it from being recycled unexpectedly.
567 		 */
568 		vref(vp);
569 	}
570 
571 	lock->lf_type = fl->l_type;
572 	LIST_INIT(&lock->lf_outedges);
573 	LIST_INIT(&lock->lf_inedges);
574 	lock->lf_async_task = ap->a_task;
575 	lock->lf_flags = ap->a_flags;
576 
577 	/*
578 	 * Do the requested operation. First find our state structure
579 	 * and create a new one if necessary - the caller's *statep
580 	 * variable and the state's ls_threads count is protected by
581 	 * the vnode interlock.
582 	 */
583 	VI_LOCK(vp);
584 	if (VN_IS_DOOMED(vp)) {
585 		VI_UNLOCK(vp);
586 		lf_free_lock(lock);
587 		return (ENOENT);
588 	}
589 
590 	/*
591 	 * Allocate a state structure if necessary.
592 	 */
593 	state = *statep;
594 	if (state == NULL) {
595 		struct lockf *ls;
596 
597 		VI_UNLOCK(vp);
598 
599 		ls = malloc(sizeof(struct lockf), M_LOCKF, M_WAITOK|M_ZERO);
600 		sx_init(&ls->ls_lock, "ls_lock");
601 		LIST_INIT(&ls->ls_active);
602 		LIST_INIT(&ls->ls_pending);
603 		ls->ls_threads = 1;
604 
605 		sx_xlock(&lf_lock_states_lock);
606 		LIST_INSERT_HEAD(&lf_lock_states, ls, ls_link);
607 		sx_xunlock(&lf_lock_states_lock);
608 
609 		/*
610 		 * Cope if we lost a race with some other thread while
611 		 * trying to allocate memory.
612 		 */
613 		VI_LOCK(vp);
614 		if (VN_IS_DOOMED(vp)) {
615 			VI_UNLOCK(vp);
616 			sx_xlock(&lf_lock_states_lock);
617 			LIST_REMOVE(ls, ls_link);
618 			sx_xunlock(&lf_lock_states_lock);
619 			sx_destroy(&ls->ls_lock);
620 			free(ls, M_LOCKF);
621 			lf_free_lock(lock);
622 			return (ENOENT);
623 		}
624 		if ((*statep) == NULL) {
625 			state = *statep = ls;
626 			VI_UNLOCK(vp);
627 		} else {
628 			state = *statep;
629 			MPASS(state->ls_threads >= 0);
630 			state->ls_threads++;
631 			VI_UNLOCK(vp);
632 
633 			sx_xlock(&lf_lock_states_lock);
634 			LIST_REMOVE(ls, ls_link);
635 			sx_xunlock(&lf_lock_states_lock);
636 			sx_destroy(&ls->ls_lock);
637 			free(ls, M_LOCKF);
638 		}
639 	} else {
640 		MPASS(state->ls_threads >= 0);
641 		state->ls_threads++;
642 		VI_UNLOCK(vp);
643 	}
644 
645 	sx_xlock(&state->ls_lock);
646 	/*
647 	 * Recheck the doomed vnode after state->ls_lock is
648 	 * locked. lf_purgelocks() requires that no new threads add
649 	 * pending locks when vnode is marked by VIRF_DOOMED flag.
650 	 */
651 	if (VN_IS_DOOMED(vp)) {
652 		VI_LOCK(vp);
653 		MPASS(state->ls_threads > 0);
654 		state->ls_threads--;
655 		wakeup(state);
656 		VI_UNLOCK(vp);
657 		sx_xunlock(&state->ls_lock);
658 		lf_free_lock(lock);
659 		return (ENOENT);
660 	}
661 
662 	switch (ap->a_op) {
663 	case F_SETLK:
664 		error = lf_setlock(state, lock, vp, ap->a_cookiep);
665 		break;
666 
667 	case F_UNLCK:
668 		error = lf_clearlock(state, lock);
669 		lf_free_lock(lock);
670 		break;
671 
672 	case F_GETLK:
673 		error = lf_getlock(state, lock, fl);
674 		lf_free_lock(lock);
675 		break;
676 
677 	case F_CANCEL:
678 		if (ap->a_cookiep)
679 			error = lf_cancel(state, lock, *ap->a_cookiep);
680 		else
681 			error = EINVAL;
682 		lf_free_lock(lock);
683 		break;
684 
685 	default:
686 		lf_free_lock(lock);
687 		error = EINVAL;
688 		break;
689 	}
690 
691 #ifdef DIAGNOSTIC
692 	/*
693 	 * Check for some can't happen stuff. In this case, the active
694 	 * lock list becoming disordered or containing mutually
695 	 * blocking locks. We also check the pending list for locks
696 	 * which should be active (i.e. have no out-going edges).
697 	 */
698 	LIST_FOREACH(lock, &state->ls_active, lf_link) {
699 		struct lockf_entry *lf;
700 		if (LIST_NEXT(lock, lf_link))
701 			KASSERT((lock->lf_start
702 				<= LIST_NEXT(lock, lf_link)->lf_start),
703 			    ("locks disordered"));
704 		LIST_FOREACH(lf, &state->ls_active, lf_link) {
705 			if (lock == lf)
706 				break;
707 			KASSERT(!lf_blocks(lock, lf),
708 			    ("two conflicting active locks"));
709 			if (lock->lf_owner == lf->lf_owner)
710 				KASSERT(!lf_overlaps(lock, lf),
711 				    ("two overlapping locks from same owner"));
712 		}
713 	}
714 	LIST_FOREACH(lock, &state->ls_pending, lf_link) {
715 		KASSERT(!LIST_EMPTY(&lock->lf_outedges),
716 		    ("pending lock which should be active"));
717 	}
718 #endif
719 	sx_xunlock(&state->ls_lock);
720 
721 	VI_LOCK(vp);
722 	MPASS(state->ls_threads > 0);
723 	state->ls_threads--;
724 	if (state->ls_threads != 0) {
725 		wakeup(state);
726 	}
727 	VI_UNLOCK(vp);
728 
729 	if (error == EDOOFUS) {
730 		KASSERT(ap->a_op == F_SETLK, ("EDOOFUS"));
731 		goto retry_setlock;
732 	}
733 	return (error);
734 }
735 
736 int
lf_advlock(struct vop_advlock_args * ap,struct lockf ** statep,u_quad_t size)737 lf_advlock(struct vop_advlock_args *ap, struct lockf **statep, u_quad_t size)
738 {
739 	struct vop_advlockasync_args a;
740 
741 	a.a_vp = ap->a_vp;
742 	a.a_id = ap->a_id;
743 	a.a_op = ap->a_op;
744 	a.a_fl = ap->a_fl;
745 	a.a_flags = ap->a_flags;
746 	a.a_task = NULL;
747 	a.a_cookiep = NULL;
748 
749 	return (lf_advlockasync(&a, statep, size));
750 }
751 
752 void
lf_purgelocks(struct vnode * vp,struct lockf ** statep)753 lf_purgelocks(struct vnode *vp, struct lockf **statep)
754 {
755 	struct lockf *state;
756 	struct lockf_entry *lock, *nlock;
757 
758 	/*
759 	 * For this to work correctly, the caller must ensure that no
760 	 * other threads enter the locking system for this vnode,
761 	 * e.g. by checking VIRF_DOOMED. We wake up any threads that are
762 	 * sleeping waiting for locks on this vnode and then free all
763 	 * the remaining locks.
764 	 */
765 	VI_LOCK(vp);
766 	KASSERT(VN_IS_DOOMED(vp),
767 	    ("lf_purgelocks: vp %p has not vgone yet", vp));
768 	state = *statep;
769 	if (state == NULL) {
770 		VI_UNLOCK(vp);
771 		return;
772 	}
773 	*statep = NULL;
774 	if (LIST_EMPTY(&state->ls_active) && state->ls_threads == 0) {
775 		KASSERT(LIST_EMPTY(&state->ls_pending),
776 		    ("freeing state with pending locks"));
777 		VI_UNLOCK(vp);
778 		goto out_free;
779 	}
780 	MPASS(state->ls_threads >= 0);
781 	state->ls_threads++;
782 	VI_UNLOCK(vp);
783 
784 	sx_xlock(&state->ls_lock);
785 	sx_xlock(&lf_owner_graph_lock);
786 	LIST_FOREACH_SAFE(lock, &state->ls_pending, lf_link, nlock) {
787 		LIST_REMOVE(lock, lf_link);
788 		lf_remove_outgoing(lock);
789 		lf_remove_incoming(lock);
790 
791 		/*
792 		 * If its an async lock, we can just free it
793 		 * here, otherwise we let the sleeping thread
794 		 * free it.
795 		 */
796 		if (lock->lf_async_task) {
797 			lf_free_lock(lock);
798 		} else {
799 			lock->lf_flags |= F_INTR;
800 			wakeup(lock);
801 		}
802 	}
803 	sx_xunlock(&lf_owner_graph_lock);
804 	sx_xunlock(&state->ls_lock);
805 
806 	/*
807 	 * Wait for all other threads, sleeping and otherwise
808 	 * to leave.
809 	 */
810 	VI_LOCK(vp);
811 	while (state->ls_threads > 1)
812 		msleep(state, VI_MTX(vp), 0, "purgelocks", 0);
813 	VI_UNLOCK(vp);
814 
815 	/*
816 	 * We can just free all the active locks since they
817 	 * will have no dependencies (we removed them all
818 	 * above). We don't need to bother locking since we
819 	 * are the last thread using this state structure.
820 	 */
821 	KASSERT(LIST_EMPTY(&state->ls_pending),
822 	    ("lock pending for %p", state));
823 	LIST_FOREACH_SAFE(lock, &state->ls_active, lf_link, nlock) {
824 		LIST_REMOVE(lock, lf_link);
825 		lf_free_lock(lock);
826 	}
827 out_free:
828 	sx_xlock(&lf_lock_states_lock);
829 	LIST_REMOVE(state, ls_link);
830 	sx_xunlock(&lf_lock_states_lock);
831 	sx_destroy(&state->ls_lock);
832 	free(state, M_LOCKF);
833 }
834 
835 /*
836  * Return non-zero if locks 'x' and 'y' overlap.
837  */
838 static int
lf_overlaps(struct lockf_entry * x,struct lockf_entry * y)839 lf_overlaps(struct lockf_entry *x, struct lockf_entry *y)
840 {
841 
842 	return (x->lf_start <= y->lf_end && x->lf_end >= y->lf_start);
843 }
844 
845 /*
846  * Return non-zero if lock 'x' is blocked by lock 'y' (or vice versa).
847  */
848 static int
lf_blocks(struct lockf_entry * x,struct lockf_entry * y)849 lf_blocks(struct lockf_entry *x, struct lockf_entry *y)
850 {
851 
852 	return x->lf_owner != y->lf_owner
853 		&& (x->lf_type == F_WRLCK || y->lf_type == F_WRLCK)
854 		&& lf_overlaps(x, y);
855 }
856 
857 /*
858  * Allocate a lock edge from the free list
859  */
860 static struct lockf_edge *
lf_alloc_edge(void)861 lf_alloc_edge(void)
862 {
863 
864 	return (malloc(sizeof(struct lockf_edge), M_LOCKF, M_WAITOK|M_ZERO));
865 }
866 
867 /*
868  * Free a lock edge.
869  */
870 static void
lf_free_edge(struct lockf_edge * e)871 lf_free_edge(struct lockf_edge *e)
872 {
873 
874 	free(e, M_LOCKF);
875 }
876 
877 /*
878  * Ensure that the lock's owner has a corresponding vertex in the
879  * owner graph.
880  */
881 static void
lf_alloc_vertex(struct lockf_entry * lock)882 lf_alloc_vertex(struct lockf_entry *lock)
883 {
884 	struct owner_graph *g = &lf_owner_graph;
885 
886 	if (!lock->lf_owner->lo_vertex)
887 		lock->lf_owner->lo_vertex =
888 			graph_alloc_vertex(g, lock->lf_owner);
889 }
890 
891 /*
892  * Attempt to record an edge from lock x to lock y. Return EDEADLK if
893  * the new edge would cause a cycle in the owner graph.
894  */
895 static int
lf_add_edge(struct lockf_entry * x,struct lockf_entry * y)896 lf_add_edge(struct lockf_entry *x, struct lockf_entry *y)
897 {
898 	struct owner_graph *g = &lf_owner_graph;
899 	struct lockf_edge *e;
900 	int error;
901 
902 #ifdef DIAGNOSTIC
903 	LIST_FOREACH(e, &x->lf_outedges, le_outlink)
904 		KASSERT(e->le_to != y, ("adding lock edge twice"));
905 #endif
906 
907 	/*
908 	 * Make sure the two owners have entries in the owner graph.
909 	 */
910 	lf_alloc_vertex(x);
911 	lf_alloc_vertex(y);
912 
913 	error = graph_add_edge(g, x->lf_owner->lo_vertex,
914 	    y->lf_owner->lo_vertex);
915 	if (error)
916 		return (error);
917 
918 	e = lf_alloc_edge();
919 	LIST_INSERT_HEAD(&x->lf_outedges, e, le_outlink);
920 	LIST_INSERT_HEAD(&y->lf_inedges, e, le_inlink);
921 	e->le_from = x;
922 	e->le_to = y;
923 
924 	return (0);
925 }
926 
927 /*
928  * Remove an edge from the lock graph.
929  */
930 static void
lf_remove_edge(struct lockf_edge * e)931 lf_remove_edge(struct lockf_edge *e)
932 {
933 	struct owner_graph *g = &lf_owner_graph;
934 	struct lockf_entry *x = e->le_from;
935 	struct lockf_entry *y = e->le_to;
936 
937 	graph_remove_edge(g, x->lf_owner->lo_vertex, y->lf_owner->lo_vertex);
938 	LIST_REMOVE(e, le_outlink);
939 	LIST_REMOVE(e, le_inlink);
940 	e->le_from = NULL;
941 	e->le_to = NULL;
942 	lf_free_edge(e);
943 }
944 
945 /*
946  * Remove all out-going edges from lock x.
947  */
948 static void
lf_remove_outgoing(struct lockf_entry * x)949 lf_remove_outgoing(struct lockf_entry *x)
950 {
951 	struct lockf_edge *e;
952 
953 	while ((e = LIST_FIRST(&x->lf_outedges)) != NULL) {
954 		lf_remove_edge(e);
955 	}
956 }
957 
958 /*
959  * Remove all in-coming edges from lock x.
960  */
961 static void
lf_remove_incoming(struct lockf_entry * x)962 lf_remove_incoming(struct lockf_entry *x)
963 {
964 	struct lockf_edge *e;
965 
966 	while ((e = LIST_FIRST(&x->lf_inedges)) != NULL) {
967 		lf_remove_edge(e);
968 	}
969 }
970 
971 /*
972  * Walk the list of locks for the file and create an out-going edge
973  * from lock to each blocking lock.
974  */
975 static int
lf_add_outgoing(struct lockf * state,struct lockf_entry * lock)976 lf_add_outgoing(struct lockf *state, struct lockf_entry *lock)
977 {
978 	struct lockf_entry *overlap;
979 	int error;
980 
981 	LIST_FOREACH(overlap, &state->ls_active, lf_link) {
982 		/*
983 		 * We may assume that the active list is sorted by
984 		 * lf_start.
985 		 */
986 		if (overlap->lf_start > lock->lf_end)
987 			break;
988 		if (!lf_blocks(lock, overlap))
989 			continue;
990 
991 		/*
992 		 * We've found a blocking lock. Add the corresponding
993 		 * edge to the graphs and see if it would cause a
994 		 * deadlock.
995 		 */
996 		error = lf_add_edge(lock, overlap);
997 
998 		/*
999 		 * The only error that lf_add_edge returns is EDEADLK.
1000 		 * Remove any edges we added and return the error.
1001 		 */
1002 		if (error) {
1003 			lf_remove_outgoing(lock);
1004 			return (error);
1005 		}
1006 	}
1007 
1008 	/*
1009 	 * We also need to add edges to sleeping locks that block
1010 	 * us. This ensures that lf_wakeup_lock cannot grant two
1011 	 * mutually blocking locks simultaneously and also enforces a
1012 	 * 'first come, first served' fairness model. Note that this
1013 	 * only happens if we are blocked by at least one active lock
1014 	 * due to the call to lf_getblock in lf_setlock below.
1015 	 */
1016 	LIST_FOREACH(overlap, &state->ls_pending, lf_link) {
1017 		if (!lf_blocks(lock, overlap))
1018 			continue;
1019 		/*
1020 		 * We've found a blocking lock. Add the corresponding
1021 		 * edge to the graphs and see if it would cause a
1022 		 * deadlock.
1023 		 */
1024 		error = lf_add_edge(lock, overlap);
1025 
1026 		/*
1027 		 * The only error that lf_add_edge returns is EDEADLK.
1028 		 * Remove any edges we added and return the error.
1029 		 */
1030 		if (error) {
1031 			lf_remove_outgoing(lock);
1032 			return (error);
1033 		}
1034 	}
1035 
1036 	return (0);
1037 }
1038 
1039 /*
1040  * Walk the list of pending locks for the file and create an in-coming
1041  * edge from lock to each blocking lock.
1042  */
1043 static int
lf_add_incoming(struct lockf * state,struct lockf_entry * lock)1044 lf_add_incoming(struct lockf *state, struct lockf_entry *lock)
1045 {
1046 	struct lockf_entry *overlap;
1047 	int error;
1048 
1049 	sx_assert(&state->ls_lock, SX_XLOCKED);
1050 	if (LIST_EMPTY(&state->ls_pending))
1051 		return (0);
1052 
1053 	error = 0;
1054 	sx_xlock(&lf_owner_graph_lock);
1055 	LIST_FOREACH(overlap, &state->ls_pending, lf_link) {
1056 		if (!lf_blocks(lock, overlap))
1057 			continue;
1058 
1059 		/*
1060 		 * We've found a blocking lock. Add the corresponding
1061 		 * edge to the graphs and see if it would cause a
1062 		 * deadlock.
1063 		 */
1064 		error = lf_add_edge(overlap, lock);
1065 
1066 		/*
1067 		 * The only error that lf_add_edge returns is EDEADLK.
1068 		 * Remove any edges we added and return the error.
1069 		 */
1070 		if (error) {
1071 			lf_remove_incoming(lock);
1072 			break;
1073 		}
1074 	}
1075 	sx_xunlock(&lf_owner_graph_lock);
1076 	return (error);
1077 }
1078 
1079 /*
1080  * Insert lock into the active list, keeping list entries ordered by
1081  * increasing values of lf_start.
1082  */
1083 static void
lf_insert_lock(struct lockf * state,struct lockf_entry * lock)1084 lf_insert_lock(struct lockf *state, struct lockf_entry *lock)
1085 {
1086 	struct lockf_entry *lf, *lfprev;
1087 
1088 	if (LIST_EMPTY(&state->ls_active)) {
1089 		LIST_INSERT_HEAD(&state->ls_active, lock, lf_link);
1090 		return;
1091 	}
1092 
1093 	lfprev = NULL;
1094 	LIST_FOREACH(lf, &state->ls_active, lf_link) {
1095 		if (lf->lf_start > lock->lf_start) {
1096 			LIST_INSERT_BEFORE(lf, lock, lf_link);
1097 			return;
1098 		}
1099 		lfprev = lf;
1100 	}
1101 	LIST_INSERT_AFTER(lfprev, lock, lf_link);
1102 }
1103 
1104 /*
1105  * Wake up a sleeping lock and remove it from the pending list now
1106  * that all its dependencies have been resolved. The caller should
1107  * arrange for the lock to be added to the active list, adjusting any
1108  * existing locks for the same owner as needed.
1109  */
1110 static void
lf_wakeup_lock(struct lockf * state,struct lockf_entry * wakelock)1111 lf_wakeup_lock(struct lockf *state, struct lockf_entry *wakelock)
1112 {
1113 
1114 	/*
1115 	 * Remove from ls_pending list and wake up the caller
1116 	 * or start the async notification, as appropriate.
1117 	 */
1118 	LIST_REMOVE(wakelock, lf_link);
1119 #ifdef LOCKF_DEBUG
1120 	if (lockf_debug & 1)
1121 		lf_print("lf_wakeup_lock: awakening", wakelock);
1122 #endif /* LOCKF_DEBUG */
1123 	if (wakelock->lf_async_task) {
1124 		taskqueue_enqueue(taskqueue_thread, wakelock->lf_async_task);
1125 	} else {
1126 		wakeup(wakelock);
1127 	}
1128 }
1129 
1130 /*
1131  * Re-check all dependent locks and remove edges to locks that we no
1132  * longer block. If 'all' is non-zero, the lock has been removed and
1133  * we must remove all the dependencies, otherwise it has simply been
1134  * reduced but remains active. Any pending locks which have been been
1135  * unblocked are added to 'granted'
1136  */
1137 static void
lf_update_dependancies(struct lockf * state,struct lockf_entry * lock,int all,struct lockf_entry_list * granted)1138 lf_update_dependancies(struct lockf *state, struct lockf_entry *lock, int all,
1139 	struct lockf_entry_list *granted)
1140 {
1141 	struct lockf_edge *e, *ne;
1142 	struct lockf_entry *deplock;
1143 
1144 	LIST_FOREACH_SAFE(e, &lock->lf_inedges, le_inlink, ne) {
1145 		deplock = e->le_from;
1146 		if (all || !lf_blocks(lock, deplock)) {
1147 			sx_xlock(&lf_owner_graph_lock);
1148 			lf_remove_edge(e);
1149 			sx_xunlock(&lf_owner_graph_lock);
1150 			if (LIST_EMPTY(&deplock->lf_outedges)) {
1151 				lf_wakeup_lock(state, deplock);
1152 				LIST_INSERT_HEAD(granted, deplock, lf_link);
1153 			}
1154 		}
1155 	}
1156 }
1157 
1158 /*
1159  * Set the start of an existing active lock, updating dependencies and
1160  * adding any newly woken locks to 'granted'.
1161  */
1162 static void
lf_set_start(struct lockf * state,struct lockf_entry * lock,off_t new_start,struct lockf_entry_list * granted)1163 lf_set_start(struct lockf *state, struct lockf_entry *lock, off_t new_start,
1164 	struct lockf_entry_list *granted)
1165 {
1166 
1167 	KASSERT(new_start >= lock->lf_start, ("can't increase lock"));
1168 	lock->lf_start = new_start;
1169 	LIST_REMOVE(lock, lf_link);
1170 	lf_insert_lock(state, lock);
1171 	lf_update_dependancies(state, lock, FALSE, granted);
1172 }
1173 
1174 /*
1175  * Set the end of an existing active lock, updating dependencies and
1176  * adding any newly woken locks to 'granted'.
1177  */
1178 static void
lf_set_end(struct lockf * state,struct lockf_entry * lock,off_t new_end,struct lockf_entry_list * granted)1179 lf_set_end(struct lockf *state, struct lockf_entry *lock, off_t new_end,
1180 	struct lockf_entry_list *granted)
1181 {
1182 
1183 	KASSERT(new_end <= lock->lf_end, ("can't increase lock"));
1184 	lock->lf_end = new_end;
1185 	lf_update_dependancies(state, lock, FALSE, granted);
1186 }
1187 
1188 /*
1189  * Add a lock to the active list, updating or removing any current
1190  * locks owned by the same owner and processing any pending locks that
1191  * become unblocked as a result. This code is also used for unlock
1192  * since the logic for updating existing locks is identical.
1193  *
1194  * As a result of processing the new lock, we may unblock existing
1195  * pending locks as a result of downgrading/unlocking. We simply
1196  * activate the newly granted locks by looping.
1197  *
1198  * Since the new lock already has its dependencies set up, we always
1199  * add it to the list (unless its an unlock request). This may
1200  * fragment the lock list in some pathological cases but its probably
1201  * not a real problem.
1202  */
1203 static void
lf_activate_lock(struct lockf * state,struct lockf_entry * lock)1204 lf_activate_lock(struct lockf *state, struct lockf_entry *lock)
1205 {
1206 	struct lockf_entry *overlap, *lf;
1207 	struct lockf_entry_list granted;
1208 	int ovcase;
1209 
1210 	LIST_INIT(&granted);
1211 	LIST_INSERT_HEAD(&granted, lock, lf_link);
1212 
1213 	while (!LIST_EMPTY(&granted)) {
1214 		lock = LIST_FIRST(&granted);
1215 		LIST_REMOVE(lock, lf_link);
1216 
1217 		/*
1218 		 * Skip over locks owned by other processes.  Handle
1219 		 * any locks that overlap and are owned by ourselves.
1220 		 */
1221 		overlap = LIST_FIRST(&state->ls_active);
1222 		for (;;) {
1223 			ovcase = lf_findoverlap(&overlap, lock, SELF);
1224 
1225 #ifdef LOCKF_DEBUG
1226 			if (ovcase && (lockf_debug & 2)) {
1227 				printf("lf_setlock: overlap %d", ovcase);
1228 				lf_print("", overlap);
1229 			}
1230 #endif
1231 			/*
1232 			 * Six cases:
1233 			 *	0) no overlap
1234 			 *	1) overlap == lock
1235 			 *	2) overlap contains lock
1236 			 *	3) lock contains overlap
1237 			 *	4) overlap starts before lock
1238 			 *	5) overlap ends after lock
1239 			 */
1240 			switch (ovcase) {
1241 			case 0: /* no overlap */
1242 				break;
1243 
1244 			case 1: /* overlap == lock */
1245 				/*
1246 				 * We have already setup the
1247 				 * dependants for the new lock, taking
1248 				 * into account a possible downgrade
1249 				 * or unlock. Remove the old lock.
1250 				 */
1251 				LIST_REMOVE(overlap, lf_link);
1252 				lf_update_dependancies(state, overlap, TRUE,
1253 					&granted);
1254 				lf_free_lock(overlap);
1255 				break;
1256 
1257 			case 2: /* overlap contains lock */
1258 				/*
1259 				 * Just split the existing lock.
1260 				 */
1261 				lf_split(state, overlap, lock, &granted);
1262 				break;
1263 
1264 			case 3: /* lock contains overlap */
1265 				/*
1266 				 * Delete the overlap and advance to
1267 				 * the next entry in the list.
1268 				 */
1269 				lf = LIST_NEXT(overlap, lf_link);
1270 				LIST_REMOVE(overlap, lf_link);
1271 				lf_update_dependancies(state, overlap, TRUE,
1272 					&granted);
1273 				lf_free_lock(overlap);
1274 				overlap = lf;
1275 				continue;
1276 
1277 			case 4: /* overlap starts before lock */
1278 				/*
1279 				 * Just update the overlap end and
1280 				 * move on.
1281 				 */
1282 				lf_set_end(state, overlap, lock->lf_start - 1,
1283 				    &granted);
1284 				overlap = LIST_NEXT(overlap, lf_link);
1285 				continue;
1286 
1287 			case 5: /* overlap ends after lock */
1288 				/*
1289 				 * Change the start of overlap and
1290 				 * re-insert.
1291 				 */
1292 				lf_set_start(state, overlap, lock->lf_end + 1,
1293 				    &granted);
1294 				break;
1295 			}
1296 			break;
1297 		}
1298 #ifdef LOCKF_DEBUG
1299 		if (lockf_debug & 1) {
1300 			if (lock->lf_type != F_UNLCK)
1301 				lf_print("lf_activate_lock: activated", lock);
1302 			else
1303 				lf_print("lf_activate_lock: unlocked", lock);
1304 			lf_printlist("lf_activate_lock", lock);
1305 		}
1306 #endif /* LOCKF_DEBUG */
1307 		if (lock->lf_type != F_UNLCK)
1308 			lf_insert_lock(state, lock);
1309 	}
1310 }
1311 
1312 /*
1313  * Cancel a pending lock request, either as a result of a signal or a
1314  * cancel request for an async lock.
1315  */
1316 static void
lf_cancel_lock(struct lockf * state,struct lockf_entry * lock)1317 lf_cancel_lock(struct lockf *state, struct lockf_entry *lock)
1318 {
1319 	struct lockf_entry_list granted;
1320 
1321 	/*
1322 	 * Note it is theoretically possible that cancelling this lock
1323 	 * may allow some other pending lock to become
1324 	 * active. Consider this case:
1325 	 *
1326 	 * Owner	Action		Result		Dependencies
1327 	 *
1328 	 * A:		lock [0..0]	succeeds
1329 	 * B:		lock [2..2]	succeeds
1330 	 * C:		lock [1..2]	blocked		C->B
1331 	 * D:		lock [0..1]	blocked		C->B,D->A,D->C
1332 	 * A:		unlock [0..0]			C->B,D->C
1333 	 * C:		cancel [1..2]
1334 	 */
1335 
1336 	LIST_REMOVE(lock, lf_link);
1337 
1338 	/*
1339 	 * Removing out-going edges is simple.
1340 	 */
1341 	sx_xlock(&lf_owner_graph_lock);
1342 	lf_remove_outgoing(lock);
1343 	sx_xunlock(&lf_owner_graph_lock);
1344 
1345 	/*
1346 	 * Removing in-coming edges may allow some other lock to
1347 	 * become active - we use lf_update_dependancies to figure
1348 	 * this out.
1349 	 */
1350 	LIST_INIT(&granted);
1351 	lf_update_dependancies(state, lock, TRUE, &granted);
1352 	lf_free_lock(lock);
1353 
1354 	/*
1355 	 * Feed any newly active locks to lf_activate_lock.
1356 	 */
1357 	while (!LIST_EMPTY(&granted)) {
1358 		lock = LIST_FIRST(&granted);
1359 		LIST_REMOVE(lock, lf_link);
1360 		lf_activate_lock(state, lock);
1361 	}
1362 }
1363 
1364 /*
1365  * Set a byte-range lock.
1366  */
1367 static int
lf_setlock(struct lockf * state,struct lockf_entry * lock,struct vnode * vp,void ** cookiep)1368 lf_setlock(struct lockf *state, struct lockf_entry *lock, struct vnode *vp,
1369     void **cookiep)
1370 {
1371 	static char lockstr[] = "lockf";
1372 	int error, priority, stops_deferred;
1373 
1374 #ifdef LOCKF_DEBUG
1375 	if (lockf_debug & 1)
1376 		lf_print("lf_setlock", lock);
1377 #endif /* LOCKF_DEBUG */
1378 
1379 	/*
1380 	 * Set the priority
1381 	 */
1382 	priority = PLOCK;
1383 	if (lock->lf_type == F_WRLCK)
1384 		priority += 4;
1385 	if (!(lock->lf_flags & F_NOINTR))
1386 		priority |= PCATCH;
1387 	/*
1388 	 * Scan lock list for this file looking for locks that would block us.
1389 	 */
1390 	if (lf_getblock(state, lock)) {
1391 		/*
1392 		 * Free the structure and return if nonblocking.
1393 		 */
1394 		if ((lock->lf_flags & F_WAIT) == 0
1395 		    && lock->lf_async_task == NULL) {
1396 			lf_free_lock(lock);
1397 			error = EAGAIN;
1398 			goto out;
1399 		}
1400 
1401 		/*
1402 		 * For flock type locks, we must first remove
1403 		 * any shared locks that we hold before we sleep
1404 		 * waiting for an exclusive lock.
1405 		 */
1406 		if ((lock->lf_flags & F_FLOCK) &&
1407 		    lock->lf_type == F_WRLCK) {
1408 			lock->lf_type = F_UNLCK;
1409 			lf_activate_lock(state, lock);
1410 			lock->lf_type = F_WRLCK;
1411 		}
1412 
1413 		/*
1414 		 * We are blocked. Create edges to each blocking lock,
1415 		 * checking for deadlock using the owner graph. For
1416 		 * simplicity, we run deadlock detection for all
1417 		 * locks, posix and otherwise.
1418 		 */
1419 		sx_xlock(&lf_owner_graph_lock);
1420 		error = lf_add_outgoing(state, lock);
1421 		sx_xunlock(&lf_owner_graph_lock);
1422 
1423 		if (error) {
1424 #ifdef LOCKF_DEBUG
1425 			if (lockf_debug & 1)
1426 				lf_print("lf_setlock: deadlock", lock);
1427 #endif
1428 			lf_free_lock(lock);
1429 			goto out;
1430 		}
1431 
1432 		/*
1433 		 * We have added edges to everything that blocks
1434 		 * us. Sleep until they all go away.
1435 		 */
1436 		LIST_INSERT_HEAD(&state->ls_pending, lock, lf_link);
1437 #ifdef LOCKF_DEBUG
1438 		if (lockf_debug & 1) {
1439 			struct lockf_edge *e;
1440 			LIST_FOREACH(e, &lock->lf_outedges, le_outlink) {
1441 				lf_print("lf_setlock: blocking on", e->le_to);
1442 				lf_printlist("lf_setlock", e->le_to);
1443 			}
1444 		}
1445 #endif /* LOCKF_DEBUG */
1446 
1447 		if ((lock->lf_flags & F_WAIT) == 0) {
1448 			/*
1449 			 * The caller requested async notification -
1450 			 * this callback happens when the blocking
1451 			 * lock is released, allowing the caller to
1452 			 * make another attempt to take the lock.
1453 			 */
1454 			*cookiep = (void *) lock;
1455 			error = EINPROGRESS;
1456 			goto out;
1457 		}
1458 
1459 		lock->lf_refs++;
1460 		stops_deferred = sigdeferstop(SIGDEFERSTOP_ERESTART);
1461 		error = sx_sleep(lock, &state->ls_lock, priority, lockstr, 0);
1462 		sigallowstop(stops_deferred);
1463 		if (lf_free_lock(lock)) {
1464 			error = EDOOFUS;
1465 			goto out;
1466 		}
1467 
1468 		/*
1469 		 * We may have been awakened by a signal and/or by a
1470 		 * debugger continuing us (in which cases we must
1471 		 * remove our lock graph edges) and/or by another
1472 		 * process releasing a lock (in which case our edges
1473 		 * have already been removed and we have been moved to
1474 		 * the active list). We may also have been woken by
1475 		 * lf_purgelocks which we report to the caller as
1476 		 * EINTR. In that case, lf_purgelocks will have
1477 		 * removed our lock graph edges.
1478 		 *
1479 		 * Note that it is possible to receive a signal after
1480 		 * we were successfully woken (and moved to the active
1481 		 * list) but before we resumed execution. In this
1482 		 * case, our lf_outedges list will be clear. We
1483 		 * pretend there was no error.
1484 		 *
1485 		 * Note also, if we have been sleeping long enough, we
1486 		 * may now have incoming edges from some newer lock
1487 		 * which is waiting behind us in the queue.
1488 		 */
1489 		if (lock->lf_flags & F_INTR) {
1490 			error = EINTR;
1491 			lf_free_lock(lock);
1492 			goto out;
1493 		}
1494 		if (LIST_EMPTY(&lock->lf_outedges)) {
1495 			error = 0;
1496 		} else {
1497 			lf_cancel_lock(state, lock);
1498 			goto out;
1499 		}
1500 #ifdef LOCKF_DEBUG
1501 		if (lockf_debug & 1) {
1502 			lf_print("lf_setlock: granted", lock);
1503 		}
1504 #endif
1505 		goto out;
1506 	}
1507 	/*
1508 	 * It looks like we are going to grant the lock. First add
1509 	 * edges from any currently pending lock that the new lock
1510 	 * would block.
1511 	 */
1512 	error = lf_add_incoming(state, lock);
1513 	if (error) {
1514 #ifdef LOCKF_DEBUG
1515 		if (lockf_debug & 1)
1516 			lf_print("lf_setlock: deadlock", lock);
1517 #endif
1518 		lf_free_lock(lock);
1519 		goto out;
1520 	}
1521 
1522 	/*
1523 	 * No blocks!!  Add the lock.  Note that we will
1524 	 * downgrade or upgrade any overlapping locks this
1525 	 * process already owns.
1526 	 */
1527 	lf_activate_lock(state, lock);
1528 	error = 0;
1529 out:
1530 	return (error);
1531 }
1532 
1533 /*
1534  * Remove a byte-range lock on an inode.
1535  *
1536  * Generally, find the lock (or an overlap to that lock)
1537  * and remove it (or shrink it), then wakeup anyone we can.
1538  */
1539 static int
lf_clearlock(struct lockf * state,struct lockf_entry * unlock)1540 lf_clearlock(struct lockf *state, struct lockf_entry *unlock)
1541 {
1542 	struct lockf_entry *overlap;
1543 
1544 	overlap = LIST_FIRST(&state->ls_active);
1545 
1546 	if (overlap == NOLOCKF)
1547 		return (0);
1548 #ifdef LOCKF_DEBUG
1549 	if (unlock->lf_type != F_UNLCK)
1550 		panic("lf_clearlock: bad type");
1551 	if (lockf_debug & 1)
1552 		lf_print("lf_clearlock", unlock);
1553 #endif /* LOCKF_DEBUG */
1554 
1555 	lf_activate_lock(state, unlock);
1556 
1557 	return (0);
1558 }
1559 
1560 /*
1561  * Check whether there is a blocking lock, and if so return its
1562  * details in '*fl'.
1563  */
1564 static int
lf_getlock(struct lockf * state,struct lockf_entry * lock,struct flock * fl)1565 lf_getlock(struct lockf *state, struct lockf_entry *lock, struct flock *fl)
1566 {
1567 	struct lockf_entry *block;
1568 
1569 #ifdef LOCKF_DEBUG
1570 	if (lockf_debug & 1)
1571 		lf_print("lf_getlock", lock);
1572 #endif /* LOCKF_DEBUG */
1573 
1574 	if ((block = lf_getblock(state, lock))) {
1575 		fl->l_type = block->lf_type;
1576 		fl->l_whence = SEEK_SET;
1577 		fl->l_start = block->lf_start;
1578 		if (block->lf_end == OFF_MAX)
1579 			fl->l_len = 0;
1580 		else
1581 			fl->l_len = block->lf_end - block->lf_start + 1;
1582 		fl->l_pid = block->lf_owner->lo_pid;
1583 		fl->l_sysid = block->lf_owner->lo_sysid;
1584 	} else {
1585 		fl->l_type = F_UNLCK;
1586 	}
1587 	return (0);
1588 }
1589 
1590 /*
1591  * Cancel an async lock request.
1592  */
1593 static int
lf_cancel(struct lockf * state,struct lockf_entry * lock,void * cookie)1594 lf_cancel(struct lockf *state, struct lockf_entry *lock, void *cookie)
1595 {
1596 	struct lockf_entry *reallock;
1597 
1598 	/*
1599 	 * We need to match this request with an existing lock
1600 	 * request.
1601 	 */
1602 	LIST_FOREACH(reallock, &state->ls_pending, lf_link) {
1603 		if ((void *) reallock == cookie) {
1604 			/*
1605 			 * Double-check that this lock looks right
1606 			 * (maybe use a rolling ID for the cancel
1607 			 * cookie instead?)
1608 			 */
1609 			if (!(reallock->lf_vnode == lock->lf_vnode
1610 				&& reallock->lf_start == lock->lf_start
1611 				&& reallock->lf_end == lock->lf_end)) {
1612 				return (ENOENT);
1613 			}
1614 
1615 			/*
1616 			 * Make sure this lock was async and then just
1617 			 * remove it from its wait lists.
1618 			 */
1619 			if (!reallock->lf_async_task) {
1620 				return (ENOENT);
1621 			}
1622 
1623 			/*
1624 			 * Note that since any other thread must take
1625 			 * state->ls_lock before it can possibly
1626 			 * trigger the async callback, we are safe
1627 			 * from a race with lf_wakeup_lock, i.e. we
1628 			 * can free the lock (actually our caller does
1629 			 * this).
1630 			 */
1631 			lf_cancel_lock(state, reallock);
1632 			return (0);
1633 		}
1634 	}
1635 
1636 	/*
1637 	 * We didn't find a matching lock - not much we can do here.
1638 	 */
1639 	return (ENOENT);
1640 }
1641 
1642 /*
1643  * Walk the list of locks for an inode and
1644  * return the first blocking lock.
1645  */
1646 static struct lockf_entry *
lf_getblock(struct lockf * state,struct lockf_entry * lock)1647 lf_getblock(struct lockf *state, struct lockf_entry *lock)
1648 {
1649 	struct lockf_entry *overlap;
1650 
1651 	LIST_FOREACH(overlap, &state->ls_active, lf_link) {
1652 		/*
1653 		 * We may assume that the active list is sorted by
1654 		 * lf_start.
1655 		 */
1656 		if (overlap->lf_start > lock->lf_end)
1657 			break;
1658 		if (!lf_blocks(lock, overlap))
1659 			continue;
1660 		return (overlap);
1661 	}
1662 	return (NOLOCKF);
1663 }
1664 
1665 /*
1666  * Walk the list of locks for an inode to find an overlapping lock (if
1667  * any) and return a classification of that overlap.
1668  *
1669  * Arguments:
1670  *	*overlap	The place in the lock list to start looking
1671  *	lock		The lock which is being tested
1672  *	type		Pass 'SELF' to test only locks with the same
1673  *			owner as lock, or 'OTHER' to test only locks
1674  *			with a different owner
1675  *
1676  * Returns one of six values:
1677  *	0) no overlap
1678  *	1) overlap == lock
1679  *	2) overlap contains lock
1680  *	3) lock contains overlap
1681  *	4) overlap starts before lock
1682  *	5) overlap ends after lock
1683  *
1684  * If there is an overlapping lock, '*overlap' is set to point at the
1685  * overlapping lock.
1686  *
1687  * NOTE: this returns only the FIRST overlapping lock.  There
1688  *	 may be more than one.
1689  */
1690 static int
lf_findoverlap(struct lockf_entry ** overlap,struct lockf_entry * lock,int type)1691 lf_findoverlap(struct lockf_entry **overlap, struct lockf_entry *lock, int type)
1692 {
1693 	struct lockf_entry *lf;
1694 	off_t start, end;
1695 	int res;
1696 
1697 	if ((*overlap) == NOLOCKF) {
1698 		return (0);
1699 	}
1700 #ifdef LOCKF_DEBUG
1701 	if (lockf_debug & 2)
1702 		lf_print("lf_findoverlap: looking for overlap in", lock);
1703 #endif /* LOCKF_DEBUG */
1704 	start = lock->lf_start;
1705 	end = lock->lf_end;
1706 	res = 0;
1707 	while (*overlap) {
1708 		lf = *overlap;
1709 		if (lf->lf_start > end)
1710 			break;
1711 		if (((type & SELF) && lf->lf_owner != lock->lf_owner) ||
1712 		    ((type & OTHERS) && lf->lf_owner == lock->lf_owner)) {
1713 			*overlap = LIST_NEXT(lf, lf_link);
1714 			continue;
1715 		}
1716 #ifdef LOCKF_DEBUG
1717 		if (lockf_debug & 2)
1718 			lf_print("\tchecking", lf);
1719 #endif /* LOCKF_DEBUG */
1720 		/*
1721 		 * OK, check for overlap
1722 		 *
1723 		 * Six cases:
1724 		 *	0) no overlap
1725 		 *	1) overlap == lock
1726 		 *	2) overlap contains lock
1727 		 *	3) lock contains overlap
1728 		 *	4) overlap starts before lock
1729 		 *	5) overlap ends after lock
1730 		 */
1731 		if (start > lf->lf_end) {
1732 			/* Case 0 */
1733 #ifdef LOCKF_DEBUG
1734 			if (lockf_debug & 2)
1735 				printf("no overlap\n");
1736 #endif /* LOCKF_DEBUG */
1737 			*overlap = LIST_NEXT(lf, lf_link);
1738 			continue;
1739 		}
1740 		if (lf->lf_start == start && lf->lf_end == end) {
1741 			/* Case 1 */
1742 #ifdef LOCKF_DEBUG
1743 			if (lockf_debug & 2)
1744 				printf("overlap == lock\n");
1745 #endif /* LOCKF_DEBUG */
1746 			res = 1;
1747 			break;
1748 		}
1749 		if (lf->lf_start <= start && lf->lf_end >= end) {
1750 			/* Case 2 */
1751 #ifdef LOCKF_DEBUG
1752 			if (lockf_debug & 2)
1753 				printf("overlap contains lock\n");
1754 #endif /* LOCKF_DEBUG */
1755 			res = 2;
1756 			break;
1757 		}
1758 		if (start <= lf->lf_start && end >= lf->lf_end) {
1759 			/* Case 3 */
1760 #ifdef LOCKF_DEBUG
1761 			if (lockf_debug & 2)
1762 				printf("lock contains overlap\n");
1763 #endif /* LOCKF_DEBUG */
1764 			res = 3;
1765 			break;
1766 		}
1767 		if (lf->lf_start < start && lf->lf_end >= start) {
1768 			/* Case 4 */
1769 #ifdef LOCKF_DEBUG
1770 			if (lockf_debug & 2)
1771 				printf("overlap starts before lock\n");
1772 #endif /* LOCKF_DEBUG */
1773 			res = 4;
1774 			break;
1775 		}
1776 		if (lf->lf_start > start && lf->lf_end > end) {
1777 			/* Case 5 */
1778 #ifdef LOCKF_DEBUG
1779 			if (lockf_debug & 2)
1780 				printf("overlap ends after lock\n");
1781 #endif /* LOCKF_DEBUG */
1782 			res = 5;
1783 			break;
1784 		}
1785 		panic("lf_findoverlap: default");
1786 	}
1787 	return (res);
1788 }
1789 
1790 /*
1791  * Split an the existing 'lock1', based on the extent of the lock
1792  * described by 'lock2'. The existing lock should cover 'lock2'
1793  * entirely.
1794  *
1795  * Any pending locks which have been been unblocked are added to
1796  * 'granted'
1797  */
1798 static void
lf_split(struct lockf * state,struct lockf_entry * lock1,struct lockf_entry * lock2,struct lockf_entry_list * granted)1799 lf_split(struct lockf *state, struct lockf_entry *lock1,
1800     struct lockf_entry *lock2, struct lockf_entry_list *granted)
1801 {
1802 	struct lockf_entry *splitlock;
1803 
1804 #ifdef LOCKF_DEBUG
1805 	if (lockf_debug & 2) {
1806 		lf_print("lf_split", lock1);
1807 		lf_print("splitting from", lock2);
1808 	}
1809 #endif /* LOCKF_DEBUG */
1810 	/*
1811 	 * Check to see if we don't need to split at all.
1812 	 */
1813 	if (lock1->lf_start == lock2->lf_start) {
1814 		lf_set_start(state, lock1, lock2->lf_end + 1, granted);
1815 		return;
1816 	}
1817 	if (lock1->lf_end == lock2->lf_end) {
1818 		lf_set_end(state, lock1, lock2->lf_start - 1, granted);
1819 		return;
1820 	}
1821 	/*
1822 	 * Make a new lock consisting of the last part of
1823 	 * the encompassing lock.
1824 	 */
1825 	splitlock = lf_alloc_lock(lock1->lf_owner);
1826 	memcpy(splitlock, lock1, sizeof *splitlock);
1827 	splitlock->lf_refs = 1;
1828 	if (splitlock->lf_flags & F_REMOTE)
1829 		vref(splitlock->lf_vnode);
1830 
1831 	/*
1832 	 * This cannot cause a deadlock since any edges we would add
1833 	 * to splitlock already exist in lock1. We must be sure to add
1834 	 * necessary dependencies to splitlock before we reduce lock1
1835 	 * otherwise we may accidentally grant a pending lock that
1836 	 * was blocked by the tail end of lock1.
1837 	 */
1838 	splitlock->lf_start = lock2->lf_end + 1;
1839 	LIST_INIT(&splitlock->lf_outedges);
1840 	LIST_INIT(&splitlock->lf_inedges);
1841 	lf_add_incoming(state, splitlock);
1842 
1843 	lf_set_end(state, lock1, lock2->lf_start - 1, granted);
1844 
1845 	/*
1846 	 * OK, now link it in
1847 	 */
1848 	lf_insert_lock(state, splitlock);
1849 }
1850 
1851 struct lockdesc {
1852 	STAILQ_ENTRY(lockdesc) link;
1853 	struct vnode *vp;
1854 	struct flock fl;
1855 };
1856 STAILQ_HEAD(lockdesclist, lockdesc);
1857 
1858 int
lf_iteratelocks_sysid(int sysid,lf_iterator * fn,void * arg)1859 lf_iteratelocks_sysid(int sysid, lf_iterator *fn, void *arg)
1860 {
1861 	struct lockf *ls;
1862 	struct lockf_entry *lf;
1863 	struct lockdesc *ldesc;
1864 	struct lockdesclist locks;
1865 	int error;
1866 
1867 	/*
1868 	 * In order to keep the locking simple, we iterate over the
1869 	 * active lock lists to build a list of locks that need
1870 	 * releasing. We then call the iterator for each one in turn.
1871 	 *
1872 	 * We take an extra reference to the vnode for the duration to
1873 	 * make sure it doesn't go away before we are finished.
1874 	 */
1875 	STAILQ_INIT(&locks);
1876 	sx_xlock(&lf_lock_states_lock);
1877 	LIST_FOREACH(ls, &lf_lock_states, ls_link) {
1878 		sx_xlock(&ls->ls_lock);
1879 		LIST_FOREACH(lf, &ls->ls_active, lf_link) {
1880 			if (lf->lf_owner->lo_sysid != sysid)
1881 				continue;
1882 
1883 			ldesc = malloc(sizeof(struct lockdesc), M_LOCKF,
1884 			    M_WAITOK);
1885 			ldesc->vp = lf->lf_vnode;
1886 			vref(ldesc->vp);
1887 			ldesc->fl.l_start = lf->lf_start;
1888 			if (lf->lf_end == OFF_MAX)
1889 				ldesc->fl.l_len = 0;
1890 			else
1891 				ldesc->fl.l_len =
1892 					lf->lf_end - lf->lf_start + 1;
1893 			ldesc->fl.l_whence = SEEK_SET;
1894 			ldesc->fl.l_type = F_UNLCK;
1895 			ldesc->fl.l_pid = lf->lf_owner->lo_pid;
1896 			ldesc->fl.l_sysid = sysid;
1897 			STAILQ_INSERT_TAIL(&locks, ldesc, link);
1898 		}
1899 		sx_xunlock(&ls->ls_lock);
1900 	}
1901 	sx_xunlock(&lf_lock_states_lock);
1902 
1903 	/*
1904 	 * Call the iterator function for each lock in turn. If the
1905 	 * iterator returns an error code, just free the rest of the
1906 	 * lockdesc structures.
1907 	 */
1908 	error = 0;
1909 	while ((ldesc = STAILQ_FIRST(&locks)) != NULL) {
1910 		STAILQ_REMOVE_HEAD(&locks, link);
1911 		if (!error)
1912 			error = fn(ldesc->vp, &ldesc->fl, arg);
1913 		vrele(ldesc->vp);
1914 		free(ldesc, M_LOCKF);
1915 	}
1916 
1917 	return (error);
1918 }
1919 
1920 int
lf_iteratelocks_vnode(struct vnode * vp,lf_iterator * fn,void * arg)1921 lf_iteratelocks_vnode(struct vnode *vp, lf_iterator *fn, void *arg)
1922 {
1923 	struct lockf *ls;
1924 	struct lockf_entry *lf;
1925 	struct lockdesc *ldesc;
1926 	struct lockdesclist locks;
1927 	int error;
1928 
1929 	/*
1930 	 * In order to keep the locking simple, we iterate over the
1931 	 * active lock lists to build a list of locks that need
1932 	 * releasing. We then call the iterator for each one in turn.
1933 	 *
1934 	 * We take an extra reference to the vnode for the duration to
1935 	 * make sure it doesn't go away before we are finished.
1936 	 */
1937 	STAILQ_INIT(&locks);
1938 	VI_LOCK(vp);
1939 	ls = vp->v_lockf;
1940 	if (!ls) {
1941 		VI_UNLOCK(vp);
1942 		return (0);
1943 	}
1944 	MPASS(ls->ls_threads >= 0);
1945 	ls->ls_threads++;
1946 	VI_UNLOCK(vp);
1947 
1948 	sx_xlock(&ls->ls_lock);
1949 	LIST_FOREACH(lf, &ls->ls_active, lf_link) {
1950 		ldesc = malloc(sizeof(struct lockdesc), M_LOCKF,
1951 		    M_WAITOK);
1952 		ldesc->vp = lf->lf_vnode;
1953 		vref(ldesc->vp);
1954 		ldesc->fl.l_start = lf->lf_start;
1955 		if (lf->lf_end == OFF_MAX)
1956 			ldesc->fl.l_len = 0;
1957 		else
1958 			ldesc->fl.l_len =
1959 				lf->lf_end - lf->lf_start + 1;
1960 		ldesc->fl.l_whence = SEEK_SET;
1961 		ldesc->fl.l_type = F_UNLCK;
1962 		ldesc->fl.l_pid = lf->lf_owner->lo_pid;
1963 		ldesc->fl.l_sysid = lf->lf_owner->lo_sysid;
1964 		STAILQ_INSERT_TAIL(&locks, ldesc, link);
1965 	}
1966 	sx_xunlock(&ls->ls_lock);
1967 	VI_LOCK(vp);
1968 	MPASS(ls->ls_threads > 0);
1969 	ls->ls_threads--;
1970 	wakeup(ls);
1971 	VI_UNLOCK(vp);
1972 
1973 	/*
1974 	 * Call the iterator function for each lock in turn. If the
1975 	 * iterator returns an error code, just free the rest of the
1976 	 * lockdesc structures.
1977 	 */
1978 	error = 0;
1979 	while ((ldesc = STAILQ_FIRST(&locks)) != NULL) {
1980 		STAILQ_REMOVE_HEAD(&locks, link);
1981 		if (!error)
1982 			error = fn(ldesc->vp, &ldesc->fl, arg);
1983 		vrele(ldesc->vp);
1984 		free(ldesc, M_LOCKF);
1985 	}
1986 
1987 	return (error);
1988 }
1989 
1990 static int
lf_clearremotesys_iterator(struct vnode * vp,struct flock * fl,void * arg)1991 lf_clearremotesys_iterator(struct vnode *vp, struct flock *fl, void *arg)
1992 {
1993 
1994 	VOP_ADVLOCK(vp, 0, F_UNLCK, fl, F_REMOTE);
1995 	return (0);
1996 }
1997 
1998 void
lf_clearremotesys(int sysid)1999 lf_clearremotesys(int sysid)
2000 {
2001 
2002 	KASSERT(sysid != 0, ("Can't clear local locks with F_UNLCKSYS"));
2003 	lf_iteratelocks_sysid(sysid, lf_clearremotesys_iterator, NULL);
2004 }
2005 
2006 int
lf_countlocks(int sysid)2007 lf_countlocks(int sysid)
2008 {
2009 	int i;
2010 	struct lock_owner *lo;
2011 	int count;
2012 
2013 	count = 0;
2014 	for (i = 0; i < LOCK_OWNER_HASH_SIZE; i++) {
2015 		sx_xlock(&lf_lock_owners[i].lock);
2016 		LIST_FOREACH(lo, &lf_lock_owners[i].list, lo_link)
2017 			if (lo->lo_sysid == sysid)
2018 				count += lo->lo_refs;
2019 		sx_xunlock(&lf_lock_owners[i].lock);
2020 	}
2021 
2022 	return (count);
2023 }
2024 
2025 #ifdef LOCKF_DEBUG
2026 
2027 /*
2028  * Return non-zero if y is reachable from x using a brute force
2029  * search. If reachable and path is non-null, return the route taken
2030  * in path.
2031  */
2032 static int
graph_reaches(struct owner_vertex * x,struct owner_vertex * y,struct owner_vertex_list * path)2033 graph_reaches(struct owner_vertex *x, struct owner_vertex *y,
2034     struct owner_vertex_list *path)
2035 {
2036 	struct owner_edge *e;
2037 
2038 	if (x == y) {
2039 		if (path)
2040 			TAILQ_INSERT_HEAD(path, x, v_link);
2041 		return 1;
2042 	}
2043 
2044 	LIST_FOREACH(e, &x->v_outedges, e_outlink) {
2045 		if (graph_reaches(e->e_to, y, path)) {
2046 			if (path)
2047 				TAILQ_INSERT_HEAD(path, x, v_link);
2048 			return 1;
2049 		}
2050 	}
2051 	return 0;
2052 }
2053 
2054 /*
2055  * Perform consistency checks on the graph. Make sure the values of
2056  * v_order are correct. If checkorder is non-zero, check no vertex can
2057  * reach any other vertex with a smaller order.
2058  */
2059 static void
graph_check(struct owner_graph * g,int checkorder)2060 graph_check(struct owner_graph *g, int checkorder)
2061 {
2062 	int i, j;
2063 
2064 	for (i = 0; i < g->g_size; i++) {
2065 		if (!g->g_vertices[i]->v_owner)
2066 			continue;
2067 		KASSERT(g->g_vertices[i]->v_order == i,
2068 		    ("lock graph vertices disordered"));
2069 		if (checkorder) {
2070 			for (j = 0; j < i; j++) {
2071 				if (!g->g_vertices[j]->v_owner)
2072 					continue;
2073 				KASSERT(!graph_reaches(g->g_vertices[i],
2074 					g->g_vertices[j], NULL),
2075 				    ("lock graph vertices disordered"));
2076 			}
2077 		}
2078 	}
2079 }
2080 
2081 static void
graph_print_vertices(struct owner_vertex_list * set)2082 graph_print_vertices(struct owner_vertex_list *set)
2083 {
2084 	struct owner_vertex *v;
2085 
2086 	printf("{ ");
2087 	TAILQ_FOREACH(v, set, v_link) {
2088 		printf("%d:", v->v_order);
2089 		lf_print_owner(v->v_owner);
2090 		if (TAILQ_NEXT(v, v_link))
2091 			printf(", ");
2092 	}
2093 	printf(" }\n");
2094 }
2095 
2096 #endif
2097 
2098 /*
2099  * Calculate the sub-set of vertices v from the affected region [y..x]
2100  * where v is reachable from y. Return -1 if a loop was detected
2101  * (i.e. x is reachable from y, otherwise the number of vertices in
2102  * this subset.
2103  */
2104 static int
graph_delta_forward(struct owner_graph * g,struct owner_vertex * x,struct owner_vertex * y,struct owner_vertex_list * delta)2105 graph_delta_forward(struct owner_graph *g, struct owner_vertex *x,
2106     struct owner_vertex *y, struct owner_vertex_list *delta)
2107 {
2108 	uint32_t gen;
2109 	struct owner_vertex *v;
2110 	struct owner_edge *e;
2111 	int n;
2112 
2113 	/*
2114 	 * We start with a set containing just y. Then for each vertex
2115 	 * v in the set so far unprocessed, we add each vertex that v
2116 	 * has an out-edge to and that is within the affected region
2117 	 * [y..x]. If we see the vertex x on our travels, stop
2118 	 * immediately.
2119 	 */
2120 	TAILQ_INIT(delta);
2121 	TAILQ_INSERT_TAIL(delta, y, v_link);
2122 	v = y;
2123 	n = 1;
2124 	gen = g->g_gen;
2125 	while (v) {
2126 		LIST_FOREACH(e, &v->v_outedges, e_outlink) {
2127 			if (e->e_to == x)
2128 				return -1;
2129 			if (e->e_to->v_order < x->v_order
2130 			    && e->e_to->v_gen != gen) {
2131 				e->e_to->v_gen = gen;
2132 				TAILQ_INSERT_TAIL(delta, e->e_to, v_link);
2133 				n++;
2134 			}
2135 		}
2136 		v = TAILQ_NEXT(v, v_link);
2137 	}
2138 
2139 	return (n);
2140 }
2141 
2142 /*
2143  * Calculate the sub-set of vertices v from the affected region [y..x]
2144  * where v reaches x. Return the number of vertices in this subset.
2145  */
2146 static int
graph_delta_backward(struct owner_graph * g,struct owner_vertex * x,struct owner_vertex * y,struct owner_vertex_list * delta)2147 graph_delta_backward(struct owner_graph *g, struct owner_vertex *x,
2148     struct owner_vertex *y, struct owner_vertex_list *delta)
2149 {
2150 	uint32_t gen;
2151 	struct owner_vertex *v;
2152 	struct owner_edge *e;
2153 	int n;
2154 
2155 	/*
2156 	 * We start with a set containing just x. Then for each vertex
2157 	 * v in the set so far unprocessed, we add each vertex that v
2158 	 * has an in-edge from and that is within the affected region
2159 	 * [y..x].
2160 	 */
2161 	TAILQ_INIT(delta);
2162 	TAILQ_INSERT_TAIL(delta, x, v_link);
2163 	v = x;
2164 	n = 1;
2165 	gen = g->g_gen;
2166 	while (v) {
2167 		LIST_FOREACH(e, &v->v_inedges, e_inlink) {
2168 			if (e->e_from->v_order > y->v_order
2169 			    && e->e_from->v_gen != gen) {
2170 				e->e_from->v_gen = gen;
2171 				TAILQ_INSERT_HEAD(delta, e->e_from, v_link);
2172 				n++;
2173 			}
2174 		}
2175 		v = TAILQ_PREV(v, owner_vertex_list, v_link);
2176 	}
2177 
2178 	return (n);
2179 }
2180 
2181 static int
graph_add_indices(int * indices,int n,struct owner_vertex_list * set)2182 graph_add_indices(int *indices, int n, struct owner_vertex_list *set)
2183 {
2184 	struct owner_vertex *v;
2185 	int i, j;
2186 
2187 	TAILQ_FOREACH(v, set, v_link) {
2188 		for (i = n;
2189 		     i > 0 && indices[i - 1] > v->v_order; i--)
2190 			;
2191 		for (j = n - 1; j >= i; j--)
2192 			indices[j + 1] = indices[j];
2193 		indices[i] = v->v_order;
2194 		n++;
2195 	}
2196 
2197 	return (n);
2198 }
2199 
2200 static int
graph_assign_indices(struct owner_graph * g,int * indices,int nextunused,struct owner_vertex_list * set)2201 graph_assign_indices(struct owner_graph *g, int *indices, int nextunused,
2202     struct owner_vertex_list *set)
2203 {
2204 	struct owner_vertex *v, *vlowest;
2205 
2206 	while (!TAILQ_EMPTY(set)) {
2207 		vlowest = NULL;
2208 		TAILQ_FOREACH(v, set, v_link) {
2209 			if (!vlowest || v->v_order < vlowest->v_order)
2210 				vlowest = v;
2211 		}
2212 		TAILQ_REMOVE(set, vlowest, v_link);
2213 		vlowest->v_order = indices[nextunused];
2214 		g->g_vertices[vlowest->v_order] = vlowest;
2215 		nextunused++;
2216 	}
2217 
2218 	return (nextunused);
2219 }
2220 
2221 static int
graph_add_edge(struct owner_graph * g,struct owner_vertex * x,struct owner_vertex * y)2222 graph_add_edge(struct owner_graph *g, struct owner_vertex *x,
2223     struct owner_vertex *y)
2224 {
2225 	struct owner_edge *e;
2226 	struct owner_vertex_list deltaF, deltaB;
2227 	int nF, n, vi, i;
2228 	int *indices;
2229 	int nB __unused;
2230 
2231 	sx_assert(&lf_owner_graph_lock, SX_XLOCKED);
2232 
2233 	LIST_FOREACH(e, &x->v_outedges, e_outlink) {
2234 		if (e->e_to == y) {
2235 			e->e_refs++;
2236 			return (0);
2237 		}
2238 	}
2239 
2240 #ifdef LOCKF_DEBUG
2241 	if (lockf_debug & 8) {
2242 		printf("adding edge %d:", x->v_order);
2243 		lf_print_owner(x->v_owner);
2244 		printf(" -> %d:", y->v_order);
2245 		lf_print_owner(y->v_owner);
2246 		printf("\n");
2247 	}
2248 #endif
2249 	if (y->v_order < x->v_order) {
2250 		/*
2251 		 * The new edge violates the order. First find the set
2252 		 * of affected vertices reachable from y (deltaF) and
2253 		 * the set of affect vertices affected that reach x
2254 		 * (deltaB), using the graph generation number to
2255 		 * detect whether we have visited a given vertex
2256 		 * already. We re-order the graph so that each vertex
2257 		 * in deltaB appears before each vertex in deltaF.
2258 		 *
2259 		 * If x is a member of deltaF, then the new edge would
2260 		 * create a cycle. Otherwise, we may assume that
2261 		 * deltaF and deltaB are disjoint.
2262 		 */
2263 		g->g_gen++;
2264 		if (g->g_gen == 0) {
2265 			/*
2266 			 * Generation wrap.
2267 			 */
2268 			for (vi = 0; vi < g->g_size; vi++) {
2269 				g->g_vertices[vi]->v_gen = 0;
2270 			}
2271 			g->g_gen++;
2272 		}
2273 		nF = graph_delta_forward(g, x, y, &deltaF);
2274 		if (nF < 0) {
2275 #ifdef LOCKF_DEBUG
2276 			if (lockf_debug & 8) {
2277 				struct owner_vertex_list path;
2278 				printf("deadlock: ");
2279 				TAILQ_INIT(&path);
2280 				graph_reaches(y, x, &path);
2281 				graph_print_vertices(&path);
2282 			}
2283 #endif
2284 			return (EDEADLK);
2285 		}
2286 
2287 #ifdef LOCKF_DEBUG
2288 		if (lockf_debug & 8) {
2289 			printf("re-ordering graph vertices\n");
2290 			printf("deltaF = ");
2291 			graph_print_vertices(&deltaF);
2292 		}
2293 #endif
2294 
2295 		nB = graph_delta_backward(g, x, y, &deltaB);
2296 
2297 #ifdef LOCKF_DEBUG
2298 		if (lockf_debug & 8) {
2299 			printf("deltaB = ");
2300 			graph_print_vertices(&deltaB);
2301 		}
2302 #endif
2303 
2304 		/*
2305 		 * We first build a set of vertex indices (vertex
2306 		 * order values) that we may use, then we re-assign
2307 		 * orders first to those vertices in deltaB, then to
2308 		 * deltaF. Note that the contents of deltaF and deltaB
2309 		 * may be partially disordered - we perform an
2310 		 * insertion sort while building our index set.
2311 		 */
2312 		indices = g->g_indexbuf;
2313 		n = graph_add_indices(indices, 0, &deltaF);
2314 		graph_add_indices(indices, n, &deltaB);
2315 
2316 		/*
2317 		 * We must also be sure to maintain the relative
2318 		 * ordering of deltaF and deltaB when re-assigning
2319 		 * vertices. We do this by iteratively removing the
2320 		 * lowest ordered element from the set and assigning
2321 		 * it the next value from our new ordering.
2322 		 */
2323 		i = graph_assign_indices(g, indices, 0, &deltaB);
2324 		graph_assign_indices(g, indices, i, &deltaF);
2325 
2326 #ifdef LOCKF_DEBUG
2327 		if (lockf_debug & 8) {
2328 			struct owner_vertex_list set;
2329 			TAILQ_INIT(&set);
2330 			for (i = 0; i < nB + nF; i++)
2331 				TAILQ_INSERT_TAIL(&set,
2332 				    g->g_vertices[indices[i]], v_link);
2333 			printf("new ordering = ");
2334 			graph_print_vertices(&set);
2335 		}
2336 #endif
2337 	}
2338 
2339 	KASSERT(x->v_order < y->v_order, ("Failed to re-order graph"));
2340 
2341 #ifdef LOCKF_DEBUG
2342 	if (lockf_debug & 8) {
2343 		graph_check(g, TRUE);
2344 	}
2345 #endif
2346 
2347 	e = malloc(sizeof(struct owner_edge), M_LOCKF, M_WAITOK);
2348 
2349 	LIST_INSERT_HEAD(&x->v_outedges, e, e_outlink);
2350 	LIST_INSERT_HEAD(&y->v_inedges, e, e_inlink);
2351 	e->e_refs = 1;
2352 	e->e_from = x;
2353 	e->e_to = y;
2354 
2355 	return (0);
2356 }
2357 
2358 /*
2359  * Remove an edge x->y from the graph.
2360  */
2361 static void
graph_remove_edge(struct owner_graph * g,struct owner_vertex * x,struct owner_vertex * y)2362 graph_remove_edge(struct owner_graph *g, struct owner_vertex *x,
2363     struct owner_vertex *y)
2364 {
2365 	struct owner_edge *e;
2366 
2367 	sx_assert(&lf_owner_graph_lock, SX_XLOCKED);
2368 
2369 	LIST_FOREACH(e, &x->v_outedges, e_outlink) {
2370 		if (e->e_to == y)
2371 			break;
2372 	}
2373 	KASSERT(e, ("Removing non-existent edge from deadlock graph"));
2374 
2375 	e->e_refs--;
2376 	if (e->e_refs == 0) {
2377 #ifdef LOCKF_DEBUG
2378 		if (lockf_debug & 8) {
2379 			printf("removing edge %d:", x->v_order);
2380 			lf_print_owner(x->v_owner);
2381 			printf(" -> %d:", y->v_order);
2382 			lf_print_owner(y->v_owner);
2383 			printf("\n");
2384 		}
2385 #endif
2386 		LIST_REMOVE(e, e_outlink);
2387 		LIST_REMOVE(e, e_inlink);
2388 		free(e, M_LOCKF);
2389 	}
2390 }
2391 
2392 /*
2393  * Allocate a vertex from the free list. Return ENOMEM if there are
2394  * none.
2395  */
2396 static struct owner_vertex *
graph_alloc_vertex(struct owner_graph * g,struct lock_owner * lo)2397 graph_alloc_vertex(struct owner_graph *g, struct lock_owner *lo)
2398 {
2399 	struct owner_vertex *v;
2400 
2401 	sx_assert(&lf_owner_graph_lock, SX_XLOCKED);
2402 
2403 	v = malloc(sizeof(struct owner_vertex), M_LOCKF, M_WAITOK);
2404 	if (g->g_size == g->g_space) {
2405 		g->g_vertices = realloc(g->g_vertices,
2406 		    2 * g->g_space * sizeof(struct owner_vertex *),
2407 		    M_LOCKF, M_WAITOK);
2408 		free(g->g_indexbuf, M_LOCKF);
2409 		g->g_indexbuf = malloc(2 * g->g_space * sizeof(int),
2410 		    M_LOCKF, M_WAITOK);
2411 		g->g_space = 2 * g->g_space;
2412 	}
2413 	v->v_order = g->g_size;
2414 	v->v_gen = g->g_gen;
2415 	g->g_vertices[g->g_size] = v;
2416 	g->g_size++;
2417 
2418 	LIST_INIT(&v->v_outedges);
2419 	LIST_INIT(&v->v_inedges);
2420 	v->v_owner = lo;
2421 
2422 	return (v);
2423 }
2424 
2425 static void
graph_free_vertex(struct owner_graph * g,struct owner_vertex * v)2426 graph_free_vertex(struct owner_graph *g, struct owner_vertex *v)
2427 {
2428 	struct owner_vertex *w;
2429 	int i;
2430 
2431 	sx_assert(&lf_owner_graph_lock, SX_XLOCKED);
2432 
2433 	KASSERT(LIST_EMPTY(&v->v_outedges), ("Freeing vertex with edges"));
2434 	KASSERT(LIST_EMPTY(&v->v_inedges), ("Freeing vertex with edges"));
2435 
2436 	/*
2437 	 * Remove from the graph's array and close up the gap,
2438 	 * renumbering the other vertices.
2439 	 */
2440 	for (i = v->v_order + 1; i < g->g_size; i++) {
2441 		w = g->g_vertices[i];
2442 		w->v_order--;
2443 		g->g_vertices[i - 1] = w;
2444 	}
2445 	g->g_size--;
2446 
2447 	free(v, M_LOCKF);
2448 }
2449 
2450 static struct owner_graph *
graph_init(struct owner_graph * g)2451 graph_init(struct owner_graph *g)
2452 {
2453 
2454 	g->g_vertices = malloc(10 * sizeof(struct owner_vertex *),
2455 	    M_LOCKF, M_WAITOK);
2456 	g->g_size = 0;
2457 	g->g_space = 10;
2458 	g->g_indexbuf = malloc(g->g_space * sizeof(int), M_LOCKF, M_WAITOK);
2459 	g->g_gen = 0;
2460 
2461 	return (g);
2462 }
2463 
2464 struct kinfo_lockf_linked {
2465 	struct kinfo_lockf kl;
2466 	struct vnode *vp;
2467 	STAILQ_ENTRY(kinfo_lockf_linked) link;
2468 };
2469 
2470 int
vfs_report_lockf(struct mount * mp,struct sbuf * sb)2471 vfs_report_lockf(struct mount *mp, struct sbuf *sb)
2472 {
2473 	struct lockf *ls;
2474 	struct lockf_entry *lf;
2475 	struct kinfo_lockf_linked *klf;
2476 	struct vnode *vp;
2477 	struct ucred *ucred;
2478 	char *fullpath, *freepath;
2479 	struct stat stt;
2480 	STAILQ_HEAD(, kinfo_lockf_linked) locks;
2481 	int error, gerror;
2482 
2483 	STAILQ_INIT(&locks);
2484 	sx_slock(&lf_lock_states_lock);
2485 	LIST_FOREACH(ls, &lf_lock_states, ls_link) {
2486 		sx_slock(&ls->ls_lock);
2487 		LIST_FOREACH(lf, &ls->ls_active, lf_link) {
2488 			vp = lf->lf_vnode;
2489 			if (VN_IS_DOOMED(vp) || vp->v_mount != mp)
2490 				continue;
2491 			vhold(vp);
2492 			klf = malloc(sizeof(struct kinfo_lockf_linked),
2493 			    M_LOCKF, M_WAITOK | M_ZERO);
2494 			klf->vp = vp;
2495 			klf->kl.kl_structsize = sizeof(struct kinfo_lockf);
2496 			klf->kl.kl_start = lf->lf_start;
2497 			klf->kl.kl_len = lf->lf_end == OFF_MAX ? 0 :
2498 			    lf->lf_end - lf->lf_start + 1;
2499 			klf->kl.kl_rw = lf->lf_type == F_RDLCK ?
2500 			    KLOCKF_RW_READ : KLOCKF_RW_WRITE;
2501 			if (lf->lf_owner->lo_sysid != 0) {
2502 				klf->kl.kl_pid = lf->lf_owner->lo_pid;
2503 				klf->kl.kl_sysid = lf->lf_owner->lo_sysid;
2504 				klf->kl.kl_type = KLOCKF_TYPE_REMOTE;
2505 			} else if (lf->lf_owner->lo_pid == -1) {
2506 				klf->kl.kl_pid = -1;
2507 				klf->kl.kl_sysid = 0;
2508 				klf->kl.kl_type = KLOCKF_TYPE_FLOCK;
2509 			} else {
2510 				klf->kl.kl_pid = lf->lf_owner->lo_pid;
2511 				klf->kl.kl_sysid = 0;
2512 				klf->kl.kl_type = KLOCKF_TYPE_PID;
2513 			}
2514 			STAILQ_INSERT_TAIL(&locks, klf, link);
2515 		}
2516 		sx_sunlock(&ls->ls_lock);
2517 	}
2518 	sx_sunlock(&lf_lock_states_lock);
2519 
2520 	gerror = 0;
2521 	ucred = curthread->td_ucred;
2522 	while ((klf = STAILQ_FIRST(&locks)) != NULL) {
2523 		STAILQ_REMOVE_HEAD(&locks, link);
2524 		vp = klf->vp;
2525 		if (gerror == 0 && vn_lock(vp, LK_SHARED) == 0) {
2526 			error = prison_canseemount(ucred, vp->v_mount);
2527 			if (error == 0)
2528 				error = VOP_STAT(vp, &stt, ucred, NOCRED,
2529 				    curthread);
2530 			VOP_UNLOCK(vp);
2531 			if (error == 0) {
2532 				klf->kl.kl_file_fsid = stt.st_dev;
2533 				klf->kl.kl_file_rdev = stt.st_rdev;
2534 				klf->kl.kl_file_fileid = stt.st_ino;
2535 				freepath = NULL;
2536 				fullpath = "-";
2537 				error = vn_fullpath(vp, &fullpath, &freepath);
2538 				if (error == 0)
2539 					strlcpy(klf->kl.kl_path, fullpath,
2540 					    sizeof(klf->kl.kl_path));
2541 				free(freepath, M_TEMP);
2542 				if (sbuf_bcat(sb, &klf->kl,
2543 				    klf->kl.kl_structsize) != 0) {
2544 					gerror = sbuf_error(sb);
2545 				}
2546 			}
2547 		}
2548 		vdrop(vp);
2549 		free(klf, M_LOCKF);
2550 	}
2551 
2552 	return (gerror);
2553 }
2554 
2555 static int
sysctl_kern_lockf_run(struct sbuf * sb)2556 sysctl_kern_lockf_run(struct sbuf *sb)
2557 {
2558 	struct mount *mp;
2559 	int error;
2560 
2561 	error = 0;
2562 	mtx_lock(&mountlist_mtx);
2563 	TAILQ_FOREACH(mp, &mountlist, mnt_list) {
2564 		error = vfs_busy(mp, MBF_MNTLSTLOCK);
2565 		if (error != 0)
2566 			continue;
2567 		error = mp->mnt_op->vfs_report_lockf(mp, sb);
2568 		mtx_lock(&mountlist_mtx);
2569 		vfs_unbusy(mp);
2570 		if (error != 0)
2571 			break;
2572 	}
2573 	mtx_unlock(&mountlist_mtx);
2574 	return (error);
2575 }
2576 
2577 static int
sysctl_kern_lockf(SYSCTL_HANDLER_ARGS)2578 sysctl_kern_lockf(SYSCTL_HANDLER_ARGS)
2579 {
2580 	struct sbuf sb;
2581 	int error, error2;
2582 
2583 	sbuf_new_for_sysctl(&sb, NULL, sizeof(struct kinfo_lockf) * 5, req);
2584 	sbuf_clear_flags(&sb, SBUF_INCLUDENUL);
2585 	error = sysctl_kern_lockf_run(&sb);
2586 	error2 = sbuf_finish(&sb);
2587 	sbuf_delete(&sb);
2588 	return (error != 0 ? error : error2);
2589 }
2590 SYSCTL_PROC(_kern, KERN_LOCKF, lockf,
2591     CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
2592     0, 0, sysctl_kern_lockf, "S,lockf",
2593     "Advisory locks table");
2594 
2595 #ifdef LOCKF_DEBUG
2596 /*
2597  * Print description of a lock owner
2598  */
2599 static void
lf_print_owner(struct lock_owner * lo)2600 lf_print_owner(struct lock_owner *lo)
2601 {
2602 
2603 	if (lo->lo_flags & F_REMOTE) {
2604 		printf("remote pid %d, system %d",
2605 		    lo->lo_pid, lo->lo_sysid);
2606 	} else if (lo->lo_flags & F_FLOCK) {
2607 		printf("file %p", lo->lo_id);
2608 	} else {
2609 		printf("local pid %d", lo->lo_pid);
2610 	}
2611 }
2612 
2613 /*
2614  * Print out a lock.
2615  */
2616 static void
lf_print(char * tag,struct lockf_entry * lock)2617 lf_print(char *tag, struct lockf_entry *lock)
2618 {
2619 
2620 	printf("%s: lock %p for ", tag, (void *)lock);
2621 	lf_print_owner(lock->lf_owner);
2622 	printf("\nvnode %p", lock->lf_vnode);
2623 	VOP_PRINT(lock->lf_vnode);
2624 	printf(" %s, start %jd, end ",
2625 	    lock->lf_type == F_RDLCK ? "shared" :
2626 	    lock->lf_type == F_WRLCK ? "exclusive" :
2627 	    lock->lf_type == F_UNLCK ? "unlock" : "unknown",
2628 	    (intmax_t)lock->lf_start);
2629 	if (lock->lf_end == OFF_MAX)
2630 		printf("EOF");
2631 	else
2632 		printf("%jd", (intmax_t)lock->lf_end);
2633 	if (!LIST_EMPTY(&lock->lf_outedges))
2634 		printf(" block %p\n",
2635 		    (void *)LIST_FIRST(&lock->lf_outedges)->le_to);
2636 	else
2637 		printf("\n");
2638 }
2639 
2640 static void
lf_printlist(char * tag,struct lockf_entry * lock)2641 lf_printlist(char *tag, struct lockf_entry *lock)
2642 {
2643 	struct lockf_entry *lf, *blk;
2644 	struct lockf_edge *e;
2645 
2646 	printf("%s: Lock list for vnode %p:\n", tag, lock->lf_vnode);
2647 	LIST_FOREACH(lf, &lock->lf_vnode->v_lockf->ls_active, lf_link) {
2648 		printf("\tlock %p for ",(void *)lf);
2649 		lf_print_owner(lock->lf_owner);
2650 		printf(", %s, start %jd, end %jd",
2651 		    lf->lf_type == F_RDLCK ? "shared" :
2652 		    lf->lf_type == F_WRLCK ? "exclusive" :
2653 		    lf->lf_type == F_UNLCK ? "unlock" :
2654 		    "unknown", (intmax_t)lf->lf_start, (intmax_t)lf->lf_end);
2655 		LIST_FOREACH(e, &lf->lf_outedges, le_outlink) {
2656 			blk = e->le_to;
2657 			printf("\n\t\tlock request %p for ", (void *)blk);
2658 			lf_print_owner(blk->lf_owner);
2659 			printf(", %s, start %jd, end %jd",
2660 			    blk->lf_type == F_RDLCK ? "shared" :
2661 			    blk->lf_type == F_WRLCK ? "exclusive" :
2662 			    blk->lf_type == F_UNLCK ? "unlock" :
2663 			    "unknown", (intmax_t)blk->lf_start,
2664 			    (intmax_t)blk->lf_end);
2665 			if (!LIST_EMPTY(&blk->lf_inedges))
2666 				panic("lf_printlist: bad list");
2667 		}
2668 		printf("\n");
2669 	}
2670 }
2671 #endif /* LOCKF_DEBUG */
2672