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