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