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