]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/vfs_subr.c
vfs: introduce vnode sequence counters
[FreeBSD/FreeBSD.git] / sys / kern / vfs_subr.c
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1989, 1993
5  *      The Regents of the University of California.  All rights reserved.
6  * (c) UNIX System Laboratories, Inc.
7  * All or some portions of this file are derived from material licensed
8  * to the University of California by American Telephone and Telegraph
9  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
10  * the permission of UNIX System Laboratories, Inc.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  *      @(#)vfs_subr.c  8.31 (Berkeley) 5/26/95
37  */
38
39 /*
40  * External virtual filesystem routines
41  */
42
43 #include <sys/cdefs.h>
44 __FBSDID("$FreeBSD$");
45
46 #include "opt_ddb.h"
47 #include "opt_watchdog.h"
48
49 #include <sys/param.h>
50 #include <sys/systm.h>
51 #include <sys/bio.h>
52 #include <sys/buf.h>
53 #include <sys/capsicum.h>
54 #include <sys/condvar.h>
55 #include <sys/conf.h>
56 #include <sys/counter.h>
57 #include <sys/dirent.h>
58 #include <sys/event.h>
59 #include <sys/eventhandler.h>
60 #include <sys/extattr.h>
61 #include <sys/file.h>
62 #include <sys/fcntl.h>
63 #include <sys/jail.h>
64 #include <sys/kdb.h>
65 #include <sys/kernel.h>
66 #include <sys/kthread.h>
67 #include <sys/ktr.h>
68 #include <sys/lockf.h>
69 #include <sys/malloc.h>
70 #include <sys/mount.h>
71 #include <sys/namei.h>
72 #include <sys/pctrie.h>
73 #include <sys/priv.h>
74 #include <sys/reboot.h>
75 #include <sys/refcount.h>
76 #include <sys/rwlock.h>
77 #include <sys/sched.h>
78 #include <sys/sleepqueue.h>
79 #include <sys/smr.h>
80 #include <sys/smp.h>
81 #include <sys/stat.h>
82 #include <sys/sysctl.h>
83 #include <sys/syslog.h>
84 #include <sys/vmmeter.h>
85 #include <sys/vnode.h>
86 #include <sys/watchdog.h>
87
88 #include <machine/stdarg.h>
89
90 #include <security/mac/mac_framework.h>
91
92 #include <vm/vm.h>
93 #include <vm/vm_object.h>
94 #include <vm/vm_extern.h>
95 #include <vm/pmap.h>
96 #include <vm/vm_map.h>
97 #include <vm/vm_page.h>
98 #include <vm/vm_kern.h>
99 #include <vm/uma.h>
100
101 #ifdef DDB
102 #include <ddb/ddb.h>
103 #endif
104
105 static void     delmntque(struct vnode *vp);
106 static int      flushbuflist(struct bufv *bufv, int flags, struct bufobj *bo,
107                     int slpflag, int slptimeo);
108 static void     syncer_shutdown(void *arg, int howto);
109 static int      vtryrecycle(struct vnode *vp);
110 static void     v_init_counters(struct vnode *);
111 static void     v_incr_devcount(struct vnode *);
112 static void     v_decr_devcount(struct vnode *);
113 static void     vgonel(struct vnode *);
114 static void     vfs_knllock(void *arg);
115 static void     vfs_knlunlock(void *arg);
116 static void     vfs_knl_assert_locked(void *arg);
117 static void     vfs_knl_assert_unlocked(void *arg);
118 static void     destroy_vpollinfo(struct vpollinfo *vi);
119 static int      v_inval_buf_range_locked(struct vnode *vp, struct bufobj *bo,
120                     daddr_t startlbn, daddr_t endlbn);
121 static void     vnlru_recalc(void);
122
123 /*
124  * These fences are intended for cases where some synchronization is
125  * needed between access of v_iflags and lockless vnode refcount (v_holdcnt
126  * and v_usecount) updates.  Access to v_iflags is generally synchronized
127  * by the interlock, but we have some internal assertions that check vnode
128  * flags without acquiring the lock.  Thus, these fences are INVARIANTS-only
129  * for now.
130  */
131 #ifdef INVARIANTS
132 #define VNODE_REFCOUNT_FENCE_ACQ()      atomic_thread_fence_acq()
133 #define VNODE_REFCOUNT_FENCE_REL()      atomic_thread_fence_rel()
134 #else
135 #define VNODE_REFCOUNT_FENCE_ACQ()
136 #define VNODE_REFCOUNT_FENCE_REL()
137 #endif
138
139 /*
140  * Number of vnodes in existence.  Increased whenever getnewvnode()
141  * allocates a new vnode, decreased in vdropl() for VIRF_DOOMED vnode.
142  */
143 static u_long __exclusive_cache_line numvnodes;
144
145 SYSCTL_ULONG(_vfs, OID_AUTO, numvnodes, CTLFLAG_RD, &numvnodes, 0,
146     "Number of vnodes in existence");
147
148 static counter_u64_t vnodes_created;
149 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, vnodes_created, CTLFLAG_RD, &vnodes_created,
150     "Number of vnodes created by getnewvnode");
151
152 /*
153  * Conversion tables for conversion from vnode types to inode formats
154  * and back.
155  */
156 enum vtype iftovt_tab[16] = {
157         VNON, VFIFO, VCHR, VNON, VDIR, VNON, VBLK, VNON,
158         VREG, VNON, VLNK, VNON, VSOCK, VNON, VNON, VNON
159 };
160 int vttoif_tab[10] = {
161         0, S_IFREG, S_IFDIR, S_IFBLK, S_IFCHR, S_IFLNK,
162         S_IFSOCK, S_IFIFO, S_IFMT, S_IFMT
163 };
164
165 /*
166  * List of allocates vnodes in the system.
167  */
168 static TAILQ_HEAD(freelst, vnode) vnode_list;
169 static struct vnode *vnode_list_free_marker;
170 static struct vnode *vnode_list_reclaim_marker;
171
172 /*
173  * "Free" vnode target.  Free vnodes are rarely completely free, but are
174  * just ones that are cheap to recycle.  Usually they are for files which
175  * have been stat'd but not read; these usually have inode and namecache
176  * data attached to them.  This target is the preferred minimum size of a
177  * sub-cache consisting mostly of such files. The system balances the size
178  * of this sub-cache with its complement to try to prevent either from
179  * thrashing while the other is relatively inactive.  The targets express
180  * a preference for the best balance.
181  *
182  * "Above" this target there are 2 further targets (watermarks) related
183  * to recyling of free vnodes.  In the best-operating case, the cache is
184  * exactly full, the free list has size between vlowat and vhiwat above the
185  * free target, and recycling from it and normal use maintains this state.
186  * Sometimes the free list is below vlowat or even empty, but this state
187  * is even better for immediate use provided the cache is not full.
188  * Otherwise, vnlru_proc() runs to reclaim enough vnodes (usually non-free
189  * ones) to reach one of these states.  The watermarks are currently hard-
190  * coded as 4% and 9% of the available space higher.  These and the default
191  * of 25% for wantfreevnodes are too large if the memory size is large.
192  * E.g., 9% of 75% of MAXVNODES is more than 566000 vnodes to reclaim
193  * whenever vnlru_proc() becomes active.
194  */
195 static long wantfreevnodes;
196 static long __exclusive_cache_line freevnodes;
197 SYSCTL_ULONG(_vfs, OID_AUTO, freevnodes, CTLFLAG_RD,
198     &freevnodes, 0, "Number of \"free\" vnodes");
199 static long freevnodes_old;
200
201 static counter_u64_t recycles_count;
202 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, recycles, CTLFLAG_RD, &recycles_count,
203     "Number of vnodes recycled to meet vnode cache targets");
204
205 static counter_u64_t recycles_free_count;
206 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, recycles_free, CTLFLAG_RD, &recycles_free_count,
207     "Number of free vnodes recycled to meet vnode cache targets");
208
209 /*
210  * Various variables used for debugging the new implementation of
211  * reassignbuf().
212  * XXX these are probably of (very) limited utility now.
213  */
214 static int reassignbufcalls;
215 SYSCTL_INT(_vfs, OID_AUTO, reassignbufcalls, CTLFLAG_RW | CTLFLAG_STATS,
216     &reassignbufcalls, 0, "Number of calls to reassignbuf");
217
218 static counter_u64_t deferred_inact;
219 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, deferred_inact, CTLFLAG_RD, &deferred_inact,
220     "Number of times inactive processing was deferred");
221
222 /* To keep more than one thread at a time from running vfs_getnewfsid */
223 static struct mtx mntid_mtx;
224
225 /*
226  * Lock for any access to the following:
227  *      vnode_list
228  *      numvnodes
229  *      freevnodes
230  */
231 static struct mtx __exclusive_cache_line vnode_list_mtx;
232
233 /* Publicly exported FS */
234 struct nfs_public nfs_pub;
235
236 static uma_zone_t buf_trie_zone;
237 static smr_t buf_trie_smr;
238
239 /* Zone for allocation of new vnodes - used exclusively by getnewvnode() */
240 static uma_zone_t vnode_zone;
241 static uma_zone_t vnodepoll_zone;
242
243 __read_frequently smr_t vfs_smr;
244
245 /*
246  * The workitem queue.
247  *
248  * It is useful to delay writes of file data and filesystem metadata
249  * for tens of seconds so that quickly created and deleted files need
250  * not waste disk bandwidth being created and removed. To realize this,
251  * we append vnodes to a "workitem" queue. When running with a soft
252  * updates implementation, most pending metadata dependencies should
253  * not wait for more than a few seconds. Thus, mounted on block devices
254  * are delayed only about a half the time that file data is delayed.
255  * Similarly, directory updates are more critical, so are only delayed
256  * about a third the time that file data is delayed. Thus, there are
257  * SYNCER_MAXDELAY queues that are processed round-robin at a rate of
258  * one each second (driven off the filesystem syncer process). The
259  * syncer_delayno variable indicates the next queue that is to be processed.
260  * Items that need to be processed soon are placed in this queue:
261  *
262  *      syncer_workitem_pending[syncer_delayno]
263  *
264  * A delay of fifteen seconds is done by placing the request fifteen
265  * entries later in the queue:
266  *
267  *      syncer_workitem_pending[(syncer_delayno + 15) & syncer_mask]
268  *
269  */
270 static int syncer_delayno;
271 static long syncer_mask;
272 LIST_HEAD(synclist, bufobj);
273 static struct synclist *syncer_workitem_pending;
274 /*
275  * The sync_mtx protects:
276  *      bo->bo_synclist
277  *      sync_vnode_count
278  *      syncer_delayno
279  *      syncer_state
280  *      syncer_workitem_pending
281  *      syncer_worklist_len
282  *      rushjob
283  */
284 static struct mtx sync_mtx;
285 static struct cv sync_wakeup;
286
287 #define SYNCER_MAXDELAY         32
288 static int syncer_maxdelay = SYNCER_MAXDELAY;   /* maximum delay time */
289 static int syncdelay = 30;              /* max time to delay syncing data */
290 static int filedelay = 30;              /* time to delay syncing files */
291 SYSCTL_INT(_kern, OID_AUTO, filedelay, CTLFLAG_RW, &filedelay, 0,
292     "Time to delay syncing files (in seconds)");
293 static int dirdelay = 29;               /* time to delay syncing directories */
294 SYSCTL_INT(_kern, OID_AUTO, dirdelay, CTLFLAG_RW, &dirdelay, 0,
295     "Time to delay syncing directories (in seconds)");
296 static int metadelay = 28;              /* time to delay syncing metadata */
297 SYSCTL_INT(_kern, OID_AUTO, metadelay, CTLFLAG_RW, &metadelay, 0,
298     "Time to delay syncing metadata (in seconds)");
299 static int rushjob;             /* number of slots to run ASAP */
300 static int stat_rush_requests;  /* number of times I/O speeded up */
301 SYSCTL_INT(_debug, OID_AUTO, rush_requests, CTLFLAG_RW, &stat_rush_requests, 0,
302     "Number of times I/O speeded up (rush requests)");
303
304 #define VDBATCH_SIZE 8
305 struct vdbatch {
306         u_int index;
307         long freevnodes;
308         struct mtx lock;
309         struct vnode *tab[VDBATCH_SIZE];
310 };
311 DPCPU_DEFINE_STATIC(struct vdbatch, vd);
312
313 static void     vdbatch_dequeue(struct vnode *vp);
314
315 /*
316  * When shutting down the syncer, run it at four times normal speed.
317  */
318 #define SYNCER_SHUTDOWN_SPEEDUP         4
319 static int sync_vnode_count;
320 static int syncer_worklist_len;
321 static enum { SYNCER_RUNNING, SYNCER_SHUTTING_DOWN, SYNCER_FINAL_DELAY }
322     syncer_state;
323
324 /* Target for maximum number of vnodes. */
325 u_long desiredvnodes;
326 static u_long gapvnodes;                /* gap between wanted and desired */
327 static u_long vhiwat;           /* enough extras after expansion */
328 static u_long vlowat;           /* minimal extras before expansion */
329 static u_long vstir;            /* nonzero to stir non-free vnodes */
330 static volatile int vsmalltrigger = 8;  /* pref to keep if > this many pages */
331
332 static u_long vnlru_read_freevnodes(void);
333
334 /*
335  * Note that no attempt is made to sanitize these parameters.
336  */
337 static int
338 sysctl_maxvnodes(SYSCTL_HANDLER_ARGS)
339 {
340         u_long val;
341         int error;
342
343         val = desiredvnodes;
344         error = sysctl_handle_long(oidp, &val, 0, req);
345         if (error != 0 || req->newptr == NULL)
346                 return (error);
347
348         if (val == desiredvnodes)
349                 return (0);
350         mtx_lock(&vnode_list_mtx);
351         desiredvnodes = val;
352         wantfreevnodes = desiredvnodes / 4;
353         vnlru_recalc();
354         mtx_unlock(&vnode_list_mtx);
355         /*
356          * XXX There is no protection against multiple threads changing
357          * desiredvnodes at the same time. Locking above only helps vnlru and
358          * getnewvnode.
359          */
360         vfs_hash_changesize(desiredvnodes);
361         cache_changesize(desiredvnodes);
362         return (0);
363 }
364
365 SYSCTL_PROC(_kern, KERN_MAXVNODES, maxvnodes,
366     CTLTYPE_ULONG | CTLFLAG_MPSAFE | CTLFLAG_RW, NULL, 0, sysctl_maxvnodes,
367     "LU", "Target for maximum number of vnodes");
368
369 static int
370 sysctl_wantfreevnodes(SYSCTL_HANDLER_ARGS)
371 {
372         u_long val;
373         int error;
374
375         val = wantfreevnodes;
376         error = sysctl_handle_long(oidp, &val, 0, req);
377         if (error != 0 || req->newptr == NULL)
378                 return (error);
379
380         if (val == wantfreevnodes)
381                 return (0);
382         mtx_lock(&vnode_list_mtx);
383         wantfreevnodes = val;
384         vnlru_recalc();
385         mtx_unlock(&vnode_list_mtx);
386         return (0);
387 }
388
389 SYSCTL_PROC(_vfs, OID_AUTO, wantfreevnodes,
390     CTLTYPE_ULONG | CTLFLAG_MPSAFE | CTLFLAG_RW, NULL, 0, sysctl_wantfreevnodes,
391     "LU", "Target for minimum number of \"free\" vnodes");
392
393 SYSCTL_ULONG(_kern, OID_AUTO, minvnodes, CTLFLAG_RW,
394     &wantfreevnodes, 0, "Old name for vfs.wantfreevnodes (legacy)");
395 static int vnlru_nowhere;
396 SYSCTL_INT(_debug, OID_AUTO, vnlru_nowhere, CTLFLAG_RW,
397     &vnlru_nowhere, 0, "Number of times the vnlru process ran without success");
398
399 static int
400 sysctl_try_reclaim_vnode(SYSCTL_HANDLER_ARGS)
401 {
402         struct vnode *vp;
403         struct nameidata nd;
404         char *buf;
405         unsigned long ndflags;
406         int error;
407
408         if (req->newptr == NULL)
409                 return (EINVAL);
410         if (req->newlen >= PATH_MAX)
411                 return (E2BIG);
412
413         buf = malloc(PATH_MAX, M_TEMP, M_WAITOK);
414         error = SYSCTL_IN(req, buf, req->newlen);
415         if (error != 0)
416                 goto out;
417
418         buf[req->newlen] = '\0';
419
420         ndflags = LOCKLEAF | NOFOLLOW | AUDITVNODE1 | NOCACHE | SAVENAME;
421         NDINIT(&nd, LOOKUP, ndflags, UIO_SYSSPACE, buf, curthread);
422         if ((error = namei(&nd)) != 0)
423                 goto out;
424         vp = nd.ni_vp;
425
426         if (VN_IS_DOOMED(vp)) {
427                 /*
428                  * This vnode is being recycled.  Return != 0 to let the caller
429                  * know that the sysctl had no effect.  Return EAGAIN because a
430                  * subsequent call will likely succeed (since namei will create
431                  * a new vnode if necessary)
432                  */
433                 error = EAGAIN;
434                 goto putvnode;
435         }
436
437         counter_u64_add(recycles_count, 1);
438         vgone(vp);
439 putvnode:
440         NDFREE(&nd, 0);
441 out:
442         free(buf, M_TEMP);
443         return (error);
444 }
445
446 static int
447 sysctl_ftry_reclaim_vnode(SYSCTL_HANDLER_ARGS)
448 {
449         struct thread *td = curthread;
450         struct vnode *vp;
451         struct file *fp;
452         int error;
453         int fd;
454
455         if (req->newptr == NULL)
456                 return (EBADF);
457
458         error = sysctl_handle_int(oidp, &fd, 0, req);
459         if (error != 0)
460                 return (error);
461         error = getvnode(curthread, fd, &cap_fcntl_rights, &fp);
462         if (error != 0)
463                 return (error);
464         vp = fp->f_vnode;
465
466         error = vn_lock(vp, LK_EXCLUSIVE);
467         if (error != 0)
468                 goto drop;
469
470         counter_u64_add(recycles_count, 1);
471         vgone(vp);
472         VOP_UNLOCK(vp);
473 drop:
474         fdrop(fp, td);
475         return (error);
476 }
477
478 SYSCTL_PROC(_debug, OID_AUTO, try_reclaim_vnode,
479     CTLTYPE_STRING | CTLFLAG_MPSAFE | CTLFLAG_WR, NULL, 0,
480     sysctl_try_reclaim_vnode, "A", "Try to reclaim a vnode by its pathname");
481 SYSCTL_PROC(_debug, OID_AUTO, ftry_reclaim_vnode,
482     CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_WR, NULL, 0,
483     sysctl_ftry_reclaim_vnode, "I",
484     "Try to reclaim a vnode by its file descriptor");
485
486 /* Shift count for (uintptr_t)vp to initialize vp->v_hash. */
487 static int vnsz2log;
488
489 /*
490  * Support for the bufobj clean & dirty pctrie.
491  */
492 static void *
493 buf_trie_alloc(struct pctrie *ptree)
494 {
495         return (uma_zalloc_smr(buf_trie_zone, M_NOWAIT));
496 }
497
498 static void
499 buf_trie_free(struct pctrie *ptree, void *node)
500 {
501         uma_zfree_smr(buf_trie_zone, node);
502 }
503 PCTRIE_DEFINE_SMR(BUF, buf, b_lblkno, buf_trie_alloc, buf_trie_free,
504     buf_trie_smr);
505
506 /*
507  * Initialize the vnode management data structures.
508  *
509  * Reevaluate the following cap on the number of vnodes after the physical
510  * memory size exceeds 512GB.  In the limit, as the physical memory size
511  * grows, the ratio of the memory size in KB to vnodes approaches 64:1.
512  */
513 #ifndef MAXVNODES_MAX
514 #define MAXVNODES_MAX   (512UL * 1024 * 1024 / 64)      /* 8M */
515 #endif
516
517 static MALLOC_DEFINE(M_VNODE_MARKER, "vnodemarker", "vnode marker");
518
519 static struct vnode *
520 vn_alloc_marker(struct mount *mp)
521 {
522         struct vnode *vp;
523
524         vp = malloc(sizeof(struct vnode), M_VNODE_MARKER, M_WAITOK | M_ZERO);
525         vp->v_type = VMARKER;
526         vp->v_mount = mp;
527
528         return (vp);
529 }
530
531 static void
532 vn_free_marker(struct vnode *vp)
533 {
534
535         MPASS(vp->v_type == VMARKER);
536         free(vp, M_VNODE_MARKER);
537 }
538
539 /*
540  * Initialize a vnode as it first enters the zone.
541  */
542 static int
543 vnode_init(void *mem, int size, int flags)
544 {
545         struct vnode *vp;
546
547         vp = mem;
548         bzero(vp, size);
549         /*
550          * Setup locks.
551          */
552         vp->v_vnlock = &vp->v_lock;
553         mtx_init(&vp->v_interlock, "vnode interlock", NULL, MTX_DEF);
554         /*
555          * By default, don't allow shared locks unless filesystems opt-in.
556          */
557         lockinit(vp->v_vnlock, PVFS, "vnode", VLKTIMEOUT,
558             LK_NOSHARE | LK_IS_VNODE);
559         /*
560          * Initialize bufobj.
561          */
562         bufobj_init(&vp->v_bufobj, vp);
563         /*
564          * Initialize namecache.
565          */
566         LIST_INIT(&vp->v_cache_src);
567         TAILQ_INIT(&vp->v_cache_dst);
568         /*
569          * Initialize rangelocks.
570          */
571         rangelock_init(&vp->v_rl);
572
573         vp->v_dbatchcpu = NOCPU;
574
575         mtx_lock(&vnode_list_mtx);
576         TAILQ_INSERT_BEFORE(vnode_list_free_marker, vp, v_vnodelist);
577         mtx_unlock(&vnode_list_mtx);
578         return (0);
579 }
580
581 /*
582  * Free a vnode when it is cleared from the zone.
583  */
584 static void
585 vnode_fini(void *mem, int size)
586 {
587         struct vnode *vp;
588         struct bufobj *bo;
589
590         vp = mem;
591         vdbatch_dequeue(vp);
592         mtx_lock(&vnode_list_mtx);
593         TAILQ_REMOVE(&vnode_list, vp, v_vnodelist);
594         mtx_unlock(&vnode_list_mtx);
595         rangelock_destroy(&vp->v_rl);
596         lockdestroy(vp->v_vnlock);
597         mtx_destroy(&vp->v_interlock);
598         bo = &vp->v_bufobj;
599         rw_destroy(BO_LOCKPTR(bo));
600 }
601
602 /*
603  * Provide the size of NFS nclnode and NFS fh for calculation of the
604  * vnode memory consumption.  The size is specified directly to
605  * eliminate dependency on NFS-private header.
606  *
607  * Other filesystems may use bigger or smaller (like UFS and ZFS)
608  * private inode data, but the NFS-based estimation is ample enough.
609  * Still, we care about differences in the size between 64- and 32-bit
610  * platforms.
611  *
612  * Namecache structure size is heuristically
613  * sizeof(struct namecache_ts) + CACHE_PATH_CUTOFF + 1.
614  */
615 #ifdef _LP64
616 #define NFS_NCLNODE_SZ  (528 + 64)
617 #define NC_SZ           148
618 #else
619 #define NFS_NCLNODE_SZ  (360 + 32)
620 #define NC_SZ           92
621 #endif
622
623 static void
624 vntblinit(void *dummy __unused)
625 {
626         struct vdbatch *vd;
627         int cpu, physvnodes, virtvnodes;
628         u_int i;
629
630         /*
631          * Desiredvnodes is a function of the physical memory size and the
632          * kernel's heap size.  Generally speaking, it scales with the
633          * physical memory size.  The ratio of desiredvnodes to the physical
634          * memory size is 1:16 until desiredvnodes exceeds 98,304.
635          * Thereafter, the
636          * marginal ratio of desiredvnodes to the physical memory size is
637          * 1:64.  However, desiredvnodes is limited by the kernel's heap
638          * size.  The memory required by desiredvnodes vnodes and vm objects
639          * must not exceed 1/10th of the kernel's heap size.
640          */
641         physvnodes = maxproc + pgtok(vm_cnt.v_page_count) / 64 +
642             3 * min(98304 * 16, pgtok(vm_cnt.v_page_count)) / 64;
643         virtvnodes = vm_kmem_size / (10 * (sizeof(struct vm_object) +
644             sizeof(struct vnode) + NC_SZ * ncsizefactor + NFS_NCLNODE_SZ));
645         desiredvnodes = min(physvnodes, virtvnodes);
646         if (desiredvnodes > MAXVNODES_MAX) {
647                 if (bootverbose)
648                         printf("Reducing kern.maxvnodes %lu -> %lu\n",
649                             desiredvnodes, MAXVNODES_MAX);
650                 desiredvnodes = MAXVNODES_MAX;
651         }
652         wantfreevnodes = desiredvnodes / 4;
653         mtx_init(&mntid_mtx, "mntid", NULL, MTX_DEF);
654         TAILQ_INIT(&vnode_list);
655         mtx_init(&vnode_list_mtx, "vnode_list", NULL, MTX_DEF);
656         /*
657          * The lock is taken to appease WITNESS.
658          */
659         mtx_lock(&vnode_list_mtx);
660         vnlru_recalc();
661         mtx_unlock(&vnode_list_mtx);
662         vnode_list_free_marker = vn_alloc_marker(NULL);
663         TAILQ_INSERT_HEAD(&vnode_list, vnode_list_free_marker, v_vnodelist);
664         vnode_list_reclaim_marker = vn_alloc_marker(NULL);
665         TAILQ_INSERT_HEAD(&vnode_list, vnode_list_reclaim_marker, v_vnodelist);
666         vnode_zone = uma_zcreate("VNODE", sizeof (struct vnode), NULL, NULL,
667             vnode_init, vnode_fini, UMA_ALIGN_PTR, UMA_ZONE_SMR);
668         vfs_smr = uma_zone_get_smr(vnode_zone);
669         vnodepoll_zone = uma_zcreate("VNODEPOLL", sizeof (struct vpollinfo),
670             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
671         /*
672          * Preallocate enough nodes to support one-per buf so that
673          * we can not fail an insert.  reassignbuf() callers can not
674          * tolerate the insertion failure.
675          */
676         buf_trie_zone = uma_zcreate("BUF TRIE", pctrie_node_size(),
677             NULL, NULL, pctrie_zone_init, NULL, UMA_ALIGN_PTR, 
678             UMA_ZONE_NOFREE | UMA_ZONE_SMR);
679         buf_trie_smr = uma_zone_get_smr(buf_trie_zone);
680         uma_prealloc(buf_trie_zone, nbuf);
681
682         vnodes_created = counter_u64_alloc(M_WAITOK);
683         recycles_count = counter_u64_alloc(M_WAITOK);
684         recycles_free_count = counter_u64_alloc(M_WAITOK);
685         deferred_inact = counter_u64_alloc(M_WAITOK);
686
687         /*
688          * Initialize the filesystem syncer.
689          */
690         syncer_workitem_pending = hashinit(syncer_maxdelay, M_VNODE,
691             &syncer_mask);
692         syncer_maxdelay = syncer_mask + 1;
693         mtx_init(&sync_mtx, "Syncer mtx", NULL, MTX_DEF);
694         cv_init(&sync_wakeup, "syncer");
695         for (i = 1; i <= sizeof(struct vnode); i <<= 1)
696                 vnsz2log++;
697         vnsz2log--;
698
699         CPU_FOREACH(cpu) {
700                 vd = DPCPU_ID_PTR((cpu), vd);
701                 bzero(vd, sizeof(*vd));
702                 mtx_init(&vd->lock, "vdbatch", NULL, MTX_DEF);
703         }
704 }
705 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_FIRST, vntblinit, NULL);
706
707 /*
708  * Mark a mount point as busy. Used to synchronize access and to delay
709  * unmounting. Eventually, mountlist_mtx is not released on failure.
710  *
711  * vfs_busy() is a custom lock, it can block the caller.
712  * vfs_busy() only sleeps if the unmount is active on the mount point.
713  * For a mountpoint mp, vfs_busy-enforced lock is before lock of any
714  * vnode belonging to mp.
715  *
716  * Lookup uses vfs_busy() to traverse mount points.
717  * root fs                      var fs
718  * / vnode lock         A       / vnode lock (/var)             D
719  * /var vnode lock      B       /log vnode lock(/var/log)       E
720  * vfs_busy lock        C       vfs_busy lock                   F
721  *
722  * Within each file system, the lock order is C->A->B and F->D->E.
723  *
724  * When traversing across mounts, the system follows that lock order:
725  *
726  *        C->A->B
727  *              |
728  *              +->F->D->E
729  *
730  * The lookup() process for namei("/var") illustrates the process:
731  *  VOP_LOOKUP() obtains B while A is held
732  *  vfs_busy() obtains a shared lock on F while A and B are held
733  *  vput() releases lock on B
734  *  vput() releases lock on A
735  *  VFS_ROOT() obtains lock on D while shared lock on F is held
736  *  vfs_unbusy() releases shared lock on F
737  *  vn_lock() obtains lock on deadfs vnode vp_crossmp instead of A.
738  *    Attempt to lock A (instead of vp_crossmp) while D is held would
739  *    violate the global order, causing deadlocks.
740  *
741  * dounmount() locks B while F is drained.
742  */
743 int
744 vfs_busy(struct mount *mp, int flags)
745 {
746
747         MPASS((flags & ~MBF_MASK) == 0);
748         CTR3(KTR_VFS, "%s: mp %p with flags %d", __func__, mp, flags);
749
750         if (vfs_op_thread_enter(mp)) {
751                 MPASS((mp->mnt_kern_flag & MNTK_DRAINING) == 0);
752                 MPASS((mp->mnt_kern_flag & MNTK_UNMOUNT) == 0);
753                 MPASS((mp->mnt_kern_flag & MNTK_REFEXPIRE) == 0);
754                 vfs_mp_count_add_pcpu(mp, ref, 1);
755                 vfs_mp_count_add_pcpu(mp, lockref, 1);
756                 vfs_op_thread_exit(mp);
757                 if (flags & MBF_MNTLSTLOCK)
758                         mtx_unlock(&mountlist_mtx);
759                 return (0);
760         }
761
762         MNT_ILOCK(mp);
763         vfs_assert_mount_counters(mp);
764         MNT_REF(mp);
765         /*
766          * If mount point is currently being unmounted, sleep until the
767          * mount point fate is decided.  If thread doing the unmounting fails,
768          * it will clear MNTK_UNMOUNT flag before waking us up, indicating
769          * that this mount point has survived the unmount attempt and vfs_busy
770          * should retry.  Otherwise the unmounter thread will set MNTK_REFEXPIRE
771          * flag in addition to MNTK_UNMOUNT, indicating that mount point is
772          * about to be really destroyed.  vfs_busy needs to release its
773          * reference on the mount point in this case and return with ENOENT,
774          * telling the caller that mount mount it tried to busy is no longer
775          * valid.
776          */
777         while (mp->mnt_kern_flag & MNTK_UNMOUNT) {
778                 if (flags & MBF_NOWAIT || mp->mnt_kern_flag & MNTK_REFEXPIRE) {
779                         MNT_REL(mp);
780                         MNT_IUNLOCK(mp);
781                         CTR1(KTR_VFS, "%s: failed busying before sleeping",
782                             __func__);
783                         return (ENOENT);
784                 }
785                 if (flags & MBF_MNTLSTLOCK)
786                         mtx_unlock(&mountlist_mtx);
787                 mp->mnt_kern_flag |= MNTK_MWAIT;
788                 msleep(mp, MNT_MTX(mp), PVFS | PDROP, "vfs_busy", 0);
789                 if (flags & MBF_MNTLSTLOCK)
790                         mtx_lock(&mountlist_mtx);
791                 MNT_ILOCK(mp);
792         }
793         if (flags & MBF_MNTLSTLOCK)
794                 mtx_unlock(&mountlist_mtx);
795         mp->mnt_lockref++;
796         MNT_IUNLOCK(mp);
797         return (0);
798 }
799
800 /*
801  * Free a busy filesystem.
802  */
803 void
804 vfs_unbusy(struct mount *mp)
805 {
806         int c;
807
808         CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
809
810         if (vfs_op_thread_enter(mp)) {
811                 MPASS((mp->mnt_kern_flag & MNTK_DRAINING) == 0);
812                 vfs_mp_count_sub_pcpu(mp, lockref, 1);
813                 vfs_mp_count_sub_pcpu(mp, ref, 1);
814                 vfs_op_thread_exit(mp);
815                 return;
816         }
817
818         MNT_ILOCK(mp);
819         vfs_assert_mount_counters(mp);
820         MNT_REL(mp);
821         c = --mp->mnt_lockref;
822         if (mp->mnt_vfs_ops == 0) {
823                 MPASS((mp->mnt_kern_flag & MNTK_DRAINING) == 0);
824                 MNT_IUNLOCK(mp);
825                 return;
826         }
827         if (c < 0)
828                 vfs_dump_mount_counters(mp);
829         if (c == 0 && (mp->mnt_kern_flag & MNTK_DRAINING) != 0) {
830                 MPASS(mp->mnt_kern_flag & MNTK_UNMOUNT);
831                 CTR1(KTR_VFS, "%s: waking up waiters", __func__);
832                 mp->mnt_kern_flag &= ~MNTK_DRAINING;
833                 wakeup(&mp->mnt_lockref);
834         }
835         MNT_IUNLOCK(mp);
836 }
837
838 /*
839  * Lookup a mount point by filesystem identifier.
840  */
841 struct mount *
842 vfs_getvfs(fsid_t *fsid)
843 {
844         struct mount *mp;
845
846         CTR2(KTR_VFS, "%s: fsid %p", __func__, fsid);
847         mtx_lock(&mountlist_mtx);
848         TAILQ_FOREACH(mp, &mountlist, mnt_list) {
849                 if (fsidcmp(&mp->mnt_stat.f_fsid, fsid) == 0) {
850                         vfs_ref(mp);
851                         mtx_unlock(&mountlist_mtx);
852                         return (mp);
853                 }
854         }
855         mtx_unlock(&mountlist_mtx);
856         CTR2(KTR_VFS, "%s: lookup failed for %p id", __func__, fsid);
857         return ((struct mount *) 0);
858 }
859
860 /*
861  * Lookup a mount point by filesystem identifier, busying it before
862  * returning.
863  *
864  * To avoid congestion on mountlist_mtx, implement simple direct-mapped
865  * cache for popular filesystem identifiers.  The cache is lockess, using
866  * the fact that struct mount's are never freed.  In worst case we may
867  * get pointer to unmounted or even different filesystem, so we have to
868  * check what we got, and go slow way if so.
869  */
870 struct mount *
871 vfs_busyfs(fsid_t *fsid)
872 {
873 #define FSID_CACHE_SIZE 256
874         typedef struct mount * volatile vmp_t;
875         static vmp_t cache[FSID_CACHE_SIZE];
876         struct mount *mp;
877         int error;
878         uint32_t hash;
879
880         CTR2(KTR_VFS, "%s: fsid %p", __func__, fsid);
881         hash = fsid->val[0] ^ fsid->val[1];
882         hash = (hash >> 16 ^ hash) & (FSID_CACHE_SIZE - 1);
883         mp = cache[hash];
884         if (mp == NULL || fsidcmp(&mp->mnt_stat.f_fsid, fsid) != 0)
885                 goto slow;
886         if (vfs_busy(mp, 0) != 0) {
887                 cache[hash] = NULL;
888                 goto slow;
889         }
890         if (fsidcmp(&mp->mnt_stat.f_fsid, fsid) == 0)
891                 return (mp);
892         else
893             vfs_unbusy(mp);
894
895 slow:
896         mtx_lock(&mountlist_mtx);
897         TAILQ_FOREACH(mp, &mountlist, mnt_list) {
898                 if (fsidcmp(&mp->mnt_stat.f_fsid, fsid) == 0) {
899                         error = vfs_busy(mp, MBF_MNTLSTLOCK);
900                         if (error) {
901                                 cache[hash] = NULL;
902                                 mtx_unlock(&mountlist_mtx);
903                                 return (NULL);
904                         }
905                         cache[hash] = mp;
906                         return (mp);
907                 }
908         }
909         CTR2(KTR_VFS, "%s: lookup failed for %p id", __func__, fsid);
910         mtx_unlock(&mountlist_mtx);
911         return ((struct mount *) 0);
912 }
913
914 /*
915  * Check if a user can access privileged mount options.
916  */
917 int
918 vfs_suser(struct mount *mp, struct thread *td)
919 {
920         int error;
921
922         if (jailed(td->td_ucred)) {
923                 /*
924                  * If the jail of the calling thread lacks permission for
925                  * this type of file system, deny immediately.
926                  */
927                 if (!prison_allow(td->td_ucred, mp->mnt_vfc->vfc_prison_flag))
928                         return (EPERM);
929
930                 /*
931                  * If the file system was mounted outside the jail of the
932                  * calling thread, deny immediately.
933                  */
934                 if (prison_check(td->td_ucred, mp->mnt_cred) != 0)
935                         return (EPERM);
936         }
937
938         /*
939          * If file system supports delegated administration, we don't check
940          * for the PRIV_VFS_MOUNT_OWNER privilege - it will be better verified
941          * by the file system itself.
942          * If this is not the user that did original mount, we check for
943          * the PRIV_VFS_MOUNT_OWNER privilege.
944          */
945         if (!(mp->mnt_vfc->vfc_flags & VFCF_DELEGADMIN) &&
946             mp->mnt_cred->cr_uid != td->td_ucred->cr_uid) {
947                 if ((error = priv_check(td, PRIV_VFS_MOUNT_OWNER)) != 0)
948                         return (error);
949         }
950         return (0);
951 }
952
953 /*
954  * Get a new unique fsid.  Try to make its val[0] unique, since this value
955  * will be used to create fake device numbers for stat().  Also try (but
956  * not so hard) make its val[0] unique mod 2^16, since some emulators only
957  * support 16-bit device numbers.  We end up with unique val[0]'s for the
958  * first 2^16 calls and unique val[0]'s mod 2^16 for the first 2^8 calls.
959  *
960  * Keep in mind that several mounts may be running in parallel.  Starting
961  * the search one past where the previous search terminated is both a
962  * micro-optimization and a defense against returning the same fsid to
963  * different mounts.
964  */
965 void
966 vfs_getnewfsid(struct mount *mp)
967 {
968         static uint16_t mntid_base;
969         struct mount *nmp;
970         fsid_t tfsid;
971         int mtype;
972
973         CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
974         mtx_lock(&mntid_mtx);
975         mtype = mp->mnt_vfc->vfc_typenum;
976         tfsid.val[1] = mtype;
977         mtype = (mtype & 0xFF) << 24;
978         for (;;) {
979                 tfsid.val[0] = makedev(255,
980                     mtype | ((mntid_base & 0xFF00) << 8) | (mntid_base & 0xFF));
981                 mntid_base++;
982                 if ((nmp = vfs_getvfs(&tfsid)) == NULL)
983                         break;
984                 vfs_rel(nmp);
985         }
986         mp->mnt_stat.f_fsid.val[0] = tfsid.val[0];
987         mp->mnt_stat.f_fsid.val[1] = tfsid.val[1];
988         mtx_unlock(&mntid_mtx);
989 }
990
991 /*
992  * Knob to control the precision of file timestamps:
993  *
994  *   0 = seconds only; nanoseconds zeroed.
995  *   1 = seconds and nanoseconds, accurate within 1/HZ.
996  *   2 = seconds and nanoseconds, truncated to microseconds.
997  * >=3 = seconds and nanoseconds, maximum precision.
998  */
999 enum { TSP_SEC, TSP_HZ, TSP_USEC, TSP_NSEC };
1000
1001 static int timestamp_precision = TSP_USEC;
1002 SYSCTL_INT(_vfs, OID_AUTO, timestamp_precision, CTLFLAG_RW,
1003     &timestamp_precision, 0, "File timestamp precision (0: seconds, "
1004     "1: sec + ns accurate to 1/HZ, 2: sec + ns truncated to us, "
1005     "3+: sec + ns (max. precision))");
1006
1007 /*
1008  * Get a current timestamp.
1009  */
1010 void
1011 vfs_timestamp(struct timespec *tsp)
1012 {
1013         struct timeval tv;
1014
1015         switch (timestamp_precision) {
1016         case TSP_SEC:
1017                 tsp->tv_sec = time_second;
1018                 tsp->tv_nsec = 0;
1019                 break;
1020         case TSP_HZ:
1021                 getnanotime(tsp);
1022                 break;
1023         case TSP_USEC:
1024                 microtime(&tv);
1025                 TIMEVAL_TO_TIMESPEC(&tv, tsp);
1026                 break;
1027         case TSP_NSEC:
1028         default:
1029                 nanotime(tsp);
1030                 break;
1031         }
1032 }
1033
1034 /*
1035  * Set vnode attributes to VNOVAL
1036  */
1037 void
1038 vattr_null(struct vattr *vap)
1039 {
1040
1041         vap->va_type = VNON;
1042         vap->va_size = VNOVAL;
1043         vap->va_bytes = VNOVAL;
1044         vap->va_mode = VNOVAL;
1045         vap->va_nlink = VNOVAL;
1046         vap->va_uid = VNOVAL;
1047         vap->va_gid = VNOVAL;
1048         vap->va_fsid = VNOVAL;
1049         vap->va_fileid = VNOVAL;
1050         vap->va_blocksize = VNOVAL;
1051         vap->va_rdev = VNOVAL;
1052         vap->va_atime.tv_sec = VNOVAL;
1053         vap->va_atime.tv_nsec = VNOVAL;
1054         vap->va_mtime.tv_sec = VNOVAL;
1055         vap->va_mtime.tv_nsec = VNOVAL;
1056         vap->va_ctime.tv_sec = VNOVAL;
1057         vap->va_ctime.tv_nsec = VNOVAL;
1058         vap->va_birthtime.tv_sec = VNOVAL;
1059         vap->va_birthtime.tv_nsec = VNOVAL;
1060         vap->va_flags = VNOVAL;
1061         vap->va_gen = VNOVAL;
1062         vap->va_vaflags = 0;
1063 }
1064
1065 /*
1066  * Try to reduce the total number of vnodes.
1067  *
1068  * This routine (and its user) are buggy in at least the following ways:
1069  * - all parameters were picked years ago when RAM sizes were significantly
1070  *   smaller
1071  * - it can pick vnodes based on pages used by the vm object, but filesystems
1072  *   like ZFS don't use it making the pick broken
1073  * - since ZFS has its own aging policy it gets partially combated by this one
1074  * - a dedicated method should be provided for filesystems to let them decide
1075  *   whether the vnode should be recycled
1076  *
1077  * This routine is called when we have too many vnodes.  It attempts
1078  * to free <count> vnodes and will potentially free vnodes that still
1079  * have VM backing store (VM backing store is typically the cause
1080  * of a vnode blowout so we want to do this).  Therefore, this operation
1081  * is not considered cheap.
1082  *
1083  * A number of conditions may prevent a vnode from being reclaimed.
1084  * the buffer cache may have references on the vnode, a directory
1085  * vnode may still have references due to the namei cache representing
1086  * underlying files, or the vnode may be in active use.   It is not
1087  * desirable to reuse such vnodes.  These conditions may cause the
1088  * number of vnodes to reach some minimum value regardless of what
1089  * you set kern.maxvnodes to.  Do not set kern.maxvnodes too low.
1090  *
1091  * @param reclaim_nc_src Only reclaim directories with outgoing namecache
1092  *                       entries if this argument is strue
1093  * @param trigger        Only reclaim vnodes with fewer than this many resident
1094  *                       pages.
1095  * @param target         How many vnodes to reclaim.
1096  * @return               The number of vnodes that were reclaimed.
1097  */
1098 static int
1099 vlrureclaim(bool reclaim_nc_src, int trigger, u_long target)
1100 {
1101         struct vnode *vp, *mvp;
1102         struct mount *mp;
1103         struct vm_object *object;
1104         u_long done;
1105         bool retried;
1106
1107         mtx_assert(&vnode_list_mtx, MA_OWNED);
1108
1109         retried = false;
1110         done = 0;
1111
1112         mvp = vnode_list_reclaim_marker;
1113 restart:
1114         vp = mvp;
1115         while (done < target) {
1116                 vp = TAILQ_NEXT(vp, v_vnodelist);
1117                 if (__predict_false(vp == NULL))
1118                         break;
1119
1120                 if (__predict_false(vp->v_type == VMARKER))
1121                         continue;
1122
1123                 /*
1124                  * If it's been deconstructed already, it's still
1125                  * referenced, or it exceeds the trigger, skip it.
1126                  * Also skip free vnodes.  We are trying to make space
1127                  * to expand the free list, not reduce it.
1128                  */
1129                 if (vp->v_usecount > 0 || vp->v_holdcnt == 0 ||
1130                     (!reclaim_nc_src && !LIST_EMPTY(&vp->v_cache_src)))
1131                         goto next_iter;
1132
1133                 if (vp->v_type == VBAD || vp->v_type == VNON)
1134                         goto next_iter;
1135
1136                 if (!VI_TRYLOCK(vp))
1137                         goto next_iter;
1138
1139                 if (vp->v_usecount > 0 || vp->v_holdcnt == 0 ||
1140                     (!reclaim_nc_src && !LIST_EMPTY(&vp->v_cache_src)) ||
1141                     VN_IS_DOOMED(vp) || vp->v_type == VNON) {
1142                         VI_UNLOCK(vp);
1143                         goto next_iter;
1144                 }
1145
1146                 object = atomic_load_ptr(&vp->v_object);
1147                 if (object == NULL || object->resident_page_count > trigger) {
1148                         VI_UNLOCK(vp);
1149                         goto next_iter;
1150                 }
1151
1152                 vholdl(vp);
1153                 VI_UNLOCK(vp);
1154                 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1155                 TAILQ_INSERT_AFTER(&vnode_list, vp, mvp, v_vnodelist);
1156                 mtx_unlock(&vnode_list_mtx);
1157
1158                 if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
1159                         vdrop(vp);
1160                         goto next_iter_unlocked;
1161                 }
1162                 if (VOP_LOCK(vp, LK_EXCLUSIVE|LK_NOWAIT) != 0) {
1163                         vdrop(vp);
1164                         vn_finished_write(mp);
1165                         goto next_iter_unlocked;
1166                 }
1167
1168                 VI_LOCK(vp);
1169                 if (vp->v_usecount > 0 ||
1170                     (!reclaim_nc_src && !LIST_EMPTY(&vp->v_cache_src)) ||
1171                     (vp->v_object != NULL &&
1172                     vp->v_object->resident_page_count > trigger)) {
1173                         VOP_UNLOCK(vp);
1174                         vdropl(vp);
1175                         vn_finished_write(mp);
1176                         goto next_iter_unlocked;
1177                 }
1178                 counter_u64_add(recycles_count, 1);
1179                 vgonel(vp);
1180                 VOP_UNLOCK(vp);
1181                 vdropl(vp);
1182                 vn_finished_write(mp);
1183                 done++;
1184 next_iter_unlocked:
1185                 if (should_yield())
1186                         kern_yield(PRI_USER);
1187                 mtx_lock(&vnode_list_mtx);
1188                 goto restart;
1189 next_iter:
1190                 MPASS(vp->v_type != VMARKER);
1191                 if (!should_yield())
1192                         continue;
1193                 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1194                 TAILQ_INSERT_AFTER(&vnode_list, vp, mvp, v_vnodelist);
1195                 mtx_unlock(&vnode_list_mtx);
1196                 kern_yield(PRI_USER);
1197                 mtx_lock(&vnode_list_mtx);
1198                 goto restart;
1199         }
1200         if (done == 0 && !retried) {
1201                 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1202                 TAILQ_INSERT_HEAD(&vnode_list, mvp, v_vnodelist);
1203                 retried = true;
1204                 goto restart;
1205         }
1206         return (done);
1207 }
1208
1209 static int max_vnlru_free = 10000; /* limit on vnode free requests per call */
1210 SYSCTL_INT(_debug, OID_AUTO, max_vnlru_free, CTLFLAG_RW, &max_vnlru_free,
1211     0,
1212     "limit on vnode free requests per call to the vnlru_free routine");
1213
1214 /*
1215  * Attempt to reduce the free list by the requested amount.
1216  */
1217 static int
1218 vnlru_free_locked(int count, struct vfsops *mnt_op)
1219 {
1220         struct vnode *vp, *mvp;
1221         struct mount *mp;
1222         int ocount;
1223
1224         mtx_assert(&vnode_list_mtx, MA_OWNED);
1225         if (count > max_vnlru_free)
1226                 count = max_vnlru_free;
1227         ocount = count;
1228         mvp = vnode_list_free_marker;
1229 restart:
1230         vp = mvp;
1231         while (count > 0) {
1232                 vp = TAILQ_NEXT(vp, v_vnodelist);
1233                 if (__predict_false(vp == NULL)) {
1234                         TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1235                         TAILQ_INSERT_TAIL(&vnode_list, mvp, v_vnodelist);
1236                         break;
1237                 }
1238                 if (__predict_false(vp->v_type == VMARKER))
1239                         continue;
1240
1241                 /*
1242                  * Don't recycle if our vnode is from different type
1243                  * of mount point.  Note that mp is type-safe, the
1244                  * check does not reach unmapped address even if
1245                  * vnode is reclaimed.
1246                  * Don't recycle if we can't get the interlock without
1247                  * blocking.
1248                  */
1249                 if (vp->v_holdcnt > 0 || (mnt_op != NULL && (mp = vp->v_mount) != NULL &&
1250                     mp->mnt_op != mnt_op) || !VI_TRYLOCK(vp)) {
1251                         continue;
1252                 }
1253                 TAILQ_REMOVE(&vnode_list, mvp, v_vnodelist);
1254                 TAILQ_INSERT_AFTER(&vnode_list, vp, mvp, v_vnodelist);
1255                 if (__predict_false(vp->v_type == VBAD || vp->v_type == VNON)) {
1256                         VI_UNLOCK(vp);
1257                         continue;
1258                 }
1259                 vholdl(vp);
1260                 count--;
1261                 mtx_unlock(&vnode_list_mtx);
1262                 VI_UNLOCK(vp);
1263                 vtryrecycle(vp);
1264                 vdrop(vp);
1265                 mtx_lock(&vnode_list_mtx);
1266                 goto restart;
1267         }
1268         return (ocount - count);
1269 }
1270
1271 void
1272 vnlru_free(int count, struct vfsops *mnt_op)
1273 {
1274
1275         mtx_lock(&vnode_list_mtx);
1276         vnlru_free_locked(count, mnt_op);
1277         mtx_unlock(&vnode_list_mtx);
1278 }
1279
1280 static void
1281 vnlru_recalc(void)
1282 {
1283
1284         mtx_assert(&vnode_list_mtx, MA_OWNED);
1285         gapvnodes = imax(desiredvnodes - wantfreevnodes, 100);
1286         vhiwat = gapvnodes / 11; /* 9% -- just under the 10% in vlrureclaim() */
1287         vlowat = vhiwat / 2;
1288 }
1289
1290 /*
1291  * Attempt to recycle vnodes in a context that is always safe to block.
1292  * Calling vlrurecycle() from the bowels of filesystem code has some
1293  * interesting deadlock problems.
1294  */
1295 static struct proc *vnlruproc;
1296 static int vnlruproc_sig;
1297
1298 /*
1299  * The main freevnodes counter is only updated when threads requeue their vnode
1300  * batches. CPUs are conditionally walked to compute a more accurate total.
1301  *
1302  * Limit how much of a slop are we willing to tolerate. Note: the actual value
1303  * at any given moment can still exceed slop, but it should not be by significant
1304  * margin in practice.
1305  */
1306 #define VNLRU_FREEVNODES_SLOP 128
1307
1308 static u_long
1309 vnlru_read_freevnodes(void)
1310 {
1311         struct vdbatch *vd;
1312         long slop;
1313         int cpu;
1314
1315         mtx_assert(&vnode_list_mtx, MA_OWNED);
1316         if (freevnodes > freevnodes_old)
1317                 slop = freevnodes - freevnodes_old;
1318         else
1319                 slop = freevnodes_old - freevnodes;
1320         if (slop < VNLRU_FREEVNODES_SLOP)
1321                 return (freevnodes >= 0 ? freevnodes : 0);
1322         freevnodes_old = freevnodes;
1323         CPU_FOREACH(cpu) {
1324                 vd = DPCPU_ID_PTR((cpu), vd);
1325                 freevnodes_old += vd->freevnodes;
1326         }
1327         return (freevnodes_old >= 0 ? freevnodes_old : 0);
1328 }
1329
1330 static bool
1331 vnlru_under(u_long rnumvnodes, u_long limit)
1332 {
1333         u_long rfreevnodes, space;
1334
1335         if (__predict_false(rnumvnodes > desiredvnodes))
1336                 return (true);
1337
1338         space = desiredvnodes - rnumvnodes;
1339         if (space < limit) {
1340                 rfreevnodes = vnlru_read_freevnodes();
1341                 if (rfreevnodes > wantfreevnodes)
1342                         space += rfreevnodes - wantfreevnodes;
1343         }
1344         return (space < limit);
1345 }
1346
1347 static bool
1348 vnlru_under_unlocked(u_long rnumvnodes, u_long limit)
1349 {
1350         long rfreevnodes, space;
1351
1352         if (__predict_false(rnumvnodes > desiredvnodes))
1353                 return (true);
1354
1355         space = desiredvnodes - rnumvnodes;
1356         if (space < limit) {
1357                 rfreevnodes = atomic_load_long(&freevnodes);
1358                 if (rfreevnodes > wantfreevnodes)
1359                         space += rfreevnodes - wantfreevnodes;
1360         }
1361         return (space < limit);
1362 }
1363
1364 static void
1365 vnlru_kick(void)
1366 {
1367
1368         mtx_assert(&vnode_list_mtx, MA_OWNED);
1369         if (vnlruproc_sig == 0) {
1370                 vnlruproc_sig = 1;
1371                 wakeup(vnlruproc);
1372         }
1373 }
1374
1375 static void
1376 vnlru_proc(void)
1377 {
1378         u_long rnumvnodes, rfreevnodes, target;
1379         unsigned long onumvnodes;
1380         int done, force, trigger, usevnodes;
1381         bool reclaim_nc_src, want_reread;
1382
1383         EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, vnlruproc,
1384             SHUTDOWN_PRI_FIRST);
1385
1386         force = 0;
1387         want_reread = false;
1388         for (;;) {
1389                 kproc_suspend_check(vnlruproc);
1390                 mtx_lock(&vnode_list_mtx);
1391                 rnumvnodes = atomic_load_long(&numvnodes);
1392
1393                 if (want_reread) {
1394                         force = vnlru_under(numvnodes, vhiwat) ? 1 : 0;
1395                         want_reread = false;
1396                 }
1397
1398                 /*
1399                  * If numvnodes is too large (due to desiredvnodes being
1400                  * adjusted using its sysctl, or emergency growth), first
1401                  * try to reduce it by discarding from the free list.
1402                  */
1403                 if (rnumvnodes > desiredvnodes) {
1404                         vnlru_free_locked(rnumvnodes - desiredvnodes, NULL);
1405                         rnumvnodes = atomic_load_long(&numvnodes);
1406                 }
1407                 /*
1408                  * Sleep if the vnode cache is in a good state.  This is
1409                  * when it is not over-full and has space for about a 4%
1410                  * or 9% expansion (by growing its size or inexcessively
1411                  * reducing its free list).  Otherwise, try to reclaim
1412                  * space for a 10% expansion.
1413                  */
1414                 if (vstir && force == 0) {
1415                         force = 1;
1416                         vstir = 0;
1417                 }
1418                 if (force == 0 && !vnlru_under(rnumvnodes, vlowat)) {
1419                         vnlruproc_sig = 0;
1420                         wakeup(&vnlruproc_sig);
1421                         msleep(vnlruproc, &vnode_list_mtx,
1422                             PVFS|PDROP, "vlruwt", hz);
1423                         continue;
1424                 }
1425                 rfreevnodes = vnlru_read_freevnodes();
1426
1427                 onumvnodes = rnumvnodes;
1428                 /*
1429                  * Calculate parameters for recycling.  These are the same
1430                  * throughout the loop to give some semblance of fairness.
1431                  * The trigger point is to avoid recycling vnodes with lots
1432                  * of resident pages.  We aren't trying to free memory; we
1433                  * are trying to recycle or at least free vnodes.
1434                  */
1435                 if (rnumvnodes <= desiredvnodes)
1436                         usevnodes = rnumvnodes - rfreevnodes;
1437                 else
1438                         usevnodes = rnumvnodes;
1439                 if (usevnodes <= 0)
1440                         usevnodes = 1;
1441                 /*
1442                  * The trigger value is is chosen to give a conservatively
1443                  * large value to ensure that it alone doesn't prevent
1444                  * making progress.  The value can easily be so large that
1445                  * it is effectively infinite in some congested and
1446                  * misconfigured cases, and this is necessary.  Normally
1447                  * it is about 8 to 100 (pages), which is quite large.
1448                  */
1449                 trigger = vm_cnt.v_page_count * 2 / usevnodes;
1450                 if (force < 2)
1451                         trigger = vsmalltrigger;
1452                 reclaim_nc_src = force >= 3;
1453                 target = rnumvnodes * (int64_t)gapvnodes / imax(desiredvnodes, 1);
1454                 target = target / 10 + 1;
1455                 done = vlrureclaim(reclaim_nc_src, trigger, target);
1456                 mtx_unlock(&vnode_list_mtx);
1457                 if (onumvnodes > desiredvnodes && numvnodes <= desiredvnodes)
1458                         uma_reclaim(UMA_RECLAIM_DRAIN);
1459                 if (done == 0) {
1460                         if (force == 0 || force == 1) {
1461                                 force = 2;
1462                                 continue;
1463                         }
1464                         if (force == 2) {
1465                                 force = 3;
1466                                 continue;
1467                         }
1468                         want_reread = true;
1469                         force = 0;
1470                         vnlru_nowhere++;
1471                         tsleep(vnlruproc, PPAUSE, "vlrup", hz * 3);
1472                 } else {
1473                         want_reread = true;
1474                         kern_yield(PRI_USER);
1475                 }
1476         }
1477 }
1478
1479 static struct kproc_desc vnlru_kp = {
1480         "vnlru",
1481         vnlru_proc,
1482         &vnlruproc
1483 };
1484 SYSINIT(vnlru, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start,
1485     &vnlru_kp);
1486
1487 /*
1488  * Routines having to do with the management of the vnode table.
1489  */
1490
1491 /*
1492  * Try to recycle a freed vnode.  We abort if anyone picks up a reference
1493  * before we actually vgone().  This function must be called with the vnode
1494  * held to prevent the vnode from being returned to the free list midway
1495  * through vgone().
1496  */
1497 static int
1498 vtryrecycle(struct vnode *vp)
1499 {
1500         struct mount *vnmp;
1501
1502         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
1503         VNASSERT(vp->v_holdcnt, vp,
1504             ("vtryrecycle: Recycling vp %p without a reference.", vp));
1505         /*
1506          * This vnode may found and locked via some other list, if so we
1507          * can't recycle it yet.
1508          */
1509         if (VOP_LOCK(vp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
1510                 CTR2(KTR_VFS,
1511                     "%s: impossible to recycle, vp %p lock is already held",
1512                     __func__, vp);
1513                 return (EWOULDBLOCK);
1514         }
1515         /*
1516          * Don't recycle if its filesystem is being suspended.
1517          */
1518         if (vn_start_write(vp, &vnmp, V_NOWAIT) != 0) {
1519                 VOP_UNLOCK(vp);
1520                 CTR2(KTR_VFS,
1521                     "%s: impossible to recycle, cannot start the write for %p",
1522                     __func__, vp);
1523                 return (EBUSY);
1524         }
1525         /*
1526          * If we got this far, we need to acquire the interlock and see if
1527          * anyone picked up this vnode from another list.  If not, we will
1528          * mark it with DOOMED via vgonel() so that anyone who does find it
1529          * will skip over it.
1530          */
1531         VI_LOCK(vp);
1532         if (vp->v_usecount) {
1533                 VOP_UNLOCK(vp);
1534                 VI_UNLOCK(vp);
1535                 vn_finished_write(vnmp);
1536                 CTR2(KTR_VFS,
1537                     "%s: impossible to recycle, %p is already referenced",
1538                     __func__, vp);
1539                 return (EBUSY);
1540         }
1541         if (!VN_IS_DOOMED(vp)) {
1542                 counter_u64_add(recycles_free_count, 1);
1543                 vgonel(vp);
1544         }
1545         VOP_UNLOCK(vp);
1546         VI_UNLOCK(vp);
1547         vn_finished_write(vnmp);
1548         return (0);
1549 }
1550
1551 /*
1552  * Allocate a new vnode.
1553  *
1554  * The operation never returns an error. Returning an error was disabled
1555  * in r145385 (dated 2005) with the following comment:
1556  *
1557  * XXX Not all VFS_VGET/ffs_vget callers check returns.
1558  *
1559  * Given the age of this commit (almost 15 years at the time of writing this
1560  * comment) restoring the ability to fail requires a significant audit of
1561  * all codepaths.
1562  *
1563  * The routine can try to free a vnode or stall for up to 1 second waiting for
1564  * vnlru to clear things up, but ultimately always performs a M_WAITOK allocation.
1565  */
1566 static u_long vn_alloc_cyclecount;
1567
1568 static struct vnode * __noinline
1569 vn_alloc_hard(struct mount *mp)
1570 {
1571         u_long rnumvnodes, rfreevnodes;
1572
1573         mtx_lock(&vnode_list_mtx);
1574         rnumvnodes = atomic_load_long(&numvnodes);
1575         if (rnumvnodes + 1 < desiredvnodes) {
1576                 vn_alloc_cyclecount = 0;
1577                 goto alloc;
1578         }
1579         rfreevnodes = vnlru_read_freevnodes();
1580         if (vn_alloc_cyclecount++ >= rfreevnodes) {
1581                 vn_alloc_cyclecount = 0;
1582                 vstir = 1;
1583         }
1584         /*
1585          * Grow the vnode cache if it will not be above its target max
1586          * after growing.  Otherwise, if the free list is nonempty, try
1587          * to reclaim 1 item from it before growing the cache (possibly
1588          * above its target max if the reclamation failed or is delayed).
1589          * Otherwise, wait for some space.  In all cases, schedule
1590          * vnlru_proc() if we are getting short of space.  The watermarks
1591          * should be chosen so that we never wait or even reclaim from
1592          * the free list to below its target minimum.
1593          */
1594         if (vnlru_free_locked(1, NULL) > 0)
1595                 goto alloc;
1596         if (mp == NULL || (mp->mnt_kern_flag & MNTK_SUSPEND) == 0) {
1597                 /*
1598                  * Wait for space for a new vnode.
1599                  */
1600                 vnlru_kick();
1601                 msleep(&vnlruproc_sig, &vnode_list_mtx, PVFS, "vlruwk", hz);
1602                 if (atomic_load_long(&numvnodes) + 1 > desiredvnodes &&
1603                     vnlru_read_freevnodes() > 1)
1604                         vnlru_free_locked(1, NULL);
1605         }
1606 alloc:
1607         rnumvnodes = atomic_fetchadd_long(&numvnodes, 1) + 1;
1608         if (vnlru_under(rnumvnodes, vlowat))
1609                 vnlru_kick();
1610         mtx_unlock(&vnode_list_mtx);
1611         return (uma_zalloc_smr(vnode_zone, M_WAITOK));
1612 }
1613
1614 static struct vnode *
1615 vn_alloc(struct mount *mp)
1616 {
1617         u_long rnumvnodes;
1618
1619         if (__predict_false(vn_alloc_cyclecount != 0))
1620                 return (vn_alloc_hard(mp));
1621         rnumvnodes = atomic_fetchadd_long(&numvnodes, 1) + 1;
1622         if (__predict_false(vnlru_under_unlocked(rnumvnodes, vlowat))) {
1623                 atomic_subtract_long(&numvnodes, 1);
1624                 return (vn_alloc_hard(mp));
1625         }
1626
1627         return (uma_zalloc_smr(vnode_zone, M_WAITOK));
1628 }
1629
1630 static void
1631 vn_free(struct vnode *vp)
1632 {
1633
1634         atomic_subtract_long(&numvnodes, 1);
1635         uma_zfree_smr(vnode_zone, vp);
1636 }
1637
1638 /*
1639  * Return the next vnode from the free list.
1640  */
1641 int
1642 getnewvnode(const char *tag, struct mount *mp, struct vop_vector *vops,
1643     struct vnode **vpp)
1644 {
1645         struct vnode *vp;
1646         struct thread *td;
1647         struct lock_object *lo;
1648
1649         CTR3(KTR_VFS, "%s: mp %p with tag %s", __func__, mp, tag);
1650
1651         KASSERT(vops->registered,
1652             ("%s: not registered vector op %p\n", __func__, vops));
1653
1654         td = curthread;
1655         if (td->td_vp_reserved != NULL) {
1656                 vp = td->td_vp_reserved;
1657                 td->td_vp_reserved = NULL;
1658         } else {
1659                 vp = vn_alloc(mp);
1660         }
1661         counter_u64_add(vnodes_created, 1);
1662         /*
1663          * Locks are given the generic name "vnode" when created.
1664          * Follow the historic practice of using the filesystem
1665          * name when they allocated, e.g., "zfs", "ufs", "nfs, etc.
1666          *
1667          * Locks live in a witness group keyed on their name. Thus,
1668          * when a lock is renamed, it must also move from the witness
1669          * group of its old name to the witness group of its new name.
1670          *
1671          * The change only needs to be made when the vnode moves
1672          * from one filesystem type to another. We ensure that each
1673          * filesystem use a single static name pointer for its tag so
1674          * that we can compare pointers rather than doing a strcmp().
1675          */
1676         lo = &vp->v_vnlock->lock_object;
1677 #ifdef WITNESS
1678         if (lo->lo_name != tag) {
1679 #endif
1680                 lo->lo_name = tag;
1681 #ifdef WITNESS
1682                 WITNESS_DESTROY(lo);
1683                 WITNESS_INIT(lo, tag);
1684         }
1685 #endif
1686         /*
1687          * By default, don't allow shared locks unless filesystems opt-in.
1688          */
1689         vp->v_vnlock->lock_object.lo_flags |= LK_NOSHARE;
1690         /*
1691          * Finalize various vnode identity bits.
1692          */
1693         KASSERT(vp->v_object == NULL, ("stale v_object %p", vp));
1694         KASSERT(vp->v_lockf == NULL, ("stale v_lockf %p", vp));
1695         KASSERT(vp->v_pollinfo == NULL, ("stale v_pollinfo %p", vp));
1696         vp->v_type = VNON;
1697         vp->v_op = vops;
1698         v_init_counters(vp);
1699         vp->v_bufobj.bo_ops = &buf_ops_bio;
1700 #ifdef DIAGNOSTIC
1701         if (mp == NULL && vops != &dead_vnodeops)
1702                 printf("NULL mp in getnewvnode(9), tag %s\n", tag);
1703 #endif
1704 #ifdef MAC
1705         mac_vnode_init(vp);
1706         if (mp != NULL && (mp->mnt_flag & MNT_MULTILABEL) == 0)
1707                 mac_vnode_associate_singlelabel(mp, vp);
1708 #endif
1709         if (mp != NULL) {
1710                 vp->v_bufobj.bo_bsize = mp->mnt_stat.f_iosize;
1711                 if ((mp->mnt_kern_flag & MNTK_NOKNOTE) != 0)
1712                         vp->v_vflag |= VV_NOKNOTE;
1713         }
1714
1715         /*
1716          * For the filesystems which do not use vfs_hash_insert(),
1717          * still initialize v_hash to have vfs_hash_index() useful.
1718          * E.g., nullfs uses vfs_hash_index() on the lower vnode for
1719          * its own hashing.
1720          */
1721         vp->v_hash = (uintptr_t)vp >> vnsz2log;
1722
1723         *vpp = vp;
1724         return (0);
1725 }
1726
1727 void
1728 getnewvnode_reserve(void)
1729 {
1730         struct thread *td;
1731
1732         td = curthread;
1733         MPASS(td->td_vp_reserved == NULL);
1734         td->td_vp_reserved = vn_alloc(NULL);
1735 }
1736
1737 void
1738 getnewvnode_drop_reserve(void)
1739 {
1740         struct thread *td;
1741
1742         td = curthread;
1743         if (td->td_vp_reserved != NULL) {
1744                 vn_free(td->td_vp_reserved);
1745                 td->td_vp_reserved = NULL;
1746         }
1747 }
1748
1749 static void
1750 freevnode(struct vnode *vp)
1751 {
1752         struct bufobj *bo;
1753
1754         /*
1755          * The vnode has been marked for destruction, so free it.
1756          *
1757          * The vnode will be returned to the zone where it will
1758          * normally remain until it is needed for another vnode. We
1759          * need to cleanup (or verify that the cleanup has already
1760          * been done) any residual data left from its current use
1761          * so as not to contaminate the freshly allocated vnode.
1762          */
1763         CTR2(KTR_VFS, "%s: destroying the vnode %p", __func__, vp);
1764         /*
1765          * Paired with vgone.
1766          */
1767         vn_seqc_write_end_locked(vp);
1768         VNPASS(vp->v_seqc_users == 0, vp);
1769
1770         bo = &vp->v_bufobj;
1771         VNASSERT(vp->v_data == NULL, vp, ("cleaned vnode isn't"));
1772         VNPASS(vp->v_holdcnt == VHOLD_NO_SMR, vp);
1773         VNASSERT(vp->v_usecount == 0, vp, ("Non-zero use count"));
1774         VNASSERT(vp->v_writecount == 0, vp, ("Non-zero write count"));
1775         VNASSERT(bo->bo_numoutput == 0, vp, ("Clean vnode has pending I/O's"));
1776         VNASSERT(bo->bo_clean.bv_cnt == 0, vp, ("cleanbufcnt not 0"));
1777         VNASSERT(pctrie_is_empty(&bo->bo_clean.bv_root), vp,
1778             ("clean blk trie not empty"));
1779         VNASSERT(bo->bo_dirty.bv_cnt == 0, vp, ("dirtybufcnt not 0"));
1780         VNASSERT(pctrie_is_empty(&bo->bo_dirty.bv_root), vp,
1781             ("dirty blk trie not empty"));
1782         VNASSERT(TAILQ_EMPTY(&vp->v_cache_dst), vp, ("vp has namecache dst"));
1783         VNASSERT(LIST_EMPTY(&vp->v_cache_src), vp, ("vp has namecache src"));
1784         VNASSERT(vp->v_cache_dd == NULL, vp, ("vp has namecache for .."));
1785         VNASSERT(TAILQ_EMPTY(&vp->v_rl.rl_waiters), vp,
1786             ("Dangling rangelock waiters"));
1787         VI_UNLOCK(vp);
1788 #ifdef MAC
1789         mac_vnode_destroy(vp);
1790 #endif
1791         if (vp->v_pollinfo != NULL) {
1792                 destroy_vpollinfo(vp->v_pollinfo);
1793                 vp->v_pollinfo = NULL;
1794         }
1795 #ifdef INVARIANTS
1796         /* XXX Elsewhere we detect an already freed vnode via NULL v_op. */
1797         vp->v_op = NULL;
1798 #endif
1799         vp->v_mountedhere = NULL;
1800         vp->v_unpcb = NULL;
1801         vp->v_rdev = NULL;
1802         vp->v_fifoinfo = NULL;
1803         vp->v_lasta = vp->v_clen = vp->v_cstart = vp->v_lastw = 0;
1804         vp->v_irflag = 0;
1805         vp->v_iflag = 0;
1806         vp->v_vflag = 0;
1807         bo->bo_flag = 0;
1808         vn_free(vp);
1809 }
1810
1811 /*
1812  * Delete from old mount point vnode list, if on one.
1813  */
1814 static void
1815 delmntque(struct vnode *vp)
1816 {
1817         struct mount *mp;
1818
1819         VNPASS((vp->v_mflag & VMP_LAZYLIST) == 0, vp);
1820
1821         mp = vp->v_mount;
1822         if (mp == NULL)
1823                 return;
1824         MNT_ILOCK(mp);
1825         VI_LOCK(vp);
1826         vp->v_mount = NULL;
1827         VI_UNLOCK(vp);
1828         VNASSERT(mp->mnt_nvnodelistsize > 0, vp,
1829                 ("bad mount point vnode list size"));
1830         TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1831         mp->mnt_nvnodelistsize--;
1832         MNT_REL(mp);
1833         MNT_IUNLOCK(mp);
1834 }
1835
1836 static void
1837 insmntque_stddtr(struct vnode *vp, void *dtr_arg)
1838 {
1839
1840         vp->v_data = NULL;
1841         vp->v_op = &dead_vnodeops;
1842         vgone(vp);
1843         vput(vp);
1844 }
1845
1846 /*
1847  * Insert into list of vnodes for the new mount point, if available.
1848  */
1849 int
1850 insmntque1(struct vnode *vp, struct mount *mp,
1851         void (*dtr)(struct vnode *, void *), void *dtr_arg)
1852 {
1853
1854         KASSERT(vp->v_mount == NULL,
1855                 ("insmntque: vnode already on per mount vnode list"));
1856         VNASSERT(mp != NULL, vp, ("Don't call insmntque(foo, NULL)"));
1857         ASSERT_VOP_ELOCKED(vp, "insmntque: non-locked vp");
1858
1859         /*
1860          * We acquire the vnode interlock early to ensure that the
1861          * vnode cannot be recycled by another process releasing a
1862          * holdcnt on it before we get it on both the vnode list
1863          * and the active vnode list. The mount mutex protects only
1864          * manipulation of the vnode list and the vnode freelist
1865          * mutex protects only manipulation of the active vnode list.
1866          * Hence the need to hold the vnode interlock throughout.
1867          */
1868         MNT_ILOCK(mp);
1869         VI_LOCK(vp);
1870         if (((mp->mnt_kern_flag & MNTK_UNMOUNT) != 0 &&
1871             ((mp->mnt_kern_flag & MNTK_UNMOUNTF) != 0 ||
1872             mp->mnt_nvnodelistsize == 0)) &&
1873             (vp->v_vflag & VV_FORCEINSMQ) == 0) {
1874                 VI_UNLOCK(vp);
1875                 MNT_IUNLOCK(mp);
1876                 if (dtr != NULL)
1877                         dtr(vp, dtr_arg);
1878                 return (EBUSY);
1879         }
1880         vp->v_mount = mp;
1881         MNT_REF(mp);
1882         TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1883         VNASSERT(mp->mnt_nvnodelistsize >= 0, vp,
1884                 ("neg mount point vnode list size"));
1885         mp->mnt_nvnodelistsize++;
1886         VI_UNLOCK(vp);
1887         MNT_IUNLOCK(mp);
1888         return (0);
1889 }
1890
1891 int
1892 insmntque(struct vnode *vp, struct mount *mp)
1893 {
1894
1895         return (insmntque1(vp, mp, insmntque_stddtr, NULL));
1896 }
1897
1898 /*
1899  * Flush out and invalidate all buffers associated with a bufobj
1900  * Called with the underlying object locked.
1901  */
1902 int
1903 bufobj_invalbuf(struct bufobj *bo, int flags, int slpflag, int slptimeo)
1904 {
1905         int error;
1906
1907         BO_LOCK(bo);
1908         if (flags & V_SAVE) {
1909                 error = bufobj_wwait(bo, slpflag, slptimeo);
1910                 if (error) {
1911                         BO_UNLOCK(bo);
1912                         return (error);
1913                 }
1914                 if (bo->bo_dirty.bv_cnt > 0) {
1915                         BO_UNLOCK(bo);
1916                         if ((error = BO_SYNC(bo, MNT_WAIT)) != 0)
1917                                 return (error);
1918                         /*
1919                          * XXX We could save a lock/unlock if this was only
1920                          * enabled under INVARIANTS
1921                          */
1922                         BO_LOCK(bo);
1923                         if (bo->bo_numoutput > 0 || bo->bo_dirty.bv_cnt > 0)
1924                                 panic("vinvalbuf: dirty bufs");
1925                 }
1926         }
1927         /*
1928          * If you alter this loop please notice that interlock is dropped and
1929          * reacquired in flushbuflist.  Special care is needed to ensure that
1930          * no race conditions occur from this.
1931          */
1932         do {
1933                 error = flushbuflist(&bo->bo_clean,
1934                     flags, bo, slpflag, slptimeo);
1935                 if (error == 0 && !(flags & V_CLEANONLY))
1936                         error = flushbuflist(&bo->bo_dirty,
1937                             flags, bo, slpflag, slptimeo);
1938                 if (error != 0 && error != EAGAIN) {
1939                         BO_UNLOCK(bo);
1940                         return (error);
1941                 }
1942         } while (error != 0);
1943
1944         /*
1945          * Wait for I/O to complete.  XXX needs cleaning up.  The vnode can
1946          * have write I/O in-progress but if there is a VM object then the
1947          * VM object can also have read-I/O in-progress.
1948          */
1949         do {
1950                 bufobj_wwait(bo, 0, 0);
1951                 if ((flags & V_VMIO) == 0 && bo->bo_object != NULL) {
1952                         BO_UNLOCK(bo);
1953                         vm_object_pip_wait_unlocked(bo->bo_object, "bovlbx");
1954                         BO_LOCK(bo);
1955                 }
1956         } while (bo->bo_numoutput > 0);
1957         BO_UNLOCK(bo);
1958
1959         /*
1960          * Destroy the copy in the VM cache, too.
1961          */
1962         if (bo->bo_object != NULL &&
1963             (flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO)) == 0) {
1964                 VM_OBJECT_WLOCK(bo->bo_object);
1965                 vm_object_page_remove(bo->bo_object, 0, 0, (flags & V_SAVE) ?
1966                     OBJPR_CLEANONLY : 0);
1967                 VM_OBJECT_WUNLOCK(bo->bo_object);
1968         }
1969
1970 #ifdef INVARIANTS
1971         BO_LOCK(bo);
1972         if ((flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO |
1973             V_ALLOWCLEAN)) == 0 && (bo->bo_dirty.bv_cnt > 0 ||
1974             bo->bo_clean.bv_cnt > 0))
1975                 panic("vinvalbuf: flush failed");
1976         if ((flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO)) == 0 &&
1977             bo->bo_dirty.bv_cnt > 0)
1978                 panic("vinvalbuf: flush dirty failed");
1979         BO_UNLOCK(bo);
1980 #endif
1981         return (0);
1982 }
1983
1984 /*
1985  * Flush out and invalidate all buffers associated with a vnode.
1986  * Called with the underlying object locked.
1987  */
1988 int
1989 vinvalbuf(struct vnode *vp, int flags, int slpflag, int slptimeo)
1990 {
1991
1992         CTR3(KTR_VFS, "%s: vp %p with flags %d", __func__, vp, flags);
1993         ASSERT_VOP_LOCKED(vp, "vinvalbuf");
1994         if (vp->v_object != NULL && vp->v_object->handle != vp)
1995                 return (0);
1996         return (bufobj_invalbuf(&vp->v_bufobj, flags, slpflag, slptimeo));
1997 }
1998
1999 /*
2000  * Flush out buffers on the specified list.
2001  *
2002  */
2003 static int
2004 flushbuflist(struct bufv *bufv, int flags, struct bufobj *bo, int slpflag,
2005     int slptimeo)
2006 {
2007         struct buf *bp, *nbp;
2008         int retval, error;
2009         daddr_t lblkno;
2010         b_xflags_t xflags;
2011
2012         ASSERT_BO_WLOCKED(bo);
2013
2014         retval = 0;
2015         TAILQ_FOREACH_SAFE(bp, &bufv->bv_hd, b_bobufs, nbp) {
2016                 /*
2017                  * If we are flushing both V_NORMAL and V_ALT buffers then
2018                  * do not skip any buffers. If we are flushing only V_NORMAL
2019                  * buffers then skip buffers marked as BX_ALTDATA. If we are
2020                  * flushing only V_ALT buffers then skip buffers not marked
2021                  * as BX_ALTDATA.
2022                  */
2023                 if (((flags & (V_NORMAL | V_ALT)) != (V_NORMAL | V_ALT)) &&
2024                    (((flags & V_NORMAL) && (bp->b_xflags & BX_ALTDATA) != 0) ||
2025                     ((flags & V_ALT) && (bp->b_xflags & BX_ALTDATA) == 0))) {
2026                         continue;
2027                 }
2028                 if (nbp != NULL) {
2029                         lblkno = nbp->b_lblkno;
2030                         xflags = nbp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN);
2031                 }
2032                 retval = EAGAIN;
2033                 error = BUF_TIMELOCK(bp,
2034                     LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, BO_LOCKPTR(bo),
2035                     "flushbuf", slpflag, slptimeo);
2036                 if (error) {
2037                         BO_LOCK(bo);
2038                         return (error != ENOLCK ? error : EAGAIN);
2039                 }
2040                 KASSERT(bp->b_bufobj == bo,
2041                     ("bp %p wrong b_bufobj %p should be %p",
2042                     bp, bp->b_bufobj, bo));
2043                 /*
2044                  * XXX Since there are no node locks for NFS, I
2045                  * believe there is a slight chance that a delayed
2046                  * write will occur while sleeping just above, so
2047                  * check for it.
2048                  */
2049                 if (((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI) &&
2050                     (flags & V_SAVE)) {
2051                         bremfree(bp);
2052                         bp->b_flags |= B_ASYNC;
2053                         bwrite(bp);
2054                         BO_LOCK(bo);
2055                         return (EAGAIN);        /* XXX: why not loop ? */
2056                 }
2057                 bremfree(bp);
2058                 bp->b_flags |= (B_INVAL | B_RELBUF);
2059                 bp->b_flags &= ~B_ASYNC;
2060                 brelse(bp);
2061                 BO_LOCK(bo);
2062                 if (nbp == NULL)
2063                         break;
2064                 nbp = gbincore(bo, lblkno);
2065                 if (nbp == NULL || (nbp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
2066                     != xflags)
2067                         break;                  /* nbp invalid */
2068         }
2069         return (retval);
2070 }
2071
2072 int
2073 bnoreuselist(struct bufv *bufv, struct bufobj *bo, daddr_t startn, daddr_t endn)
2074 {
2075         struct buf *bp;
2076         int error;
2077         daddr_t lblkno;
2078
2079         ASSERT_BO_LOCKED(bo);
2080
2081         for (lblkno = startn;;) {
2082 again:
2083                 bp = BUF_PCTRIE_LOOKUP_GE(&bufv->bv_root, lblkno);
2084                 if (bp == NULL || bp->b_lblkno >= endn ||
2085                     bp->b_lblkno < startn)
2086                         break;
2087                 error = BUF_TIMELOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
2088                     LK_INTERLOCK, BO_LOCKPTR(bo), "brlsfl", 0, 0);
2089                 if (error != 0) {
2090                         BO_RLOCK(bo);
2091                         if (error == ENOLCK)
2092                                 goto again;
2093                         return (error);
2094                 }
2095                 KASSERT(bp->b_bufobj == bo,
2096                     ("bp %p wrong b_bufobj %p should be %p",
2097                     bp, bp->b_bufobj, bo));
2098                 lblkno = bp->b_lblkno + 1;
2099                 if ((bp->b_flags & B_MANAGED) == 0)
2100                         bremfree(bp);
2101                 bp->b_flags |= B_RELBUF;
2102                 /*
2103                  * In the VMIO case, use the B_NOREUSE flag to hint that the
2104                  * pages backing each buffer in the range are unlikely to be
2105                  * reused.  Dirty buffers will have the hint applied once
2106                  * they've been written.
2107                  */
2108                 if ((bp->b_flags & B_VMIO) != 0)
2109                         bp->b_flags |= B_NOREUSE;
2110                 brelse(bp);
2111                 BO_RLOCK(bo);
2112         }
2113         return (0);
2114 }
2115
2116 /*
2117  * Truncate a file's buffer and pages to a specified length.  This
2118  * is in lieu of the old vinvalbuf mechanism, which performed unneeded
2119  * sync activity.
2120  */
2121 int
2122 vtruncbuf(struct vnode *vp, off_t length, int blksize)
2123 {
2124         struct buf *bp, *nbp;
2125         struct bufobj *bo;
2126         daddr_t startlbn;
2127
2128         CTR4(KTR_VFS, "%s: vp %p with block %d:%ju", __func__,
2129             vp, blksize, (uintmax_t)length);
2130
2131         /*
2132          * Round up to the *next* lbn.
2133          */
2134         startlbn = howmany(length, blksize);
2135
2136         ASSERT_VOP_LOCKED(vp, "vtruncbuf");
2137
2138         bo = &vp->v_bufobj;
2139 restart_unlocked:
2140         BO_LOCK(bo);
2141
2142         while (v_inval_buf_range_locked(vp, bo, startlbn, INT64_MAX) == EAGAIN)
2143                 ;
2144
2145         if (length > 0) {
2146 restartsync:
2147                 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
2148                         if (bp->b_lblkno > 0)
2149                                 continue;
2150                         /*
2151                          * Since we hold the vnode lock this should only
2152                          * fail if we're racing with the buf daemon.
2153                          */
2154                         if (BUF_LOCK(bp,
2155                             LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2156                             BO_LOCKPTR(bo)) == ENOLCK)
2157                                 goto restart_unlocked;
2158
2159                         VNASSERT((bp->b_flags & B_DELWRI), vp,
2160                             ("buf(%p) on dirty queue without DELWRI", bp));
2161
2162                         bremfree(bp);
2163                         bawrite(bp);
2164                         BO_LOCK(bo);
2165                         goto restartsync;
2166                 }
2167         }
2168
2169         bufobj_wwait(bo, 0, 0);
2170         BO_UNLOCK(bo);
2171         vnode_pager_setsize(vp, length);
2172
2173         return (0);
2174 }
2175
2176 /*
2177  * Invalidate the cached pages of a file's buffer within the range of block
2178  * numbers [startlbn, endlbn).
2179  */
2180 void
2181 v_inval_buf_range(struct vnode *vp, daddr_t startlbn, daddr_t endlbn,
2182     int blksize)
2183 {
2184         struct bufobj *bo;
2185         off_t start, end;
2186
2187         ASSERT_VOP_LOCKED(vp, "v_inval_buf_range");
2188
2189         start = blksize * startlbn;
2190         end = blksize * endlbn;
2191
2192         bo = &vp->v_bufobj;
2193         BO_LOCK(bo);
2194         MPASS(blksize == bo->bo_bsize);
2195
2196         while (v_inval_buf_range_locked(vp, bo, startlbn, endlbn) == EAGAIN)
2197                 ;
2198
2199         BO_UNLOCK(bo);
2200         vn_pages_remove(vp, OFF_TO_IDX(start), OFF_TO_IDX(end + PAGE_SIZE - 1));
2201 }
2202
2203 static int
2204 v_inval_buf_range_locked(struct vnode *vp, struct bufobj *bo,
2205     daddr_t startlbn, daddr_t endlbn)
2206 {
2207         struct buf *bp, *nbp;
2208         bool anyfreed;
2209
2210         ASSERT_VOP_LOCKED(vp, "v_inval_buf_range_locked");
2211         ASSERT_BO_LOCKED(bo);
2212
2213         do {
2214                 anyfreed = false;
2215                 TAILQ_FOREACH_SAFE(bp, &bo->bo_clean.bv_hd, b_bobufs, nbp) {
2216                         if (bp->b_lblkno < startlbn || bp->b_lblkno >= endlbn)
2217                                 continue;
2218                         if (BUF_LOCK(bp,
2219                             LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2220                             BO_LOCKPTR(bo)) == ENOLCK) {
2221                                 BO_LOCK(bo);
2222                                 return (EAGAIN);
2223                         }
2224
2225                         bremfree(bp);
2226                         bp->b_flags |= B_INVAL | B_RELBUF;
2227                         bp->b_flags &= ~B_ASYNC;
2228                         brelse(bp);
2229                         anyfreed = true;
2230
2231                         BO_LOCK(bo);
2232                         if (nbp != NULL &&
2233                             (((nbp->b_xflags & BX_VNCLEAN) == 0) ||
2234                             nbp->b_vp != vp ||
2235                             (nbp->b_flags & B_DELWRI) != 0))
2236                                 return (EAGAIN);
2237                 }
2238
2239                 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
2240                         if (bp->b_lblkno < startlbn || bp->b_lblkno >= endlbn)
2241                                 continue;
2242                         if (BUF_LOCK(bp,
2243                             LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2244                             BO_LOCKPTR(bo)) == ENOLCK) {
2245                                 BO_LOCK(bo);
2246                                 return (EAGAIN);
2247                         }
2248                         bremfree(bp);
2249                         bp->b_flags |= B_INVAL | B_RELBUF;
2250                         bp->b_flags &= ~B_ASYNC;
2251                         brelse(bp);
2252                         anyfreed = true;
2253
2254                         BO_LOCK(bo);
2255                         if (nbp != NULL &&
2256                             (((nbp->b_xflags & BX_VNDIRTY) == 0) ||
2257                             (nbp->b_vp != vp) ||
2258                             (nbp->b_flags & B_DELWRI) == 0))
2259                                 return (EAGAIN);
2260                 }
2261         } while (anyfreed);
2262         return (0);
2263 }
2264
2265 static void
2266 buf_vlist_remove(struct buf *bp)
2267 {
2268         struct bufv *bv;
2269
2270         KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
2271         ASSERT_BO_WLOCKED(bp->b_bufobj);
2272         KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) !=
2273             (BX_VNDIRTY|BX_VNCLEAN),
2274             ("buf_vlist_remove: Buf %p is on two lists", bp));
2275         if (bp->b_xflags & BX_VNDIRTY)
2276                 bv = &bp->b_bufobj->bo_dirty;
2277         else
2278                 bv = &bp->b_bufobj->bo_clean;
2279         BUF_PCTRIE_REMOVE(&bv->bv_root, bp->b_lblkno);
2280         TAILQ_REMOVE(&bv->bv_hd, bp, b_bobufs);
2281         bv->bv_cnt--;
2282         bp->b_xflags &= ~(BX_VNDIRTY | BX_VNCLEAN);
2283 }
2284
2285 /*
2286  * Add the buffer to the sorted clean or dirty block list.
2287  *
2288  * NOTE: xflags is passed as a constant, optimizing this inline function!
2289  */
2290 static void
2291 buf_vlist_add(struct buf *bp, struct bufobj *bo, b_xflags_t xflags)
2292 {
2293         struct bufv *bv;
2294         struct buf *n;
2295         int error;
2296
2297         ASSERT_BO_WLOCKED(bo);
2298         KASSERT((bo->bo_flag & BO_NOBUFS) == 0,
2299             ("buf_vlist_add: bo %p does not allow bufs", bo));
2300         KASSERT((xflags & BX_VNDIRTY) == 0 || (bo->bo_flag & BO_DEAD) == 0,
2301             ("dead bo %p", bo));
2302         KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0,
2303             ("buf_vlist_add: Buf %p has existing xflags %d", bp, bp->b_xflags));
2304         bp->b_xflags |= xflags;
2305         if (xflags & BX_VNDIRTY)
2306                 bv = &bo->bo_dirty;
2307         else
2308                 bv = &bo->bo_clean;
2309
2310         /*
2311          * Keep the list ordered.  Optimize empty list insertion.  Assume
2312          * we tend to grow at the tail so lookup_le should usually be cheaper
2313          * than _ge. 
2314          */
2315         if (bv->bv_cnt == 0 ||
2316             bp->b_lblkno > TAILQ_LAST(&bv->bv_hd, buflists)->b_lblkno)
2317                 TAILQ_INSERT_TAIL(&bv->bv_hd, bp, b_bobufs);
2318         else if ((n = BUF_PCTRIE_LOOKUP_LE(&bv->bv_root, bp->b_lblkno)) == NULL)
2319                 TAILQ_INSERT_HEAD(&bv->bv_hd, bp, b_bobufs);
2320         else
2321                 TAILQ_INSERT_AFTER(&bv->bv_hd, n, bp, b_bobufs);
2322         error = BUF_PCTRIE_INSERT(&bv->bv_root, bp);
2323         if (error)
2324                 panic("buf_vlist_add:  Preallocated nodes insufficient.");
2325         bv->bv_cnt++;
2326 }
2327
2328 /*
2329  * Look up a buffer using the buffer tries.
2330  */
2331 struct buf *
2332 gbincore(struct bufobj *bo, daddr_t lblkno)
2333 {
2334         struct buf *bp;
2335
2336         ASSERT_BO_LOCKED(bo);
2337         bp = BUF_PCTRIE_LOOKUP(&bo->bo_clean.bv_root, lblkno);
2338         if (bp != NULL)
2339                 return (bp);
2340         return (BUF_PCTRIE_LOOKUP(&bo->bo_dirty.bv_root, lblkno));
2341 }
2342
2343 /*
2344  * Look up a buf using the buffer tries, without the bufobj lock.  This relies
2345  * on SMR for safe lookup, and bufs being in a no-free zone to provide type
2346  * stability of the result.  Like other lockless lookups, the found buf may
2347  * already be invalid by the time this function returns.
2348  */
2349 struct buf *
2350 gbincore_unlocked(struct bufobj *bo, daddr_t lblkno)
2351 {
2352         struct buf *bp;
2353
2354         ASSERT_BO_UNLOCKED(bo);
2355         bp = BUF_PCTRIE_LOOKUP_UNLOCKED(&bo->bo_clean.bv_root, lblkno);
2356         if (bp != NULL)
2357                 return (bp);
2358         return (BUF_PCTRIE_LOOKUP_UNLOCKED(&bo->bo_dirty.bv_root, lblkno));
2359 }
2360
2361 /*
2362  * Associate a buffer with a vnode.
2363  */
2364 void
2365 bgetvp(struct vnode *vp, struct buf *bp)
2366 {
2367         struct bufobj *bo;
2368
2369         bo = &vp->v_bufobj;
2370         ASSERT_BO_WLOCKED(bo);
2371         VNASSERT(bp->b_vp == NULL, bp->b_vp, ("bgetvp: not free"));
2372
2373         CTR3(KTR_BUF, "bgetvp(%p) vp %p flags %X", bp, vp, bp->b_flags);
2374         VNASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0, vp,
2375             ("bgetvp: bp already attached! %p", bp));
2376
2377         vhold(vp);
2378         bp->b_vp = vp;
2379         bp->b_bufobj = bo;
2380         /*
2381          * Insert onto list for new vnode.
2382          */
2383         buf_vlist_add(bp, bo, BX_VNCLEAN);
2384 }
2385
2386 /*
2387  * Disassociate a buffer from a vnode.
2388  */
2389 void
2390 brelvp(struct buf *bp)
2391 {
2392         struct bufobj *bo;
2393         struct vnode *vp;
2394
2395         CTR3(KTR_BUF, "brelvp(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2396         KASSERT(bp->b_vp != NULL, ("brelvp: NULL"));
2397
2398         /*
2399          * Delete from old vnode list, if on one.
2400          */
2401         vp = bp->b_vp;          /* XXX */
2402         bo = bp->b_bufobj;
2403         BO_LOCK(bo);
2404         if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
2405                 buf_vlist_remove(bp);
2406         else
2407                 panic("brelvp: Buffer %p not on queue.", bp);
2408         if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
2409                 bo->bo_flag &= ~BO_ONWORKLST;
2410                 mtx_lock(&sync_mtx);
2411                 LIST_REMOVE(bo, bo_synclist);
2412                 syncer_worklist_len--;
2413                 mtx_unlock(&sync_mtx);
2414         }
2415         bp->b_vp = NULL;
2416         bp->b_bufobj = NULL;
2417         BO_UNLOCK(bo);
2418         vdrop(vp);
2419 }
2420
2421 /*
2422  * Add an item to the syncer work queue.
2423  */
2424 static void
2425 vn_syncer_add_to_worklist(struct bufobj *bo, int delay)
2426 {
2427         int slot;
2428
2429         ASSERT_BO_WLOCKED(bo);
2430
2431         mtx_lock(&sync_mtx);
2432         if (bo->bo_flag & BO_ONWORKLST)
2433                 LIST_REMOVE(bo, bo_synclist);
2434         else {
2435                 bo->bo_flag |= BO_ONWORKLST;
2436                 syncer_worklist_len++;
2437         }
2438
2439         if (delay > syncer_maxdelay - 2)
2440                 delay = syncer_maxdelay - 2;
2441         slot = (syncer_delayno + delay) & syncer_mask;
2442
2443         LIST_INSERT_HEAD(&syncer_workitem_pending[slot], bo, bo_synclist);
2444         mtx_unlock(&sync_mtx);
2445 }
2446
2447 static int
2448 sysctl_vfs_worklist_len(SYSCTL_HANDLER_ARGS)
2449 {
2450         int error, len;
2451
2452         mtx_lock(&sync_mtx);
2453         len = syncer_worklist_len - sync_vnode_count;
2454         mtx_unlock(&sync_mtx);
2455         error = SYSCTL_OUT(req, &len, sizeof(len));
2456         return (error);
2457 }
2458
2459 SYSCTL_PROC(_vfs, OID_AUTO, worklist_len,
2460     CTLTYPE_INT | CTLFLAG_MPSAFE| CTLFLAG_RD, NULL, 0,
2461     sysctl_vfs_worklist_len, "I", "Syncer thread worklist length");
2462
2463 static struct proc *updateproc;
2464 static void sched_sync(void);
2465 static struct kproc_desc up_kp = {
2466         "syncer",
2467         sched_sync,
2468         &updateproc
2469 };
2470 SYSINIT(syncer, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start, &up_kp);
2471
2472 static int
2473 sync_vnode(struct synclist *slp, struct bufobj **bo, struct thread *td)
2474 {
2475         struct vnode *vp;
2476         struct mount *mp;
2477
2478         *bo = LIST_FIRST(slp);
2479         if (*bo == NULL)
2480                 return (0);
2481         vp = bo2vnode(*bo);
2482         if (VOP_ISLOCKED(vp) != 0 || VI_TRYLOCK(vp) == 0)
2483                 return (1);
2484         /*
2485          * We use vhold in case the vnode does not
2486          * successfully sync.  vhold prevents the vnode from
2487          * going away when we unlock the sync_mtx so that
2488          * we can acquire the vnode interlock.
2489          */
2490         vholdl(vp);
2491         mtx_unlock(&sync_mtx);
2492         VI_UNLOCK(vp);
2493         if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
2494                 vdrop(vp);
2495                 mtx_lock(&sync_mtx);
2496                 return (*bo == LIST_FIRST(slp));
2497         }
2498         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2499         (void) VOP_FSYNC(vp, MNT_LAZY, td);
2500         VOP_UNLOCK(vp);
2501         vn_finished_write(mp);
2502         BO_LOCK(*bo);
2503         if (((*bo)->bo_flag & BO_ONWORKLST) != 0) {
2504                 /*
2505                  * Put us back on the worklist.  The worklist
2506                  * routine will remove us from our current
2507                  * position and then add us back in at a later
2508                  * position.
2509                  */
2510                 vn_syncer_add_to_worklist(*bo, syncdelay);
2511         }
2512         BO_UNLOCK(*bo);
2513         vdrop(vp);
2514         mtx_lock(&sync_mtx);
2515         return (0);
2516 }
2517
2518 static int first_printf = 1;
2519
2520 /*
2521  * System filesystem synchronizer daemon.
2522  */
2523 static void
2524 sched_sync(void)
2525 {
2526         struct synclist *next, *slp;
2527         struct bufobj *bo;
2528         long starttime;
2529         struct thread *td = curthread;
2530         int last_work_seen;
2531         int net_worklist_len;
2532         int syncer_final_iter;
2533         int error;
2534
2535         last_work_seen = 0;
2536         syncer_final_iter = 0;
2537         syncer_state = SYNCER_RUNNING;
2538         starttime = time_uptime;
2539         td->td_pflags |= TDP_NORUNNINGBUF;
2540
2541         EVENTHANDLER_REGISTER(shutdown_pre_sync, syncer_shutdown, td->td_proc,
2542             SHUTDOWN_PRI_LAST);
2543
2544         mtx_lock(&sync_mtx);
2545         for (;;) {
2546                 if (syncer_state == SYNCER_FINAL_DELAY &&
2547                     syncer_final_iter == 0) {
2548                         mtx_unlock(&sync_mtx);
2549                         kproc_suspend_check(td->td_proc);
2550                         mtx_lock(&sync_mtx);
2551                 }
2552                 net_worklist_len = syncer_worklist_len - sync_vnode_count;
2553                 if (syncer_state != SYNCER_RUNNING &&
2554                     starttime != time_uptime) {
2555                         if (first_printf) {
2556                                 printf("\nSyncing disks, vnodes remaining... ");
2557                                 first_printf = 0;
2558                         }
2559                         printf("%d ", net_worklist_len);
2560                 }
2561                 starttime = time_uptime;
2562
2563                 /*
2564                  * Push files whose dirty time has expired.  Be careful
2565                  * of interrupt race on slp queue.
2566                  *
2567                  * Skip over empty worklist slots when shutting down.
2568                  */
2569                 do {
2570                         slp = &syncer_workitem_pending[syncer_delayno];
2571                         syncer_delayno += 1;
2572                         if (syncer_delayno == syncer_maxdelay)
2573                                 syncer_delayno = 0;
2574                         next = &syncer_workitem_pending[syncer_delayno];
2575                         /*
2576                          * If the worklist has wrapped since the
2577                          * it was emptied of all but syncer vnodes,
2578                          * switch to the FINAL_DELAY state and run
2579                          * for one more second.
2580                          */
2581                         if (syncer_state == SYNCER_SHUTTING_DOWN &&
2582                             net_worklist_len == 0 &&
2583                             last_work_seen == syncer_delayno) {
2584                                 syncer_state = SYNCER_FINAL_DELAY;
2585                                 syncer_final_iter = SYNCER_SHUTDOWN_SPEEDUP;
2586                         }
2587                 } while (syncer_state != SYNCER_RUNNING && LIST_EMPTY(slp) &&
2588                     syncer_worklist_len > 0);
2589
2590                 /*
2591                  * Keep track of the last time there was anything
2592                  * on the worklist other than syncer vnodes.
2593                  * Return to the SHUTTING_DOWN state if any
2594                  * new work appears.
2595                  */
2596                 if (net_worklist_len > 0 || syncer_state == SYNCER_RUNNING)
2597                         last_work_seen = syncer_delayno;
2598                 if (net_worklist_len > 0 && syncer_state == SYNCER_FINAL_DELAY)
2599                         syncer_state = SYNCER_SHUTTING_DOWN;
2600                 while (!LIST_EMPTY(slp)) {
2601                         error = sync_vnode(slp, &bo, td);
2602                         if (error == 1) {
2603                                 LIST_REMOVE(bo, bo_synclist);
2604                                 LIST_INSERT_HEAD(next, bo, bo_synclist);
2605                                 continue;
2606                         }
2607
2608                         if (first_printf == 0) {
2609                                 /*
2610                                  * Drop the sync mutex, because some watchdog
2611                                  * drivers need to sleep while patting
2612                                  */
2613                                 mtx_unlock(&sync_mtx);
2614                                 wdog_kern_pat(WD_LASTVAL);
2615                                 mtx_lock(&sync_mtx);
2616                         }
2617
2618                 }
2619                 if (syncer_state == SYNCER_FINAL_DELAY && syncer_final_iter > 0)
2620                         syncer_final_iter--;
2621                 /*
2622                  * The variable rushjob allows the kernel to speed up the
2623                  * processing of the filesystem syncer process. A rushjob
2624                  * value of N tells the filesystem syncer to process the next
2625                  * N seconds worth of work on its queue ASAP. Currently rushjob
2626                  * is used by the soft update code to speed up the filesystem
2627                  * syncer process when the incore state is getting so far
2628                  * ahead of the disk that the kernel memory pool is being
2629                  * threatened with exhaustion.
2630                  */
2631                 if (rushjob > 0) {
2632                         rushjob -= 1;
2633                         continue;
2634                 }
2635                 /*
2636                  * Just sleep for a short period of time between
2637                  * iterations when shutting down to allow some I/O
2638                  * to happen.
2639                  *
2640                  * If it has taken us less than a second to process the
2641                  * current work, then wait. Otherwise start right over
2642                  * again. We can still lose time if any single round
2643                  * takes more than two seconds, but it does not really
2644                  * matter as we are just trying to generally pace the
2645                  * filesystem activity.
2646                  */
2647                 if (syncer_state != SYNCER_RUNNING ||
2648                     time_uptime == starttime) {
2649                         thread_lock(td);
2650                         sched_prio(td, PPAUSE);
2651                         thread_unlock(td);
2652                 }
2653                 if (syncer_state != SYNCER_RUNNING)
2654                         cv_timedwait(&sync_wakeup, &sync_mtx,
2655                             hz / SYNCER_SHUTDOWN_SPEEDUP);
2656                 else if (time_uptime == starttime)
2657                         cv_timedwait(&sync_wakeup, &sync_mtx, hz);
2658         }
2659 }
2660
2661 /*
2662  * Request the syncer daemon to speed up its work.
2663  * We never push it to speed up more than half of its
2664  * normal turn time, otherwise it could take over the cpu.
2665  */
2666 int
2667 speedup_syncer(void)
2668 {
2669         int ret = 0;
2670
2671         mtx_lock(&sync_mtx);
2672         if (rushjob < syncdelay / 2) {
2673                 rushjob += 1;
2674                 stat_rush_requests += 1;
2675                 ret = 1;
2676         }
2677         mtx_unlock(&sync_mtx);
2678         cv_broadcast(&sync_wakeup);
2679         return (ret);
2680 }
2681
2682 /*
2683  * Tell the syncer to speed up its work and run though its work
2684  * list several times, then tell it to shut down.
2685  */
2686 static void
2687 syncer_shutdown(void *arg, int howto)
2688 {
2689
2690         if (howto & RB_NOSYNC)
2691                 return;
2692         mtx_lock(&sync_mtx);
2693         syncer_state = SYNCER_SHUTTING_DOWN;
2694         rushjob = 0;
2695         mtx_unlock(&sync_mtx);
2696         cv_broadcast(&sync_wakeup);
2697         kproc_shutdown(arg, howto);
2698 }
2699
2700 void
2701 syncer_suspend(void)
2702 {
2703
2704         syncer_shutdown(updateproc, 0);
2705 }
2706
2707 void
2708 syncer_resume(void)
2709 {
2710
2711         mtx_lock(&sync_mtx);
2712         first_printf = 1;
2713         syncer_state = SYNCER_RUNNING;
2714         mtx_unlock(&sync_mtx);
2715         cv_broadcast(&sync_wakeup);
2716         kproc_resume(updateproc);
2717 }
2718
2719 /*
2720  * Reassign a buffer from one vnode to another.
2721  * Used to assign file specific control information
2722  * (indirect blocks) to the vnode to which they belong.
2723  */
2724 void
2725 reassignbuf(struct buf *bp)
2726 {
2727         struct vnode *vp;
2728         struct bufobj *bo;
2729         int delay;
2730 #ifdef INVARIANTS
2731         struct bufv *bv;
2732 #endif
2733
2734         vp = bp->b_vp;
2735         bo = bp->b_bufobj;
2736         ++reassignbufcalls;
2737
2738         CTR3(KTR_BUF, "reassignbuf(%p) vp %p flags %X",
2739             bp, bp->b_vp, bp->b_flags);
2740         /*
2741          * B_PAGING flagged buffers cannot be reassigned because their vp
2742          * is not fully linked in.
2743          */
2744         if (bp->b_flags & B_PAGING)
2745                 panic("cannot reassign paging buffer");
2746
2747         /*
2748          * Delete from old vnode list, if on one.
2749          */
2750         BO_LOCK(bo);
2751         if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
2752                 buf_vlist_remove(bp);
2753         else
2754                 panic("reassignbuf: Buffer %p not on queue.", bp);
2755         /*
2756          * If dirty, put on list of dirty buffers; otherwise insert onto list
2757          * of clean buffers.
2758          */
2759         if (bp->b_flags & B_DELWRI) {
2760                 if ((bo->bo_flag & BO_ONWORKLST) == 0) {
2761                         switch (vp->v_type) {
2762                         case VDIR:
2763                                 delay = dirdelay;
2764                                 break;
2765                         case VCHR:
2766                                 delay = metadelay;
2767                                 break;
2768                         default:
2769                                 delay = filedelay;
2770                         }
2771                         vn_syncer_add_to_worklist(bo, delay);
2772                 }
2773                 buf_vlist_add(bp, bo, BX_VNDIRTY);
2774         } else {
2775                 buf_vlist_add(bp, bo, BX_VNCLEAN);
2776
2777                 if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
2778                         mtx_lock(&sync_mtx);
2779                         LIST_REMOVE(bo, bo_synclist);
2780                         syncer_worklist_len--;
2781                         mtx_unlock(&sync_mtx);
2782                         bo->bo_flag &= ~BO_ONWORKLST;
2783                 }
2784         }
2785 #ifdef INVARIANTS
2786         bv = &bo->bo_clean;
2787         bp = TAILQ_FIRST(&bv->bv_hd);
2788         KASSERT(bp == NULL || bp->b_bufobj == bo,
2789             ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2790         bp = TAILQ_LAST(&bv->bv_hd, buflists);
2791         KASSERT(bp == NULL || bp->b_bufobj == bo,
2792             ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2793         bv = &bo->bo_dirty;
2794         bp = TAILQ_FIRST(&bv->bv_hd);
2795         KASSERT(bp == NULL || bp->b_bufobj == bo,
2796             ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2797         bp = TAILQ_LAST(&bv->bv_hd, buflists);
2798         KASSERT(bp == NULL || bp->b_bufobj == bo,
2799             ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2800 #endif
2801         BO_UNLOCK(bo);
2802 }
2803
2804 static void
2805 v_init_counters(struct vnode *vp)
2806 {
2807
2808         VNASSERT(vp->v_type == VNON && vp->v_data == NULL && vp->v_iflag == 0,
2809             vp, ("%s called for an initialized vnode", __FUNCTION__));
2810         ASSERT_VI_UNLOCKED(vp, __FUNCTION__);
2811
2812         refcount_init(&vp->v_holdcnt, 1);
2813         refcount_init(&vp->v_usecount, 1);
2814 }
2815
2816 /*
2817  * Increment si_usecount of the associated device, if any.
2818  */
2819 static void
2820 v_incr_devcount(struct vnode *vp)
2821 {
2822
2823         ASSERT_VI_LOCKED(vp, __FUNCTION__);
2824         if (vp->v_type == VCHR && vp->v_rdev != NULL) {
2825                 dev_lock();
2826                 vp->v_rdev->si_usecount++;
2827                 dev_unlock();
2828         }
2829 }
2830
2831 /*
2832  * Decrement si_usecount of the associated device, if any.
2833  *
2834  * The caller is required to hold the interlock when transitioning a VCHR use
2835  * count to zero. This prevents a race with devfs_reclaim_vchr() that would
2836  * leak a si_usecount reference. The vnode lock will also prevent this race
2837  * if it is held while dropping the last ref.
2838  *
2839  * The race is:
2840  *
2841  * CPU1                                 CPU2
2842  *                                      devfs_reclaim_vchr
2843  * make v_usecount == 0
2844  *                                        VI_LOCK
2845  *                                        sees v_usecount == 0, no updates
2846  *                                        vp->v_rdev = NULL;
2847  *                                        ...
2848  *                                        VI_UNLOCK
2849  * VI_LOCK
2850  * v_decr_devcount
2851  *   sees v_rdev == NULL, no updates
2852  *
2853  * In this scenario si_devcount decrement is not performed.
2854  */
2855 static void
2856 v_decr_devcount(struct vnode *vp)
2857 {
2858
2859         ASSERT_VOP_LOCKED(vp, __func__);
2860         ASSERT_VI_LOCKED(vp, __FUNCTION__);
2861         if (vp->v_type == VCHR && vp->v_rdev != NULL) {
2862                 dev_lock();
2863                 VNPASS(vp->v_rdev->si_usecount > 0, vp);
2864                 vp->v_rdev->si_usecount--;
2865                 dev_unlock();
2866         }
2867 }
2868
2869 /*
2870  * Grab a particular vnode from the free list, increment its
2871  * reference count and lock it.  VIRF_DOOMED is set if the vnode
2872  * is being destroyed.  Only callers who specify LK_RETRY will
2873  * see doomed vnodes.  If inactive processing was delayed in
2874  * vput try to do it here.
2875  *
2876  * usecount is manipulated using atomics without holding any locks.
2877  *
2878  * holdcnt can be manipulated using atomics without holding any locks,
2879  * except when transitioning 1<->0, in which case the interlock is held.
2880  *
2881  * Consumers which don't guarantee liveness of the vnode can use SMR to
2882  * try to get a reference. Note this operation can fail since the vnode
2883  * may be awaiting getting freed by the time they get to it.
2884  */
2885 enum vgetstate
2886 vget_prep_smr(struct vnode *vp)
2887 {
2888         enum vgetstate vs;
2889
2890         VFS_SMR_ASSERT_ENTERED();
2891
2892         if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2893                 vs = VGET_USECOUNT;
2894         } else {
2895                 if (vhold_smr(vp))
2896                         vs = VGET_HOLDCNT;
2897                 else
2898                         vs = VGET_NONE;
2899         }
2900         return (vs);
2901 }
2902
2903 enum vgetstate
2904 vget_prep(struct vnode *vp)
2905 {
2906         enum vgetstate vs;
2907
2908         if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2909                 vs = VGET_USECOUNT;
2910         } else {
2911                 vhold(vp);
2912                 vs = VGET_HOLDCNT;
2913         }
2914         return (vs);
2915 }
2916
2917 int
2918 vget(struct vnode *vp, int flags, struct thread *td)
2919 {
2920         enum vgetstate vs;
2921
2922         MPASS(td == curthread);
2923
2924         vs = vget_prep(vp);
2925         return (vget_finish(vp, flags, vs));
2926 }
2927
2928 static int __noinline
2929 vget_finish_vchr(struct vnode *vp)
2930 {
2931
2932         VNASSERT(vp->v_type == VCHR, vp, ("type != VCHR)"));
2933
2934         /*
2935          * See the comment in vget_finish before usecount bump.
2936          */
2937         if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2938 #ifdef INVARIANTS
2939                 int old = atomic_fetchadd_int(&vp->v_holdcnt, -1);
2940                 VNASSERT(old > 0, vp, ("%s: wrong hold count %d", __func__, old));
2941 #else
2942                 refcount_release(&vp->v_holdcnt);
2943 #endif
2944                 return (0);
2945         }
2946
2947         VI_LOCK(vp);
2948         if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2949 #ifdef INVARIANTS
2950                 int old = atomic_fetchadd_int(&vp->v_holdcnt, -1);
2951                 VNASSERT(old > 1, vp, ("%s: wrong hold count %d", __func__, old));
2952 #else
2953                 refcount_release(&vp->v_holdcnt);
2954 #endif
2955                 VI_UNLOCK(vp);
2956                 return (0);
2957         }
2958         v_incr_devcount(vp);
2959         refcount_acquire(&vp->v_usecount);
2960         VI_UNLOCK(vp);
2961         return (0);
2962 }
2963
2964 int
2965 vget_finish(struct vnode *vp, int flags, enum vgetstate vs)
2966 {
2967         int error, old;
2968
2969         if ((flags & LK_INTERLOCK) != 0)
2970                 ASSERT_VI_LOCKED(vp, __func__);
2971         else
2972                 ASSERT_VI_UNLOCKED(vp, __func__);
2973         VNPASS(vs == VGET_HOLDCNT || vs == VGET_USECOUNT, vp);
2974         VNPASS(vp->v_holdcnt > 0, vp);
2975         VNPASS(vs == VGET_HOLDCNT || vp->v_usecount > 0, vp);
2976
2977         error = vn_lock(vp, flags);
2978         if (__predict_false(error != 0)) {
2979                 if (vs == VGET_USECOUNT)
2980                         vrele(vp);
2981                 else
2982                         vdrop(vp);
2983                 CTR2(KTR_VFS, "%s: impossible to lock vnode %p", __func__,
2984                     vp);
2985                 return (error);
2986         }
2987
2988         if (vs == VGET_USECOUNT)
2989                 return (0);
2990
2991         if (__predict_false(vp->v_type == VCHR))
2992                 return (vget_finish_vchr(vp));
2993
2994         /*
2995          * We hold the vnode. If the usecount is 0 it will be utilized to keep
2996          * the vnode around. Otherwise someone else lended their hold count and
2997          * we have to drop ours.
2998          */
2999         old = atomic_fetchadd_int(&vp->v_usecount, 1);
3000         VNASSERT(old >= 0, vp, ("%s: wrong use count %d", __func__, old));
3001         if (old != 0) {
3002 #ifdef INVARIANTS
3003                 old = atomic_fetchadd_int(&vp->v_holdcnt, -1);
3004                 VNASSERT(old > 1, vp, ("%s: wrong hold count %d", __func__, old));
3005 #else
3006                 refcount_release(&vp->v_holdcnt);
3007 #endif
3008         }
3009         return (0);
3010 }
3011
3012 /*
3013  * Increase the reference (use) and hold count of a vnode.
3014  * This will also remove the vnode from the free list if it is presently free.
3015  */
3016 static void __noinline
3017 vref_vchr(struct vnode *vp, bool interlock)
3018 {
3019
3020         /*
3021          * See the comment in vget_finish before usecount bump.
3022          */
3023         if (!interlock) {
3024                 if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
3025                         VNODE_REFCOUNT_FENCE_ACQ();
3026                         VNASSERT(vp->v_holdcnt > 0, vp,
3027                             ("%s: active vnode not held", __func__));
3028                         return;
3029                 }
3030                 VI_LOCK(vp);
3031                 /*
3032                  * By the time we get here the vnode might have been doomed, at
3033                  * which point the 0->1 use count transition is no longer
3034                  * protected by the interlock. Since it can't bounce back to
3035                  * VCHR and requires vref semantics, punt it back
3036                  */
3037                 if (__predict_false(vp->v_type == VBAD)) {
3038                         VI_UNLOCK(vp);
3039                         vref(vp);
3040                         return;
3041                 }
3042         }
3043         VNASSERT(vp->v_type == VCHR, vp, ("type != VCHR)"));
3044         if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
3045                 VNODE_REFCOUNT_FENCE_ACQ();
3046                 VNASSERT(vp->v_holdcnt > 0, vp,
3047                     ("%s: active vnode not held", __func__));
3048                 if (!interlock)
3049                         VI_UNLOCK(vp);
3050                 return;
3051         }
3052         vhold(vp);
3053         v_incr_devcount(vp);
3054         refcount_acquire(&vp->v_usecount);
3055         if (!interlock)
3056                 VI_UNLOCK(vp);
3057         return;
3058 }
3059
3060 void
3061 vref(struct vnode *vp)
3062 {
3063         int old;
3064
3065         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3066         if (__predict_false(vp->v_type == VCHR)) {
3067                  vref_vchr(vp, false);
3068                  return;
3069         }
3070
3071         if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
3072                 VNODE_REFCOUNT_FENCE_ACQ();
3073                 VNASSERT(vp->v_holdcnt > 0, vp,
3074                     ("%s: active vnode not held", __func__));
3075                 return;
3076         }
3077         vhold(vp);
3078         /*
3079          * See the comment in vget_finish.
3080          */
3081         old = atomic_fetchadd_int(&vp->v_usecount, 1);
3082         VNASSERT(old >= 0, vp, ("%s: wrong use count %d", __func__, old));
3083         if (old != 0) {
3084 #ifdef INVARIANTS
3085                 old = atomic_fetchadd_int(&vp->v_holdcnt, -1);
3086                 VNASSERT(old > 1, vp, ("%s: wrong hold count %d", __func__, old));
3087 #else
3088                 refcount_release(&vp->v_holdcnt);
3089 #endif
3090         }
3091 }
3092
3093 void
3094 vrefl(struct vnode *vp)
3095 {
3096
3097         ASSERT_VI_LOCKED(vp, __func__);
3098         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3099         if (__predict_false(vp->v_type == VCHR)) {
3100                 vref_vchr(vp, true);
3101                 return;
3102         }
3103         vref(vp);
3104 }
3105
3106 void
3107 vrefact(struct vnode *vp)
3108 {
3109
3110         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3111 #ifdef INVARIANTS
3112         int old = atomic_fetchadd_int(&vp->v_usecount, 1);
3113         VNASSERT(old > 0, vp, ("%s: wrong use count %d", __func__, old));
3114 #else
3115         refcount_acquire(&vp->v_usecount);
3116 #endif
3117 }
3118
3119 void
3120 vrefactn(struct vnode *vp, u_int n)
3121 {
3122
3123         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3124 #ifdef INVARIANTS
3125         int old = atomic_fetchadd_int(&vp->v_usecount, n);
3126         VNASSERT(old > 0, vp, ("%s: wrong use count %d", __func__, old));
3127 #else
3128         atomic_add_int(&vp->v_usecount, n);
3129 #endif
3130 }
3131
3132 /*
3133  * Return reference count of a vnode.
3134  *
3135  * The results of this call are only guaranteed when some mechanism is used to
3136  * stop other processes from gaining references to the vnode.  This may be the
3137  * case if the caller holds the only reference.  This is also useful when stale
3138  * data is acceptable as race conditions may be accounted for by some other
3139  * means.
3140  */
3141 int
3142 vrefcnt(struct vnode *vp)
3143 {
3144
3145         return (vp->v_usecount);
3146 }
3147
3148 void
3149 vlazy(struct vnode *vp)
3150 {
3151         struct mount *mp;
3152
3153         VNASSERT(vp->v_holdcnt > 0, vp, ("%s: vnode not held", __func__));
3154
3155         if ((vp->v_mflag & VMP_LAZYLIST) != 0)
3156                 return;
3157         /*
3158          * We may get here for inactive routines after the vnode got doomed.
3159          */
3160         if (VN_IS_DOOMED(vp))
3161                 return;
3162         mp = vp->v_mount;
3163         mtx_lock(&mp->mnt_listmtx);
3164         if ((vp->v_mflag & VMP_LAZYLIST) == 0) {
3165                 vp->v_mflag |= VMP_LAZYLIST;
3166                 TAILQ_INSERT_TAIL(&mp->mnt_lazyvnodelist, vp, v_lazylist);
3167                 mp->mnt_lazyvnodelistsize++;
3168         }
3169         mtx_unlock(&mp->mnt_listmtx);
3170 }
3171
3172 /*
3173  * This routine is only meant to be called from vgonel prior to dooming
3174  * the vnode.
3175  */
3176 static void
3177 vunlazy_gone(struct vnode *vp)
3178 {
3179         struct mount *mp;
3180
3181         ASSERT_VOP_ELOCKED(vp, __func__);
3182         ASSERT_VI_LOCKED(vp, __func__);
3183         VNPASS(!VN_IS_DOOMED(vp), vp);
3184
3185         if (vp->v_mflag & VMP_LAZYLIST) {
3186                 mp = vp->v_mount;
3187                 mtx_lock(&mp->mnt_listmtx);
3188                 VNPASS(vp->v_mflag & VMP_LAZYLIST, vp);
3189                 vp->v_mflag &= ~VMP_LAZYLIST;
3190                 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, vp, v_lazylist);
3191                 mp->mnt_lazyvnodelistsize--;
3192                 mtx_unlock(&mp->mnt_listmtx);
3193         }
3194 }
3195
3196 static void
3197 vdefer_inactive(struct vnode *vp)
3198 {
3199
3200         ASSERT_VI_LOCKED(vp, __func__);
3201         VNASSERT(vp->v_holdcnt > 0, vp,
3202             ("%s: vnode without hold count", __func__));
3203         if (VN_IS_DOOMED(vp)) {
3204                 vdropl(vp);
3205                 return;
3206         }
3207         if (vp->v_iflag & VI_DEFINACT) {
3208                 VNASSERT(vp->v_holdcnt > 1, vp, ("lost hold count"));
3209                 vdropl(vp);
3210                 return;
3211         }
3212         if (vp->v_usecount > 0) {
3213                 vp->v_iflag &= ~VI_OWEINACT;
3214                 vdropl(vp);
3215                 return;
3216         }
3217         vlazy(vp);
3218         vp->v_iflag |= VI_DEFINACT;
3219         VI_UNLOCK(vp);
3220         counter_u64_add(deferred_inact, 1);
3221 }
3222
3223 static void
3224 vdefer_inactive_unlocked(struct vnode *vp)
3225 {
3226
3227         VI_LOCK(vp);
3228         if ((vp->v_iflag & VI_OWEINACT) == 0) {
3229                 vdropl(vp);
3230                 return;
3231         }
3232         vdefer_inactive(vp);
3233 }
3234
3235 enum vput_op { VRELE, VPUT, VUNREF };
3236
3237 /*
3238  * Handle ->v_usecount transitioning to 0.
3239  *
3240  * By releasing the last usecount we take ownership of the hold count which
3241  * provides liveness of the vnode, meaning we have to vdrop.
3242  *
3243  * If the vnode is of type VCHR we may need to decrement si_usecount, see
3244  * v_decr_devcount for details.
3245  *
3246  * For all vnodes we may need to perform inactive processing. It requires an
3247  * exclusive lock on the vnode, while it is legal to call here with only a
3248  * shared lock (or no locks). If locking the vnode in an expected manner fails,
3249  * inactive processing gets deferred to the syncer.
3250  *
3251  * XXX Some filesystems pass in an exclusively locked vnode and strongly depend
3252  * on the lock being held all the way until VOP_INACTIVE. This in particular
3253  * happens with UFS which adds half-constructed vnodes to the hash, where they
3254  * can be found by other code.
3255  */
3256 static void
3257 vput_final(struct vnode *vp, enum vput_op func)
3258 {
3259         int error;
3260         bool want_unlock;
3261
3262         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3263         VNPASS(vp->v_holdcnt > 0, vp);
3264
3265         VI_LOCK(vp);
3266         if (__predict_false(vp->v_type == VCHR && func != VRELE))
3267                 v_decr_devcount(vp);
3268
3269         /*
3270          * By the time we got here someone else might have transitioned
3271          * the count back to > 0.
3272          */
3273         if (vp->v_usecount > 0)
3274                 goto out;
3275
3276         /*
3277          * If the vnode is doomed vgone already performed inactive processing
3278          * (if needed).
3279          */
3280         if (VN_IS_DOOMED(vp))
3281                 goto out;
3282
3283         if (__predict_true(VOP_NEED_INACTIVE(vp) == 0))
3284                 goto out;
3285
3286         if (vp->v_iflag & VI_DOINGINACT)
3287                 goto out;
3288
3289         /*
3290          * Locking operations here will drop the interlock and possibly the
3291          * vnode lock, opening a window where the vnode can get doomed all the
3292          * while ->v_usecount is 0. Set VI_OWEINACT to let vgone know to
3293          * perform inactive.
3294          */
3295         vp->v_iflag |= VI_OWEINACT;
3296         want_unlock = false;
3297         error = 0;
3298         switch (func) {
3299         case VRELE:
3300                 switch (VOP_ISLOCKED(vp)) {
3301                 case LK_EXCLUSIVE:
3302                         break;
3303                 case LK_EXCLOTHER:
3304                 case 0:
3305                         want_unlock = true;
3306                         error = vn_lock(vp, LK_EXCLUSIVE | LK_INTERLOCK);
3307                         VI_LOCK(vp);
3308                         break;
3309                 default:
3310                         /*
3311                          * The lock has at least one sharer, but we have no way
3312                          * to conclude whether this is us. Play it safe and
3313                          * defer processing.
3314                          */
3315                         error = EAGAIN;
3316                         break;
3317                 }
3318                 break;
3319         case VPUT:
3320                 want_unlock = true;
3321                 if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE) {
3322                         error = VOP_LOCK(vp, LK_UPGRADE | LK_INTERLOCK |
3323                             LK_NOWAIT);
3324                         VI_LOCK(vp);
3325                 }
3326                 break;
3327         case VUNREF:
3328                 if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE) {
3329                         error = VOP_LOCK(vp, LK_TRYUPGRADE | LK_INTERLOCK);
3330                         VI_LOCK(vp);
3331                 }
3332                 break;
3333         }
3334         if (error == 0) {
3335                 vinactive(vp);
3336                 if (want_unlock)
3337                         VOP_UNLOCK(vp);
3338                 vdropl(vp);
3339         } else {
3340                 vdefer_inactive(vp);
3341         }
3342         return;
3343 out:
3344         if (func == VPUT)
3345                 VOP_UNLOCK(vp);
3346         vdropl(vp);
3347 }
3348
3349 /*
3350  * Decrement ->v_usecount for a vnode.
3351  *
3352  * Releasing the last use count requires additional processing, see vput_final
3353  * above for details.
3354  *
3355  * Note that releasing use count without the vnode lock requires special casing
3356  * for VCHR, see v_decr_devcount for details.
3357  *
3358  * Comment above each variant denotes lock state on entry and exit.
3359  */
3360
3361 static void __noinline
3362 vrele_vchr(struct vnode *vp)
3363 {
3364
3365         if (refcount_release_if_not_last(&vp->v_usecount))
3366                 return;
3367         VI_LOCK(vp);
3368         if (!refcount_release(&vp->v_usecount)) {
3369                 VI_UNLOCK(vp);
3370                 return;
3371         }
3372         v_decr_devcount(vp);
3373         VI_UNLOCK(vp);
3374         vput_final(vp, VRELE);
3375 }
3376
3377 /*
3378  * in: any
3379  * out: same as passed in
3380  */
3381 void
3382 vrele(struct vnode *vp)
3383 {
3384
3385         ASSERT_VI_UNLOCKED(vp, __func__);
3386         if (__predict_false(vp->v_type == VCHR)) {
3387                 vrele_vchr(vp);
3388                 return;
3389         }
3390         if (!refcount_release(&vp->v_usecount))
3391                 return;
3392         vput_final(vp, VRELE);
3393 }
3394
3395 /*
3396  * in: locked
3397  * out: unlocked
3398  */
3399 void
3400 vput(struct vnode *vp)
3401 {
3402
3403         ASSERT_VOP_LOCKED(vp, __func__);
3404         ASSERT_VI_UNLOCKED(vp, __func__);
3405         if (!refcount_release(&vp->v_usecount)) {
3406                 VOP_UNLOCK(vp);
3407                 return;
3408         }
3409         vput_final(vp, VPUT);
3410 }
3411
3412 /*
3413  * in: locked
3414  * out: locked
3415  */
3416 void
3417 vunref(struct vnode *vp)
3418 {
3419
3420         ASSERT_VOP_LOCKED(vp, __func__);
3421         ASSERT_VI_UNLOCKED(vp, __func__);
3422         if (!refcount_release(&vp->v_usecount))
3423                 return;
3424         vput_final(vp, VUNREF);
3425 }
3426
3427 void
3428 vhold(struct vnode *vp)
3429 {
3430         struct vdbatch *vd;
3431         int old;
3432
3433         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3434         old = atomic_fetchadd_int(&vp->v_holdcnt, 1);
3435         VNASSERT(old >= 0 && (old & VHOLD_ALL_FLAGS) == 0, vp,
3436             ("%s: wrong hold count %d", __func__, old));
3437         if (old != 0)
3438                 return;
3439         critical_enter();
3440         vd = DPCPU_PTR(vd);
3441         vd->freevnodes--;
3442         critical_exit();
3443 }
3444
3445 void
3446 vholdl(struct vnode *vp)
3447 {
3448
3449         ASSERT_VI_LOCKED(vp, __func__);
3450         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3451         vhold(vp);
3452 }
3453
3454 void
3455 vholdnz(struct vnode *vp)
3456 {
3457
3458         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3459 #ifdef INVARIANTS
3460         int old = atomic_fetchadd_int(&vp->v_holdcnt, 1);
3461         VNASSERT(old > 0 && (old & VHOLD_ALL_FLAGS) == 0, vp,
3462             ("%s: wrong hold count %d", __func__, old));
3463 #else
3464         atomic_add_int(&vp->v_holdcnt, 1);
3465 #endif
3466 }
3467
3468 /*
3469  * Grab a hold count unless the vnode is freed.
3470  *
3471  * Only use this routine if vfs smr is the only protection you have against
3472  * freeing the vnode.
3473  *
3474  * The code loops trying to add a hold count as long as the VHOLD_NO_SMR flag
3475  * is not set.  After the flag is set the vnode becomes immutable to anyone but
3476  * the thread which managed to set the flag.
3477  *
3478  * It may be tempting to replace the loop with:
3479  * count = atomic_fetchadd_int(&vp->v_holdcnt, 1);
3480  * if (count & VHOLD_NO_SMR) {
3481  *     backpedal and error out;
3482  * }
3483  *
3484  * However, while this is more performant, it hinders debugging by eliminating
3485  * the previously mentioned invariant.
3486  */
3487 bool
3488 vhold_smr(struct vnode *vp)
3489 {
3490         int count;
3491
3492         VFS_SMR_ASSERT_ENTERED();
3493
3494         count = atomic_load_int(&vp->v_holdcnt);
3495         for (;;) {
3496                 if (count & VHOLD_NO_SMR) {
3497                         VNASSERT((count & ~VHOLD_NO_SMR) == 0, vp,
3498                             ("non-zero hold count with flags %d\n", count));
3499                         return (false);
3500                 }
3501
3502                 VNASSERT(count >= 0, vp, ("invalid hold count %d\n", count));
3503                 if (atomic_fcmpset_int(&vp->v_holdcnt, &count, count + 1))
3504                         return (true);
3505         }
3506 }
3507
3508 static void __noinline
3509 vdbatch_process(struct vdbatch *vd)
3510 {
3511         struct vnode *vp;
3512         int i;
3513
3514         mtx_assert(&vd->lock, MA_OWNED);
3515         MPASS(curthread->td_pinned > 0);
3516         MPASS(vd->index == VDBATCH_SIZE);
3517
3518         mtx_lock(&vnode_list_mtx);
3519         critical_enter();
3520         freevnodes += vd->freevnodes;
3521         for (i = 0; i < VDBATCH_SIZE; i++) {
3522                 vp = vd->tab[i];
3523                 TAILQ_REMOVE(&vnode_list, vp, v_vnodelist);
3524                 TAILQ_INSERT_TAIL(&vnode_list, vp, v_vnodelist);
3525                 MPASS(vp->v_dbatchcpu != NOCPU);
3526                 vp->v_dbatchcpu = NOCPU;
3527         }
3528         mtx_unlock(&vnode_list_mtx);
3529         vd->freevnodes = 0;
3530         bzero(vd->tab, sizeof(vd->tab));
3531         vd->index = 0;
3532         critical_exit();
3533 }
3534
3535 static void
3536 vdbatch_enqueue(struct vnode *vp)
3537 {
3538         struct vdbatch *vd;
3539
3540         ASSERT_VI_LOCKED(vp, __func__);
3541         VNASSERT(!VN_IS_DOOMED(vp), vp,
3542             ("%s: deferring requeue of a doomed vnode", __func__));
3543
3544         critical_enter();
3545         vd = DPCPU_PTR(vd);
3546         vd->freevnodes++;
3547         if (vp->v_dbatchcpu != NOCPU) {
3548                 VI_UNLOCK(vp);
3549                 critical_exit();
3550                 return;
3551         }
3552
3553         sched_pin();
3554         critical_exit();
3555         mtx_lock(&vd->lock);
3556         MPASS(vd->index < VDBATCH_SIZE);
3557         MPASS(vd->tab[vd->index] == NULL);
3558         /*
3559          * A hack: we depend on being pinned so that we know what to put in
3560          * ->v_dbatchcpu.
3561          */
3562         vp->v_dbatchcpu = curcpu;
3563         vd->tab[vd->index] = vp;
3564         vd->index++;
3565         VI_UNLOCK(vp);
3566         if (vd->index == VDBATCH_SIZE)
3567                 vdbatch_process(vd);
3568         mtx_unlock(&vd->lock);
3569         sched_unpin();
3570 }
3571
3572 /*
3573  * This routine must only be called for vnodes which are about to be
3574  * deallocated. Supporting dequeue for arbitrary vndoes would require
3575  * validating that the locked batch matches.
3576  */
3577 static void
3578 vdbatch_dequeue(struct vnode *vp)
3579 {
3580         struct vdbatch *vd;
3581         int i;
3582         short cpu;
3583
3584         VNASSERT(vp->v_type == VBAD || vp->v_type == VNON, vp,
3585             ("%s: called for a used vnode\n", __func__));
3586
3587         cpu = vp->v_dbatchcpu;
3588         if (cpu == NOCPU)
3589                 return;
3590
3591         vd = DPCPU_ID_PTR(cpu, vd);
3592         mtx_lock(&vd->lock);
3593         for (i = 0; i < vd->index; i++) {
3594                 if (vd->tab[i] != vp)
3595                         continue;
3596                 vp->v_dbatchcpu = NOCPU;
3597                 vd->index--;
3598                 vd->tab[i] = vd->tab[vd->index];
3599                 vd->tab[vd->index] = NULL;
3600                 break;
3601         }
3602         mtx_unlock(&vd->lock);
3603         /*
3604          * Either we dequeued the vnode above or the target CPU beat us to it.
3605          */
3606         MPASS(vp->v_dbatchcpu == NOCPU);
3607 }
3608
3609 /*
3610  * Drop the hold count of the vnode.  If this is the last reference to
3611  * the vnode we place it on the free list unless it has been vgone'd
3612  * (marked VIRF_DOOMED) in which case we will free it.
3613  *
3614  * Because the vnode vm object keeps a hold reference on the vnode if
3615  * there is at least one resident non-cached page, the vnode cannot
3616  * leave the active list without the page cleanup done.
3617  */
3618 static void
3619 vdrop_deactivate(struct vnode *vp)
3620 {
3621         struct mount *mp;
3622
3623         ASSERT_VI_LOCKED(vp, __func__);
3624         /*
3625          * Mark a vnode as free: remove it from its active list
3626          * and put it up for recycling on the freelist.
3627          */
3628         VNASSERT(!VN_IS_DOOMED(vp), vp,
3629             ("vdrop: returning doomed vnode"));
3630         VNASSERT(vp->v_op != NULL, vp,
3631             ("vdrop: vnode already reclaimed."));
3632         VNASSERT((vp->v_iflag & VI_OWEINACT) == 0, vp,
3633             ("vnode with VI_OWEINACT set"));
3634         VNASSERT((vp->v_iflag & VI_DEFINACT) == 0, vp,
3635             ("vnode with VI_DEFINACT set"));
3636         if (vp->v_mflag & VMP_LAZYLIST) {
3637                 mp = vp->v_mount;
3638                 mtx_lock(&mp->mnt_listmtx);
3639                 VNASSERT(vp->v_mflag & VMP_LAZYLIST, vp, ("lost VMP_LAZYLIST"));
3640                 /*
3641                  * Don't remove the vnode from the lazy list if another thread
3642                  * has increased the hold count. It may have re-enqueued the
3643                  * vnode to the lazy list and is now responsible for its
3644                  * removal.
3645                  */
3646                 if (vp->v_holdcnt == 0) {
3647                         vp->v_mflag &= ~VMP_LAZYLIST;
3648                         TAILQ_REMOVE(&mp->mnt_lazyvnodelist, vp, v_lazylist);
3649                         mp->mnt_lazyvnodelistsize--;
3650                 }
3651                 mtx_unlock(&mp->mnt_listmtx);
3652         }
3653         vdbatch_enqueue(vp);
3654 }
3655
3656 void
3657 vdrop(struct vnode *vp)
3658 {
3659
3660         ASSERT_VI_UNLOCKED(vp, __func__);
3661         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3662         if (refcount_release_if_not_last(&vp->v_holdcnt))
3663                 return;
3664         VI_LOCK(vp);
3665         vdropl(vp);
3666 }
3667
3668 void
3669 vdropl(struct vnode *vp)
3670 {
3671
3672         ASSERT_VI_LOCKED(vp, __func__);
3673         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3674         if (!refcount_release(&vp->v_holdcnt)) {
3675                 VI_UNLOCK(vp);
3676                 return;
3677         }
3678         if (!VN_IS_DOOMED(vp)) {
3679                 vdrop_deactivate(vp);
3680                 return;
3681         }
3682         /*
3683          * We may be racing against vhold_smr.
3684          *
3685          * If they win we can just pretend we never got this far, they will
3686          * vdrop later.
3687          */
3688         if (!atomic_cmpset_int(&vp->v_holdcnt, 0, VHOLD_NO_SMR)) {
3689                 /*
3690                  * We lost the aforementioned race. Note that any subsequent
3691                  * access is invalid as they might have managed to vdropl on
3692                  * their own.
3693                  */
3694                 return;
3695         }
3696         freevnode(vp);
3697 }
3698
3699 /*
3700  * Call VOP_INACTIVE on the vnode and manage the DOINGINACT and OWEINACT
3701  * flags.  DOINGINACT prevents us from recursing in calls to vinactive.
3702  */
3703 static void
3704 vinactivef(struct vnode *vp)
3705 {
3706         struct vm_object *obj;
3707
3708         ASSERT_VOP_ELOCKED(vp, "vinactive");
3709         ASSERT_VI_LOCKED(vp, "vinactive");
3710         VNASSERT((vp->v_iflag & VI_DOINGINACT) == 0, vp,
3711             ("vinactive: recursed on VI_DOINGINACT"));
3712         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3713         vp->v_iflag |= VI_DOINGINACT;
3714         vp->v_iflag &= ~VI_OWEINACT;
3715         VI_UNLOCK(vp);
3716         /*
3717          * Before moving off the active list, we must be sure that any
3718          * modified pages are converted into the vnode's dirty
3719          * buffers, since these will no longer be checked once the
3720          * vnode is on the inactive list.
3721          *
3722          * The write-out of the dirty pages is asynchronous.  At the
3723          * point that VOP_INACTIVE() is called, there could still be
3724          * pending I/O and dirty pages in the object.
3725          */
3726         if ((obj = vp->v_object) != NULL && (vp->v_vflag & VV_NOSYNC) == 0 &&
3727             vm_object_mightbedirty(obj)) {
3728                 VM_OBJECT_WLOCK(obj);
3729                 vm_object_page_clean(obj, 0, 0, 0);
3730                 VM_OBJECT_WUNLOCK(obj);
3731         }
3732         VOP_INACTIVE(vp, curthread);
3733         VI_LOCK(vp);
3734         VNASSERT(vp->v_iflag & VI_DOINGINACT, vp,
3735             ("vinactive: lost VI_DOINGINACT"));
3736         vp->v_iflag &= ~VI_DOINGINACT;
3737 }
3738
3739 void
3740 vinactive(struct vnode *vp)
3741 {
3742
3743         ASSERT_VOP_ELOCKED(vp, "vinactive");
3744         ASSERT_VI_LOCKED(vp, "vinactive");
3745         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3746
3747         if ((vp->v_iflag & VI_OWEINACT) == 0)
3748                 return;
3749         if (vp->v_iflag & VI_DOINGINACT)
3750                 return;
3751         if (vp->v_usecount > 0) {
3752                 vp->v_iflag &= ~VI_OWEINACT;
3753                 return;
3754         }
3755         vinactivef(vp);
3756 }
3757
3758 /*
3759  * Remove any vnodes in the vnode table belonging to mount point mp.
3760  *
3761  * If FORCECLOSE is not specified, there should not be any active ones,
3762  * return error if any are found (nb: this is a user error, not a
3763  * system error). If FORCECLOSE is specified, detach any active vnodes
3764  * that are found.
3765  *
3766  * If WRITECLOSE is set, only flush out regular file vnodes open for
3767  * writing.
3768  *
3769  * SKIPSYSTEM causes any vnodes marked VV_SYSTEM to be skipped.
3770  *
3771  * `rootrefs' specifies the base reference count for the root vnode
3772  * of this filesystem. The root vnode is considered busy if its
3773  * v_usecount exceeds this value. On a successful return, vflush(, td)
3774  * will call vrele() on the root vnode exactly rootrefs times.
3775  * If the SKIPSYSTEM or WRITECLOSE flags are specified, rootrefs must
3776  * be zero.
3777  */
3778 #ifdef DIAGNOSTIC
3779 static int busyprt = 0;         /* print out busy vnodes */
3780 SYSCTL_INT(_debug, OID_AUTO, busyprt, CTLFLAG_RW, &busyprt, 0, "Print out busy vnodes");
3781 #endif
3782
3783 int
3784 vflush(struct mount *mp, int rootrefs, int flags, struct thread *td)
3785 {
3786         struct vnode *vp, *mvp, *rootvp = NULL;
3787         struct vattr vattr;
3788         int busy = 0, error;
3789
3790         CTR4(KTR_VFS, "%s: mp %p with rootrefs %d and flags %d", __func__, mp,
3791             rootrefs, flags);
3792         if (rootrefs > 0) {
3793                 KASSERT((flags & (SKIPSYSTEM | WRITECLOSE)) == 0,
3794                     ("vflush: bad args"));
3795                 /*
3796                  * Get the filesystem root vnode. We can vput() it
3797                  * immediately, since with rootrefs > 0, it won't go away.
3798                  */
3799                 if ((error = VFS_ROOT(mp, LK_EXCLUSIVE, &rootvp)) != 0) {
3800                         CTR2(KTR_VFS, "%s: vfs_root lookup failed with %d",
3801                             __func__, error);
3802                         return (error);
3803                 }
3804                 vput(rootvp);
3805         }
3806 loop:
3807         MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
3808                 vholdl(vp);
3809                 error = vn_lock(vp, LK_INTERLOCK | LK_EXCLUSIVE);
3810                 if (error) {
3811                         vdrop(vp);
3812                         MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
3813                         goto loop;
3814                 }
3815                 /*
3816                  * Skip over a vnodes marked VV_SYSTEM.
3817                  */
3818                 if ((flags & SKIPSYSTEM) && (vp->v_vflag & VV_SYSTEM)) {
3819                         VOP_UNLOCK(vp);
3820                         vdrop(vp);
3821                         continue;
3822                 }
3823                 /*
3824                  * If WRITECLOSE is set, flush out unlinked but still open
3825                  * files (even if open only for reading) and regular file
3826                  * vnodes open for writing.
3827                  */
3828                 if (flags & WRITECLOSE) {
3829                         if (vp->v_object != NULL) {
3830                                 VM_OBJECT_WLOCK(vp->v_object);
3831                                 vm_object_page_clean(vp->v_object, 0, 0, 0);
3832                                 VM_OBJECT_WUNLOCK(vp->v_object);
3833                         }
3834                         error = VOP_FSYNC(vp, MNT_WAIT, td);
3835                         if (error != 0) {
3836                                 VOP_UNLOCK(vp);
3837                                 vdrop(vp);
3838                                 MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
3839                                 return (error);
3840                         }
3841                         error = VOP_GETATTR(vp, &vattr, td->td_ucred);
3842                         VI_LOCK(vp);
3843
3844                         if ((vp->v_type == VNON ||
3845                             (error == 0 && vattr.va_nlink > 0)) &&
3846                             (vp->v_writecount <= 0 || vp->v_type != VREG)) {
3847                                 VOP_UNLOCK(vp);
3848                                 vdropl(vp);
3849                                 continue;
3850                         }
3851                 } else
3852                         VI_LOCK(vp);
3853                 /*
3854                  * With v_usecount == 0, all we need to do is clear out the
3855                  * vnode data structures and we are done.
3856                  *
3857                  * If FORCECLOSE is set, forcibly close the vnode.
3858                  */
3859                 if (vp->v_usecount == 0 || (flags & FORCECLOSE)) {
3860                         vgonel(vp);
3861                 } else {
3862                         busy++;
3863 #ifdef DIAGNOSTIC
3864                         if (busyprt)
3865                                 vn_printf(vp, "vflush: busy vnode ");
3866 #endif
3867                 }
3868                 VOP_UNLOCK(vp);
3869                 vdropl(vp);
3870         }
3871         if (rootrefs > 0 && (flags & FORCECLOSE) == 0) {
3872                 /*
3873                  * If just the root vnode is busy, and if its refcount
3874                  * is equal to `rootrefs', then go ahead and kill it.
3875                  */
3876                 VI_LOCK(rootvp);
3877                 KASSERT(busy > 0, ("vflush: not busy"));
3878                 VNASSERT(rootvp->v_usecount >= rootrefs, rootvp,
3879                     ("vflush: usecount %d < rootrefs %d",
3880                      rootvp->v_usecount, rootrefs));
3881                 if (busy == 1 && rootvp->v_usecount == rootrefs) {
3882                         VOP_LOCK(rootvp, LK_EXCLUSIVE|LK_INTERLOCK);
3883                         vgone(rootvp);
3884                         VOP_UNLOCK(rootvp);
3885                         busy = 0;
3886                 } else
3887                         VI_UNLOCK(rootvp);
3888         }
3889         if (busy) {
3890                 CTR2(KTR_VFS, "%s: failing as %d vnodes are busy", __func__,
3891                     busy);
3892                 return (EBUSY);
3893         }
3894         for (; rootrefs > 0; rootrefs--)
3895                 vrele(rootvp);
3896         return (0);
3897 }
3898
3899 /*
3900  * Recycle an unused vnode to the front of the free list.
3901  */
3902 int
3903 vrecycle(struct vnode *vp)
3904 {
3905         int recycled;
3906
3907         VI_LOCK(vp);
3908         recycled = vrecyclel(vp);
3909         VI_UNLOCK(vp);
3910         return (recycled);
3911 }
3912
3913 /*
3914  * vrecycle, with the vp interlock held.
3915  */
3916 int
3917 vrecyclel(struct vnode *vp)
3918 {
3919         int recycled;
3920
3921         ASSERT_VOP_ELOCKED(vp, __func__);
3922         ASSERT_VI_LOCKED(vp, __func__);
3923         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3924         recycled = 0;
3925         if (vp->v_usecount == 0) {
3926                 recycled = 1;
3927                 vgonel(vp);
3928         }
3929         return (recycled);
3930 }
3931
3932 /*
3933  * Eliminate all activity associated with a vnode
3934  * in preparation for reuse.
3935  */
3936 void
3937 vgone(struct vnode *vp)
3938 {
3939         VI_LOCK(vp);
3940         vgonel(vp);
3941         VI_UNLOCK(vp);
3942 }
3943
3944 static void
3945 notify_lowervp_vfs_dummy(struct mount *mp __unused,
3946     struct vnode *lowervp __unused)
3947 {
3948 }
3949
3950 /*
3951  * Notify upper mounts about reclaimed or unlinked vnode.
3952  */
3953 void
3954 vfs_notify_upper(struct vnode *vp, int event)
3955 {
3956         static struct vfsops vgonel_vfsops = {
3957                 .vfs_reclaim_lowervp = notify_lowervp_vfs_dummy,
3958                 .vfs_unlink_lowervp = notify_lowervp_vfs_dummy,
3959         };
3960         struct mount *mp, *ump, *mmp;
3961
3962         mp = vp->v_mount;
3963         if (mp == NULL)
3964                 return;
3965         if (TAILQ_EMPTY(&mp->mnt_uppers))
3966                 return;
3967
3968         mmp = malloc(sizeof(struct mount), M_TEMP, M_WAITOK | M_ZERO);
3969         mmp->mnt_op = &vgonel_vfsops;
3970         mmp->mnt_kern_flag |= MNTK_MARKER;
3971         MNT_ILOCK(mp);
3972         mp->mnt_kern_flag |= MNTK_VGONE_UPPER;
3973         for (ump = TAILQ_FIRST(&mp->mnt_uppers); ump != NULL;) {
3974                 if ((ump->mnt_kern_flag & MNTK_MARKER) != 0) {
3975                         ump = TAILQ_NEXT(ump, mnt_upper_link);
3976                         continue;
3977                 }
3978                 TAILQ_INSERT_AFTER(&mp->mnt_uppers, ump, mmp, mnt_upper_link);
3979                 MNT_IUNLOCK(mp);
3980                 switch (event) {
3981                 case VFS_NOTIFY_UPPER_RECLAIM:
3982                         VFS_RECLAIM_LOWERVP(ump, vp);
3983                         break;
3984                 case VFS_NOTIFY_UPPER_UNLINK:
3985                         VFS_UNLINK_LOWERVP(ump, vp);
3986                         break;
3987                 default:
3988                         KASSERT(0, ("invalid event %d", event));
3989                         break;
3990                 }
3991                 MNT_ILOCK(mp);
3992                 ump = TAILQ_NEXT(mmp, mnt_upper_link);
3993                 TAILQ_REMOVE(&mp->mnt_uppers, mmp, mnt_upper_link);
3994         }
3995         free(mmp, M_TEMP);
3996         mp->mnt_kern_flag &= ~MNTK_VGONE_UPPER;
3997         if ((mp->mnt_kern_flag & MNTK_VGONE_WAITER) != 0) {
3998                 mp->mnt_kern_flag &= ~MNTK_VGONE_WAITER;
3999                 wakeup(&mp->mnt_uppers);
4000         }
4001         MNT_IUNLOCK(mp);
4002 }
4003
4004 /*
4005  * vgone, with the vp interlock held.
4006  */
4007 static void
4008 vgonel(struct vnode *vp)
4009 {
4010         struct thread *td;
4011         struct mount *mp;
4012         vm_object_t object;
4013         bool active, oweinact;
4014
4015         ASSERT_VOP_ELOCKED(vp, "vgonel");
4016         ASSERT_VI_LOCKED(vp, "vgonel");
4017         VNASSERT(vp->v_holdcnt, vp,
4018             ("vgonel: vp %p has no reference.", vp));
4019         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
4020         td = curthread;
4021
4022         /*
4023          * Don't vgonel if we're already doomed.
4024          */
4025         if (vp->v_irflag & VIRF_DOOMED)
4026                 return;
4027         /*
4028          * Paired with freevnode.
4029          */
4030         vn_seqc_write_begin_locked(vp);
4031         vunlazy_gone(vp);
4032         vp->v_irflag |= VIRF_DOOMED;
4033
4034         /*
4035          * Check to see if the vnode is in use.  If so, we have to call
4036          * VOP_CLOSE() and VOP_INACTIVE().
4037          */
4038         active = vp->v_usecount > 0;
4039         oweinact = (vp->v_iflag & VI_OWEINACT) != 0;
4040         /*
4041          * If we need to do inactive VI_OWEINACT will be set.
4042          */
4043         if (vp->v_iflag & VI_DEFINACT) {
4044                 VNASSERT(vp->v_holdcnt > 1, vp, ("lost hold count"));
4045                 vp->v_iflag &= ~VI_DEFINACT;
4046                 vdropl(vp);
4047         } else {
4048                 VNASSERT(vp->v_holdcnt > 0, vp, ("vnode without hold count"));
4049                 VI_UNLOCK(vp);
4050         }
4051         vfs_notify_upper(vp, VFS_NOTIFY_UPPER_RECLAIM);
4052
4053         /*
4054          * If purging an active vnode, it must be closed and
4055          * deactivated before being reclaimed.
4056          */
4057         if (active)
4058                 VOP_CLOSE(vp, FNONBLOCK, NOCRED, td);
4059         if (oweinact || active) {
4060                 VI_LOCK(vp);
4061                 vinactivef(vp);
4062                 VI_UNLOCK(vp);
4063         }
4064         if (vp->v_type == VSOCK)
4065                 vfs_unp_reclaim(vp);
4066
4067         /*
4068          * Clean out any buffers associated with the vnode.
4069          * If the flush fails, just toss the buffers.
4070          */
4071         mp = NULL;
4072         if (!TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd))
4073                 (void) vn_start_secondary_write(vp, &mp, V_WAIT);
4074         if (vinvalbuf(vp, V_SAVE, 0, 0) != 0) {
4075                 while (vinvalbuf(vp, 0, 0, 0) != 0)
4076                         ;
4077         }
4078
4079         BO_LOCK(&vp->v_bufobj);
4080         KASSERT(TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd) &&
4081             vp->v_bufobj.bo_dirty.bv_cnt == 0 &&
4082             TAILQ_EMPTY(&vp->v_bufobj.bo_clean.bv_hd) &&
4083             vp->v_bufobj.bo_clean.bv_cnt == 0,
4084             ("vp %p bufobj not invalidated", vp));
4085
4086         /*
4087          * For VMIO bufobj, BO_DEAD is set later, or in
4088          * vm_object_terminate() after the object's page queue is
4089          * flushed.
4090          */
4091         object = vp->v_bufobj.bo_object;
4092         if (object == NULL)
4093                 vp->v_bufobj.bo_flag |= BO_DEAD;
4094         BO_UNLOCK(&vp->v_bufobj);
4095
4096         /*
4097          * Handle the VM part.  Tmpfs handles v_object on its own (the
4098          * OBJT_VNODE check).  Nullfs or other bypassing filesystems
4099          * should not touch the object borrowed from the lower vnode
4100          * (the handle check).
4101          */
4102         if (object != NULL && object->type == OBJT_VNODE &&
4103             object->handle == vp)
4104                 vnode_destroy_vobject(vp);
4105
4106         /*
4107          * Reclaim the vnode.
4108          */
4109         if (VOP_RECLAIM(vp, td))
4110                 panic("vgone: cannot reclaim");
4111         if (mp != NULL)
4112                 vn_finished_secondary_write(mp);
4113         VNASSERT(vp->v_object == NULL, vp,
4114             ("vop_reclaim left v_object vp=%p", vp));
4115         /*
4116          * Clear the advisory locks and wake up waiting threads.
4117          */
4118         (void)VOP_ADVLOCKPURGE(vp);
4119         vp->v_lockf = NULL;
4120         /*
4121          * Delete from old mount point vnode list.
4122          */
4123         delmntque(vp);
4124         cache_purge(vp);
4125         /*
4126          * Done with purge, reset to the standard lock and invalidate
4127          * the vnode.
4128          */
4129         VI_LOCK(vp);
4130         vp->v_vnlock = &vp->v_lock;
4131         vp->v_op = &dead_vnodeops;
4132         vp->v_type = VBAD;
4133 }
4134
4135 /*
4136  * Calculate the total number of references to a special device.
4137  */
4138 int
4139 vcount(struct vnode *vp)
4140 {
4141         int count;
4142
4143         dev_lock();
4144         count = vp->v_rdev->si_usecount;
4145         dev_unlock();
4146         return (count);
4147 }
4148
4149 /*
4150  * Print out a description of a vnode.
4151  */
4152 static const char * const typename[] =
4153 {"VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD",
4154  "VMARKER"};
4155
4156 _Static_assert((VHOLD_ALL_FLAGS & ~VHOLD_NO_SMR) == 0,
4157     "new hold count flag not added to vn_printf");
4158
4159 void
4160 vn_printf(struct vnode *vp, const char *fmt, ...)
4161 {
4162         va_list ap;
4163         char buf[256], buf2[16];
4164         u_long flags;
4165         u_int holdcnt;
4166
4167         va_start(ap, fmt);
4168         vprintf(fmt, ap);
4169         va_end(ap);
4170         printf("%p: ", (void *)vp);
4171         printf("type %s\n", typename[vp->v_type]);
4172         holdcnt = atomic_load_int(&vp->v_holdcnt);
4173         printf("    usecount %d, writecount %d, refcount %d seqc users %d",
4174             vp->v_usecount, vp->v_writecount, holdcnt & ~VHOLD_ALL_FLAGS,
4175             vp->v_seqc_users);
4176         switch (vp->v_type) {
4177         case VDIR:
4178                 printf(" mountedhere %p\n", vp->v_mountedhere);
4179                 break;
4180         case VCHR:
4181                 printf(" rdev %p\n", vp->v_rdev);
4182                 break;
4183         case VSOCK:
4184                 printf(" socket %p\n", vp->v_unpcb);
4185                 break;
4186         case VFIFO:
4187                 printf(" fifoinfo %p\n", vp->v_fifoinfo);
4188                 break;
4189         default:
4190                 printf("\n");
4191                 break;
4192         }
4193         buf[0] = '\0';
4194         buf[1] = '\0';
4195         if (holdcnt & VHOLD_NO_SMR)
4196                 strlcat(buf, "|VHOLD_NO_SMR", sizeof(buf));
4197         printf("    hold count flags (%s)\n", buf + 1);
4198
4199         buf[0] = '\0';
4200         buf[1] = '\0';
4201         if (vp->v_irflag & VIRF_DOOMED)
4202                 strlcat(buf, "|VIRF_DOOMED", sizeof(buf));
4203         flags = vp->v_irflag & ~(VIRF_DOOMED);
4204         if (flags != 0) {
4205                 snprintf(buf2, sizeof(buf2), "|VIRF(0x%lx)", flags);
4206                 strlcat(buf, buf2, sizeof(buf));
4207         }
4208         if (vp->v_vflag & VV_ROOT)
4209                 strlcat(buf, "|VV_ROOT", sizeof(buf));
4210         if (vp->v_vflag & VV_ISTTY)
4211                 strlcat(buf, "|VV_ISTTY", sizeof(buf));
4212         if (vp->v_vflag & VV_NOSYNC)
4213                 strlcat(buf, "|VV_NOSYNC", sizeof(buf));
4214         if (vp->v_vflag & VV_ETERNALDEV)
4215                 strlcat(buf, "|VV_ETERNALDEV", sizeof(buf));
4216         if (vp->v_vflag & VV_CACHEDLABEL)
4217                 strlcat(buf, "|VV_CACHEDLABEL", sizeof(buf));
4218         if (vp->v_vflag & VV_VMSIZEVNLOCK)
4219                 strlcat(buf, "|VV_VMSIZEVNLOCK", sizeof(buf));
4220         if (vp->v_vflag & VV_COPYONWRITE)
4221                 strlcat(buf, "|VV_COPYONWRITE", sizeof(buf));
4222         if (vp->v_vflag & VV_SYSTEM)
4223                 strlcat(buf, "|VV_SYSTEM", sizeof(buf));
4224         if (vp->v_vflag & VV_PROCDEP)
4225                 strlcat(buf, "|VV_PROCDEP", sizeof(buf));
4226         if (vp->v_vflag & VV_NOKNOTE)
4227                 strlcat(buf, "|VV_NOKNOTE", sizeof(buf));
4228         if (vp->v_vflag & VV_DELETED)
4229                 strlcat(buf, "|VV_DELETED", sizeof(buf));
4230         if (vp->v_vflag & VV_MD)
4231                 strlcat(buf, "|VV_MD", sizeof(buf));
4232         if (vp->v_vflag & VV_FORCEINSMQ)
4233                 strlcat(buf, "|VV_FORCEINSMQ", sizeof(buf));
4234         if (vp->v_vflag & VV_READLINK)
4235                 strlcat(buf, "|VV_READLINK", sizeof(buf));
4236         flags = vp->v_vflag & ~(VV_ROOT | VV_ISTTY | VV_NOSYNC | VV_ETERNALDEV |
4237             VV_CACHEDLABEL | VV_COPYONWRITE | VV_SYSTEM | VV_PROCDEP |
4238             VV_NOKNOTE | VV_DELETED | VV_MD | VV_FORCEINSMQ);
4239         if (flags != 0) {
4240                 snprintf(buf2, sizeof(buf2), "|VV(0x%lx)", flags);
4241                 strlcat(buf, buf2, sizeof(buf));
4242         }
4243         if (vp->v_iflag & VI_TEXT_REF)
4244                 strlcat(buf, "|VI_TEXT_REF", sizeof(buf));
4245         if (vp->v_iflag & VI_MOUNT)
4246                 strlcat(buf, "|VI_MOUNT", sizeof(buf));
4247         if (vp->v_iflag & VI_DOINGINACT)
4248                 strlcat(buf, "|VI_DOINGINACT", sizeof(buf));
4249         if (vp->v_iflag & VI_OWEINACT)
4250                 strlcat(buf, "|VI_OWEINACT", sizeof(buf));
4251         if (vp->v_iflag & VI_DEFINACT)
4252                 strlcat(buf, "|VI_DEFINACT", sizeof(buf));
4253         flags = vp->v_iflag & ~(VI_TEXT_REF | VI_MOUNT | VI_DOINGINACT |
4254             VI_OWEINACT | VI_DEFINACT);
4255         if (flags != 0) {
4256                 snprintf(buf2, sizeof(buf2), "|VI(0x%lx)", flags);
4257                 strlcat(buf, buf2, sizeof(buf));
4258         }
4259         if (vp->v_mflag & VMP_LAZYLIST)
4260                 strlcat(buf, "|VMP_LAZYLIST", sizeof(buf));
4261         flags = vp->v_mflag & ~(VMP_LAZYLIST);
4262         if (flags != 0) {
4263                 snprintf(buf2, sizeof(buf2), "|VMP(0x%lx)", flags);
4264                 strlcat(buf, buf2, sizeof(buf));
4265         }
4266         printf("    flags (%s)\n", buf + 1);
4267         if (mtx_owned(VI_MTX(vp)))
4268                 printf(" VI_LOCKed");
4269         if (vp->v_object != NULL)
4270                 printf("    v_object %p ref %d pages %d "
4271                     "cleanbuf %d dirtybuf %d\n",
4272                     vp->v_object, vp->v_object->ref_count,
4273                     vp->v_object->resident_page_count,
4274                     vp->v_bufobj.bo_clean.bv_cnt,
4275                     vp->v_bufobj.bo_dirty.bv_cnt);
4276         printf("    ");
4277         lockmgr_printinfo(vp->v_vnlock);
4278         if (vp->v_data != NULL)
4279                 VOP_PRINT(vp);
4280 }
4281
4282 #ifdef DDB
4283 /*
4284  * List all of the locked vnodes in the system.
4285  * Called when debugging the kernel.
4286  */
4287 DB_SHOW_COMMAND(lockedvnods, lockedvnodes)
4288 {
4289         struct mount *mp;
4290         struct vnode *vp;
4291
4292         /*
4293          * Note: because this is DDB, we can't obey the locking semantics
4294          * for these structures, which means we could catch an inconsistent
4295          * state and dereference a nasty pointer.  Not much to be done
4296          * about that.
4297          */
4298         db_printf("Locked vnodes\n");
4299         TAILQ_FOREACH(mp, &mountlist, mnt_list) {
4300                 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4301                         if (vp->v_type != VMARKER && VOP_ISLOCKED(vp))
4302                                 vn_printf(vp, "vnode ");
4303                 }
4304         }
4305 }
4306
4307 /*
4308  * Show details about the given vnode.
4309  */
4310 DB_SHOW_COMMAND(vnode, db_show_vnode)
4311 {
4312         struct vnode *vp;
4313
4314         if (!have_addr)
4315                 return;
4316         vp = (struct vnode *)addr;
4317         vn_printf(vp, "vnode ");
4318 }
4319
4320 /*
4321  * Show details about the given mount point.
4322  */
4323 DB_SHOW_COMMAND(mount, db_show_mount)
4324 {
4325         struct mount *mp;
4326         struct vfsopt *opt;
4327         struct statfs *sp;
4328         struct vnode *vp;
4329         char buf[512];
4330         uint64_t mflags;
4331         u_int flags;
4332
4333         if (!have_addr) {
4334                 /* No address given, print short info about all mount points. */
4335                 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
4336                         db_printf("%p %s on %s (%s)\n", mp,
4337                             mp->mnt_stat.f_mntfromname,
4338                             mp->mnt_stat.f_mntonname,
4339                             mp->mnt_stat.f_fstypename);
4340                         if (db_pager_quit)
4341                                 break;
4342                 }
4343                 db_printf("\nMore info: show mount <addr>\n");
4344                 return;
4345         }
4346
4347         mp = (struct mount *)addr;
4348         db_printf("%p %s on %s (%s)\n", mp, mp->mnt_stat.f_mntfromname,
4349             mp->mnt_stat.f_mntonname, mp->mnt_stat.f_fstypename);
4350
4351         buf[0] = '\0';
4352         mflags = mp->mnt_flag;
4353 #define MNT_FLAG(flag)  do {                                            \
4354         if (mflags & (flag)) {                                          \
4355                 if (buf[0] != '\0')                                     \
4356                         strlcat(buf, ", ", sizeof(buf));                \
4357                 strlcat(buf, (#flag) + 4, sizeof(buf));                 \
4358                 mflags &= ~(flag);                                      \
4359         }                                                               \
4360 } while (0)
4361         MNT_FLAG(MNT_RDONLY);
4362         MNT_FLAG(MNT_SYNCHRONOUS);
4363         MNT_FLAG(MNT_NOEXEC);
4364         MNT_FLAG(MNT_NOSUID);
4365         MNT_FLAG(MNT_NFS4ACLS);
4366         MNT_FLAG(MNT_UNION);
4367         MNT_FLAG(MNT_ASYNC);
4368         MNT_FLAG(MNT_SUIDDIR);
4369         MNT_FLAG(MNT_SOFTDEP);
4370         MNT_FLAG(MNT_NOSYMFOLLOW);
4371         MNT_FLAG(MNT_GJOURNAL);
4372         MNT_FLAG(MNT_MULTILABEL);
4373         MNT_FLAG(MNT_ACLS);
4374         MNT_FLAG(MNT_NOATIME);
4375         MNT_FLAG(MNT_NOCLUSTERR);
4376         MNT_FLAG(MNT_NOCLUSTERW);
4377         MNT_FLAG(MNT_SUJ);
4378         MNT_FLAG(MNT_EXRDONLY);
4379         MNT_FLAG(MNT_EXPORTED);
4380         MNT_FLAG(MNT_DEFEXPORTED);
4381         MNT_FLAG(MNT_EXPORTANON);
4382         MNT_FLAG(MNT_EXKERB);
4383         MNT_FLAG(MNT_EXPUBLIC);
4384         MNT_FLAG(MNT_LOCAL);
4385         MNT_FLAG(MNT_QUOTA);
4386         MNT_FLAG(MNT_ROOTFS);
4387         MNT_FLAG(MNT_USER);
4388         MNT_FLAG(MNT_IGNORE);
4389         MNT_FLAG(MNT_UPDATE);
4390         MNT_FLAG(MNT_DELEXPORT);
4391         MNT_FLAG(MNT_RELOAD);
4392         MNT_FLAG(MNT_FORCE);
4393         MNT_FLAG(MNT_SNAPSHOT);
4394         MNT_FLAG(MNT_BYFSID);
4395 #undef MNT_FLAG
4396         if (mflags != 0) {
4397                 if (buf[0] != '\0')
4398                         strlcat(buf, ", ", sizeof(buf));
4399                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
4400                     "0x%016jx", mflags);
4401         }
4402         db_printf("    mnt_flag = %s\n", buf);
4403
4404         buf[0] = '\0';
4405         flags = mp->mnt_kern_flag;
4406 #define MNT_KERN_FLAG(flag)     do {                                    \
4407         if (flags & (flag)) {                                           \
4408                 if (buf[0] != '\0')                                     \
4409                         strlcat(buf, ", ", sizeof(buf));                \
4410                 strlcat(buf, (#flag) + 5, sizeof(buf));                 \
4411                 flags &= ~(flag);                                       \
4412         }                                                               \
4413 } while (0)
4414         MNT_KERN_FLAG(MNTK_UNMOUNTF);
4415         MNT_KERN_FLAG(MNTK_ASYNC);
4416         MNT_KERN_FLAG(MNTK_SOFTDEP);
4417         MNT_KERN_FLAG(MNTK_DRAINING);
4418         MNT_KERN_FLAG(MNTK_REFEXPIRE);
4419         MNT_KERN_FLAG(MNTK_EXTENDED_SHARED);
4420         MNT_KERN_FLAG(MNTK_SHARED_WRITES);
4421         MNT_KERN_FLAG(MNTK_NO_IOPF);
4422         MNT_KERN_FLAG(MNTK_VGONE_UPPER);
4423         MNT_KERN_FLAG(MNTK_VGONE_WAITER);
4424         MNT_KERN_FLAG(MNTK_LOOKUP_EXCL_DOTDOT);
4425         MNT_KERN_FLAG(MNTK_MARKER);
4426         MNT_KERN_FLAG(MNTK_USES_BCACHE);
4427         MNT_KERN_FLAG(MNTK_NOASYNC);
4428         MNT_KERN_FLAG(MNTK_UNMOUNT);
4429         MNT_KERN_FLAG(MNTK_MWAIT);
4430         MNT_KERN_FLAG(MNTK_SUSPEND);
4431         MNT_KERN_FLAG(MNTK_SUSPEND2);
4432         MNT_KERN_FLAG(MNTK_SUSPENDED);
4433         MNT_KERN_FLAG(MNTK_LOOKUP_SHARED);
4434         MNT_KERN_FLAG(MNTK_NOKNOTE);
4435 #undef MNT_KERN_FLAG
4436         if (flags != 0) {
4437                 if (buf[0] != '\0')
4438                         strlcat(buf, ", ", sizeof(buf));
4439                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
4440                     "0x%08x", flags);
4441         }
4442         db_printf("    mnt_kern_flag = %s\n", buf);
4443
4444         db_printf("    mnt_opt = ");
4445         opt = TAILQ_FIRST(mp->mnt_opt);
4446         if (opt != NULL) {
4447                 db_printf("%s", opt->name);
4448                 opt = TAILQ_NEXT(opt, link);
4449                 while (opt != NULL) {
4450                         db_printf(", %s", opt->name);
4451                         opt = TAILQ_NEXT(opt, link);
4452                 }
4453         }
4454         db_printf("\n");
4455
4456         sp = &mp->mnt_stat;
4457         db_printf("    mnt_stat = { version=%u type=%u flags=0x%016jx "
4458             "bsize=%ju iosize=%ju blocks=%ju bfree=%ju bavail=%jd files=%ju "
4459             "ffree=%jd syncwrites=%ju asyncwrites=%ju syncreads=%ju "
4460             "asyncreads=%ju namemax=%u owner=%u fsid=[%d, %d] }\n",
4461             (u_int)sp->f_version, (u_int)sp->f_type, (uintmax_t)sp->f_flags,
4462             (uintmax_t)sp->f_bsize, (uintmax_t)sp->f_iosize,
4463             (uintmax_t)sp->f_blocks, (uintmax_t)sp->f_bfree,
4464             (intmax_t)sp->f_bavail, (uintmax_t)sp->f_files,
4465             (intmax_t)sp->f_ffree, (uintmax_t)sp->f_syncwrites,
4466             (uintmax_t)sp->f_asyncwrites, (uintmax_t)sp->f_syncreads,
4467             (uintmax_t)sp->f_asyncreads, (u_int)sp->f_namemax,
4468             (u_int)sp->f_owner, (int)sp->f_fsid.val[0], (int)sp->f_fsid.val[1]);
4469
4470         db_printf("    mnt_cred = { uid=%u ruid=%u",
4471             (u_int)mp->mnt_cred->cr_uid, (u_int)mp->mnt_cred->cr_ruid);
4472         if (jailed(mp->mnt_cred))
4473                 db_printf(", jail=%d", mp->mnt_cred->cr_prison->pr_id);
4474         db_printf(" }\n");
4475         db_printf("    mnt_ref = %d (with %d in the struct)\n",
4476             vfs_mount_fetch_counter(mp, MNT_COUNT_REF), mp->mnt_ref);
4477         db_printf("    mnt_gen = %d\n", mp->mnt_gen);
4478         db_printf("    mnt_nvnodelistsize = %d\n", mp->mnt_nvnodelistsize);
4479         db_printf("    mnt_lazyvnodelistsize = %d\n",
4480             mp->mnt_lazyvnodelistsize);
4481         db_printf("    mnt_writeopcount = %d (with %d in the struct)\n",
4482             vfs_mount_fetch_counter(mp, MNT_COUNT_WRITEOPCOUNT), mp->mnt_writeopcount);
4483         db_printf("    mnt_maxsymlinklen = %d\n", mp->mnt_maxsymlinklen);
4484         db_printf("    mnt_iosize_max = %d\n", mp->mnt_iosize_max);
4485         db_printf("    mnt_hashseed = %u\n", mp->mnt_hashseed);
4486         db_printf("    mnt_lockref = %d (with %d in the struct)\n",
4487             vfs_mount_fetch_counter(mp, MNT_COUNT_LOCKREF), mp->mnt_lockref);
4488         db_printf("    mnt_secondary_writes = %d\n", mp->mnt_secondary_writes);
4489         db_printf("    mnt_secondary_accwrites = %d\n",
4490             mp->mnt_secondary_accwrites);
4491         db_printf("    mnt_gjprovider = %s\n",
4492             mp->mnt_gjprovider != NULL ? mp->mnt_gjprovider : "NULL");
4493         db_printf("    mnt_vfs_ops = %d\n", mp->mnt_vfs_ops);
4494
4495         db_printf("\n\nList of active vnodes\n");
4496         TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4497                 if (vp->v_type != VMARKER && vp->v_holdcnt > 0) {
4498                         vn_printf(vp, "vnode ");
4499                         if (db_pager_quit)
4500                                 break;
4501                 }
4502         }
4503         db_printf("\n\nList of inactive vnodes\n");
4504         TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4505                 if (vp->v_type != VMARKER && vp->v_holdcnt == 0) {
4506                         vn_printf(vp, "vnode ");
4507                         if (db_pager_quit)
4508                                 break;
4509                 }
4510         }
4511 }
4512 #endif  /* DDB */
4513
4514 /*
4515  * Fill in a struct xvfsconf based on a struct vfsconf.
4516  */
4517 static int
4518 vfsconf2x(struct sysctl_req *req, struct vfsconf *vfsp)
4519 {
4520         struct xvfsconf xvfsp;
4521
4522         bzero(&xvfsp, sizeof(xvfsp));
4523         strcpy(xvfsp.vfc_name, vfsp->vfc_name);
4524         xvfsp.vfc_typenum = vfsp->vfc_typenum;
4525         xvfsp.vfc_refcount = vfsp->vfc_refcount;
4526         xvfsp.vfc_flags = vfsp->vfc_flags;
4527         /*
4528          * These are unused in userland, we keep them
4529          * to not break binary compatibility.
4530          */
4531         xvfsp.vfc_vfsops = NULL;
4532         xvfsp.vfc_next = NULL;
4533         return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
4534 }
4535
4536 #ifdef COMPAT_FREEBSD32
4537 struct xvfsconf32 {
4538         uint32_t        vfc_vfsops;
4539         char            vfc_name[MFSNAMELEN];
4540         int32_t         vfc_typenum;
4541         int32_t         vfc_refcount;
4542         int32_t         vfc_flags;
4543         uint32_t        vfc_next;
4544 };
4545
4546 static int
4547 vfsconf2x32(struct sysctl_req *req, struct vfsconf *vfsp)
4548 {
4549         struct xvfsconf32 xvfsp;
4550
4551         bzero(&xvfsp, sizeof(xvfsp));
4552         strcpy(xvfsp.vfc_name, vfsp->vfc_name);
4553         xvfsp.vfc_typenum = vfsp->vfc_typenum;
4554         xvfsp.vfc_refcount = vfsp->vfc_refcount;
4555         xvfsp.vfc_flags = vfsp->vfc_flags;
4556         return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
4557 }
4558 #endif
4559
4560 /*
4561  * Top level filesystem related information gathering.
4562  */
4563 static int
4564 sysctl_vfs_conflist(SYSCTL_HANDLER_ARGS)
4565 {
4566         struct vfsconf *vfsp;
4567         int error;
4568
4569         error = 0;
4570         vfsconf_slock();
4571         TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4572 #ifdef COMPAT_FREEBSD32
4573                 if (req->flags & SCTL_MASK32)
4574                         error = vfsconf2x32(req, vfsp);
4575                 else
4576 #endif
4577                         error = vfsconf2x(req, vfsp);
4578                 if (error)
4579                         break;
4580         }
4581         vfsconf_sunlock();
4582         return (error);
4583 }
4584
4585 SYSCTL_PROC(_vfs, OID_AUTO, conflist, CTLTYPE_OPAQUE | CTLFLAG_RD |
4586     CTLFLAG_MPSAFE, NULL, 0, sysctl_vfs_conflist,
4587     "S,xvfsconf", "List of all configured filesystems");
4588
4589 #ifndef BURN_BRIDGES
4590 static int      sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS);
4591
4592 static int
4593 vfs_sysctl(SYSCTL_HANDLER_ARGS)
4594 {
4595         int *name = (int *)arg1 - 1;    /* XXX */
4596         u_int namelen = arg2 + 1;       /* XXX */
4597         struct vfsconf *vfsp;
4598
4599         log(LOG_WARNING, "userland calling deprecated sysctl, "
4600             "please rebuild world\n");
4601
4602 #if 1 || defined(COMPAT_PRELITE2)
4603         /* Resolve ambiguity between VFS_VFSCONF and VFS_GENERIC. */
4604         if (namelen == 1)
4605                 return (sysctl_ovfs_conf(oidp, arg1, arg2, req));
4606 #endif
4607
4608         switch (name[1]) {
4609         case VFS_MAXTYPENUM:
4610                 if (namelen != 2)
4611                         return (ENOTDIR);
4612                 return (SYSCTL_OUT(req, &maxvfsconf, sizeof(int)));
4613         case VFS_CONF:
4614                 if (namelen != 3)
4615                         return (ENOTDIR);       /* overloaded */
4616                 vfsconf_slock();
4617                 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4618                         if (vfsp->vfc_typenum == name[2])
4619                                 break;
4620                 }
4621                 vfsconf_sunlock();
4622                 if (vfsp == NULL)
4623                         return (EOPNOTSUPP);
4624 #ifdef COMPAT_FREEBSD32
4625                 if (req->flags & SCTL_MASK32)
4626                         return (vfsconf2x32(req, vfsp));
4627                 else
4628 #endif
4629                         return (vfsconf2x(req, vfsp));
4630         }
4631         return (EOPNOTSUPP);
4632 }
4633
4634 static SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RD | CTLFLAG_SKIP |
4635     CTLFLAG_MPSAFE, vfs_sysctl,
4636     "Generic filesystem");
4637
4638 #if 1 || defined(COMPAT_PRELITE2)
4639
4640 static int
4641 sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS)
4642 {
4643         int error;
4644         struct vfsconf *vfsp;
4645         struct ovfsconf ovfs;
4646
4647         vfsconf_slock();
4648         TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4649                 bzero(&ovfs, sizeof(ovfs));
4650                 ovfs.vfc_vfsops = vfsp->vfc_vfsops;     /* XXX used as flag */
4651                 strcpy(ovfs.vfc_name, vfsp->vfc_name);
4652                 ovfs.vfc_index = vfsp->vfc_typenum;
4653                 ovfs.vfc_refcount = vfsp->vfc_refcount;
4654                 ovfs.vfc_flags = vfsp->vfc_flags;
4655                 error = SYSCTL_OUT(req, &ovfs, sizeof ovfs);
4656                 if (error != 0) {
4657                         vfsconf_sunlock();
4658                         return (error);
4659                 }
4660         }
4661         vfsconf_sunlock();
4662         return (0);
4663 }
4664
4665 #endif /* 1 || COMPAT_PRELITE2 */
4666 #endif /* !BURN_BRIDGES */
4667
4668 #define KINFO_VNODESLOP         10
4669 #ifdef notyet
4670 /*
4671  * Dump vnode list (via sysctl).
4672  */
4673 /* ARGSUSED */
4674 static int
4675 sysctl_vnode(SYSCTL_HANDLER_ARGS)
4676 {
4677         struct xvnode *xvn;
4678         struct mount *mp;
4679         struct vnode *vp;
4680         int error, len, n;
4681
4682         /*
4683          * Stale numvnodes access is not fatal here.
4684          */
4685         req->lock = 0;
4686         len = (numvnodes + KINFO_VNODESLOP) * sizeof *xvn;
4687         if (!req->oldptr)
4688                 /* Make an estimate */
4689                 return (SYSCTL_OUT(req, 0, len));
4690
4691         error = sysctl_wire_old_buffer(req, 0);
4692         if (error != 0)
4693                 return (error);
4694         xvn = malloc(len, M_TEMP, M_ZERO | M_WAITOK);
4695         n = 0;
4696         mtx_lock(&mountlist_mtx);
4697         TAILQ_FOREACH(mp, &mountlist, mnt_list) {
4698                 if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK))
4699                         continue;
4700                 MNT_ILOCK(mp);
4701                 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4702                         if (n == len)
4703                                 break;
4704                         vref(vp);
4705                         xvn[n].xv_size = sizeof *xvn;
4706                         xvn[n].xv_vnode = vp;
4707                         xvn[n].xv_id = 0;       /* XXX compat */
4708 #define XV_COPY(field) xvn[n].xv_##field = vp->v_##field
4709                         XV_COPY(usecount);
4710                         XV_COPY(writecount);
4711                         XV_COPY(holdcnt);
4712                         XV_COPY(mount);
4713                         XV_COPY(numoutput);
4714                         XV_COPY(type);
4715 #undef XV_COPY
4716                         xvn[n].xv_flag = vp->v_vflag;
4717
4718                         switch (vp->v_type) {
4719                         case VREG:
4720                         case VDIR:
4721                         case VLNK:
4722                                 break;
4723                         case VBLK:
4724                         case VCHR:
4725                                 if (vp->v_rdev == NULL) {
4726                                         vrele(vp);
4727                                         continue;
4728                                 }
4729                                 xvn[n].xv_dev = dev2udev(vp->v_rdev);
4730                                 break;
4731                         case VSOCK:
4732                                 xvn[n].xv_socket = vp->v_socket;
4733                                 break;
4734                         case VFIFO:
4735                                 xvn[n].xv_fifo = vp->v_fifoinfo;
4736                                 break;
4737                         case VNON:
4738                         case VBAD:
4739                         default:
4740                                 /* shouldn't happen? */
4741                                 vrele(vp);
4742                                 continue;
4743                         }
4744                         vrele(vp);
4745                         ++n;
4746                 }
4747                 MNT_IUNLOCK(mp);
4748                 mtx_lock(&mountlist_mtx);
4749                 vfs_unbusy(mp);
4750                 if (n == len)
4751                         break;
4752         }
4753         mtx_unlock(&mountlist_mtx);
4754
4755         error = SYSCTL_OUT(req, xvn, n * sizeof *xvn);
4756         free(xvn, M_TEMP);
4757         return (error);
4758 }
4759
4760 SYSCTL_PROC(_kern, KERN_VNODE, vnode, CTLTYPE_OPAQUE | CTLFLAG_RD |
4761     CTLFLAG_MPSAFE, 0, 0, sysctl_vnode, "S,xvnode",
4762     "");
4763 #endif
4764
4765 static void
4766 unmount_or_warn(struct mount *mp)
4767 {
4768         int error;
4769
4770         error = dounmount(mp, MNT_FORCE, curthread);
4771         if (error != 0) {
4772                 printf("unmount of %s failed (", mp->mnt_stat.f_mntonname);
4773                 if (error == EBUSY)
4774                         printf("BUSY)\n");
4775                 else
4776                         printf("%d)\n", error);
4777         }
4778 }
4779
4780 /*
4781  * Unmount all filesystems. The list is traversed in reverse order
4782  * of mounting to avoid dependencies.
4783  */
4784 void
4785 vfs_unmountall(void)
4786 {
4787         struct mount *mp, *tmp;
4788
4789         CTR1(KTR_VFS, "%s: unmounting all filesystems", __func__);
4790
4791         /*
4792          * Since this only runs when rebooting, it is not interlocked.
4793          */
4794         TAILQ_FOREACH_REVERSE_SAFE(mp, &mountlist, mntlist, mnt_list, tmp) {
4795                 vfs_ref(mp);
4796
4797                 /*
4798                  * Forcibly unmounting "/dev" before "/" would prevent clean
4799                  * unmount of the latter.
4800                  */
4801                 if (mp == rootdevmp)
4802                         continue;
4803
4804                 unmount_or_warn(mp);
4805         }
4806
4807         if (rootdevmp != NULL)
4808                 unmount_or_warn(rootdevmp);
4809 }
4810
4811 static void
4812 vfs_deferred_inactive(struct vnode *vp, int lkflags)
4813 {
4814
4815         ASSERT_VI_LOCKED(vp, __func__);
4816         VNASSERT((vp->v_iflag & VI_DEFINACT) == 0, vp, ("VI_DEFINACT still set"));
4817         if ((vp->v_iflag & VI_OWEINACT) == 0) {
4818                 vdropl(vp);
4819                 return;
4820         }
4821         if (vn_lock(vp, lkflags) == 0) {
4822                 VI_LOCK(vp);
4823                 vinactive(vp);
4824                 VOP_UNLOCK(vp);
4825                 vdropl(vp);
4826                 return;
4827         }
4828         vdefer_inactive_unlocked(vp);
4829 }
4830
4831 static int
4832 vfs_periodic_inactive_filter(struct vnode *vp, void *arg)
4833 {
4834
4835         return (vp->v_iflag & VI_DEFINACT);
4836 }
4837
4838 static void __noinline
4839 vfs_periodic_inactive(struct mount *mp, int flags)
4840 {
4841         struct vnode *vp, *mvp;
4842         int lkflags;
4843
4844         lkflags = LK_EXCLUSIVE | LK_INTERLOCK;
4845         if (flags != MNT_WAIT)
4846                 lkflags |= LK_NOWAIT;
4847
4848         MNT_VNODE_FOREACH_LAZY(vp, mp, mvp, vfs_periodic_inactive_filter, NULL) {
4849                 if ((vp->v_iflag & VI_DEFINACT) == 0) {
4850                         VI_UNLOCK(vp);
4851                         continue;
4852                 }
4853                 vp->v_iflag &= ~VI_DEFINACT;
4854                 vfs_deferred_inactive(vp, lkflags);
4855         }
4856 }
4857
4858 static inline bool
4859 vfs_want_msync(struct vnode *vp)
4860 {
4861         struct vm_object *obj;
4862
4863         /*
4864          * This test may be performed without any locks held.
4865          * We rely on vm_object's type stability.
4866          */
4867         if (vp->v_vflag & VV_NOSYNC)
4868                 return (false);
4869         obj = vp->v_object;
4870         return (obj != NULL && vm_object_mightbedirty(obj));
4871 }
4872
4873 static int
4874 vfs_periodic_msync_inactive_filter(struct vnode *vp, void *arg __unused)
4875 {
4876
4877         if (vp->v_vflag & VV_NOSYNC)
4878                 return (false);
4879         if (vp->v_iflag & VI_DEFINACT)
4880                 return (true);
4881         return (vfs_want_msync(vp));
4882 }
4883
4884 static void __noinline
4885 vfs_periodic_msync_inactive(struct mount *mp, int flags)
4886 {
4887         struct vnode *vp, *mvp;
4888         struct vm_object *obj;
4889         struct thread *td;
4890         int lkflags, objflags;
4891         bool seen_defer;
4892
4893         td = curthread;
4894
4895         lkflags = LK_EXCLUSIVE | LK_INTERLOCK;
4896         if (flags != MNT_WAIT) {
4897                 lkflags |= LK_NOWAIT;
4898                 objflags = OBJPC_NOSYNC;
4899         } else {
4900                 objflags = OBJPC_SYNC;
4901         }
4902
4903         MNT_VNODE_FOREACH_LAZY(vp, mp, mvp, vfs_periodic_msync_inactive_filter, NULL) {
4904                 seen_defer = false;
4905                 if (vp->v_iflag & VI_DEFINACT) {
4906                         vp->v_iflag &= ~VI_DEFINACT;
4907                         seen_defer = true;
4908                 }
4909                 if (!vfs_want_msync(vp)) {
4910                         if (seen_defer)
4911                                 vfs_deferred_inactive(vp, lkflags);
4912                         else
4913                                 VI_UNLOCK(vp);
4914                         continue;
4915                 }
4916                 if (vget(vp, lkflags, td) == 0) {
4917                         obj = vp->v_object;
4918                         if (obj != NULL && (vp->v_vflag & VV_NOSYNC) == 0) {
4919                                 VM_OBJECT_WLOCK(obj);
4920                                 vm_object_page_clean(obj, 0, 0, objflags);
4921                                 VM_OBJECT_WUNLOCK(obj);
4922                         }
4923                         vput(vp);
4924                         if (seen_defer)
4925                                 vdrop(vp);
4926                 } else {
4927                         if (seen_defer)
4928                                 vdefer_inactive_unlocked(vp);
4929                 }
4930         }
4931 }
4932
4933 void
4934 vfs_periodic(struct mount *mp, int flags)
4935 {
4936
4937         CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
4938
4939         if ((mp->mnt_kern_flag & MNTK_NOMSYNC) != 0)
4940                 vfs_periodic_inactive(mp, flags);
4941         else
4942                 vfs_periodic_msync_inactive(mp, flags);
4943 }
4944
4945 static void
4946 destroy_vpollinfo_free(struct vpollinfo *vi)
4947 {
4948
4949         knlist_destroy(&vi->vpi_selinfo.si_note);
4950         mtx_destroy(&vi->vpi_lock);
4951         uma_zfree(vnodepoll_zone, vi);
4952 }
4953
4954 static void
4955 destroy_vpollinfo(struct vpollinfo *vi)
4956 {
4957
4958         knlist_clear(&vi->vpi_selinfo.si_note, 1);
4959         seldrain(&vi->vpi_selinfo);
4960         destroy_vpollinfo_free(vi);
4961 }
4962
4963 /*
4964  * Initialize per-vnode helper structure to hold poll-related state.
4965  */
4966 void
4967 v_addpollinfo(struct vnode *vp)
4968 {
4969         struct vpollinfo *vi;
4970
4971         if (vp->v_pollinfo != NULL)
4972                 return;
4973         vi = uma_zalloc(vnodepoll_zone, M_WAITOK | M_ZERO);
4974         mtx_init(&vi->vpi_lock, "vnode pollinfo", NULL, MTX_DEF);
4975         knlist_init(&vi->vpi_selinfo.si_note, vp, vfs_knllock,
4976             vfs_knlunlock, vfs_knl_assert_locked, vfs_knl_assert_unlocked);
4977         VI_LOCK(vp);
4978         if (vp->v_pollinfo != NULL) {
4979                 VI_UNLOCK(vp);
4980                 destroy_vpollinfo_free(vi);
4981                 return;
4982         }
4983         vp->v_pollinfo = vi;
4984         VI_UNLOCK(vp);
4985 }
4986
4987 /*
4988  * Record a process's interest in events which might happen to
4989  * a vnode.  Because poll uses the historic select-style interface
4990  * internally, this routine serves as both the ``check for any
4991  * pending events'' and the ``record my interest in future events''
4992  * functions.  (These are done together, while the lock is held,
4993  * to avoid race conditions.)
4994  */
4995 int
4996 vn_pollrecord(struct vnode *vp, struct thread *td, int events)
4997 {
4998
4999         v_addpollinfo(vp);
5000         mtx_lock(&vp->v_pollinfo->vpi_lock);
5001         if (vp->v_pollinfo->vpi_revents & events) {
5002                 /*
5003                  * This leaves events we are not interested
5004                  * in available for the other process which
5005                  * which presumably had requested them
5006                  * (otherwise they would never have been
5007                  * recorded).
5008                  */
5009                 events &= vp->v_pollinfo->vpi_revents;
5010                 vp->v_pollinfo->vpi_revents &= ~events;
5011
5012                 mtx_unlock(&vp->v_pollinfo->vpi_lock);
5013                 return (events);
5014         }
5015         vp->v_pollinfo->vpi_events |= events;
5016         selrecord(td, &vp->v_pollinfo->vpi_selinfo);
5017         mtx_unlock(&vp->v_pollinfo->vpi_lock);
5018         return (0);
5019 }
5020
5021 /*
5022  * Routine to create and manage a filesystem syncer vnode.
5023  */
5024 #define sync_close ((int (*)(struct  vop_close_args *))nullop)
5025 static int      sync_fsync(struct  vop_fsync_args *);
5026 static int      sync_inactive(struct  vop_inactive_args *);
5027 static int      sync_reclaim(struct  vop_reclaim_args *);
5028
5029 static struct vop_vector sync_vnodeops = {
5030         .vop_bypass =   VOP_EOPNOTSUPP,
5031         .vop_close =    sync_close,             /* close */
5032         .vop_fsync =    sync_fsync,             /* fsync */
5033         .vop_inactive = sync_inactive,  /* inactive */
5034         .vop_need_inactive = vop_stdneed_inactive, /* need_inactive */
5035         .vop_reclaim =  sync_reclaim,   /* reclaim */
5036         .vop_lock1 =    vop_stdlock,    /* lock */
5037         .vop_unlock =   vop_stdunlock,  /* unlock */
5038         .vop_islocked = vop_stdislocked,        /* islocked */
5039 };
5040 VFS_VOP_VECTOR_REGISTER(sync_vnodeops);
5041
5042 /*
5043  * Create a new filesystem syncer vnode for the specified mount point.
5044  */
5045 void
5046 vfs_allocate_syncvnode(struct mount *mp)
5047 {
5048         struct vnode *vp;
5049         struct bufobj *bo;
5050         static long start, incr, next;
5051         int error;
5052
5053         /* Allocate a new vnode */
5054         error = getnewvnode("syncer", mp, &sync_vnodeops, &vp);
5055         if (error != 0)
5056                 panic("vfs_allocate_syncvnode: getnewvnode() failed");
5057         vp->v_type = VNON;
5058         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
5059         vp->v_vflag |= VV_FORCEINSMQ;
5060         error = insmntque(vp, mp);
5061         if (error != 0)
5062                 panic("vfs_allocate_syncvnode: insmntque() failed");
5063         vp->v_vflag &= ~VV_FORCEINSMQ;
5064         VOP_UNLOCK(vp);
5065         /*
5066          * Place the vnode onto the syncer worklist. We attempt to
5067          * scatter them about on the list so that they will go off
5068          * at evenly distributed times even if all the filesystems
5069          * are mounted at once.
5070          */
5071         next += incr;
5072         if (next == 0 || next > syncer_maxdelay) {
5073                 start /= 2;
5074                 incr /= 2;
5075                 if (start == 0) {
5076                         start = syncer_maxdelay / 2;
5077                         incr = syncer_maxdelay;
5078                 }
5079                 next = start;
5080         }
5081         bo = &vp->v_bufobj;
5082         BO_LOCK(bo);
5083         vn_syncer_add_to_worklist(bo, syncdelay > 0 ? next % syncdelay : 0);
5084         /* XXX - vn_syncer_add_to_worklist() also grabs and drops sync_mtx. */
5085         mtx_lock(&sync_mtx);
5086         sync_vnode_count++;
5087         if (mp->mnt_syncer == NULL) {
5088                 mp->mnt_syncer = vp;
5089                 vp = NULL;
5090         }
5091         mtx_unlock(&sync_mtx);
5092         BO_UNLOCK(bo);
5093         if (vp != NULL) {
5094                 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
5095                 vgone(vp);
5096                 vput(vp);
5097         }
5098 }
5099
5100 void
5101 vfs_deallocate_syncvnode(struct mount *mp)
5102 {
5103         struct vnode *vp;
5104
5105         mtx_lock(&sync_mtx);
5106         vp = mp->mnt_syncer;
5107         if (vp != NULL)
5108                 mp->mnt_syncer = NULL;
5109         mtx_unlock(&sync_mtx);
5110         if (vp != NULL)
5111                 vrele(vp);
5112 }
5113
5114 /*
5115  * Do a lazy sync of the filesystem.
5116  */
5117 static int
5118 sync_fsync(struct vop_fsync_args *ap)
5119 {
5120         struct vnode *syncvp = ap->a_vp;
5121         struct mount *mp = syncvp->v_mount;
5122         int error, save;
5123         struct bufobj *bo;
5124
5125         /*
5126          * We only need to do something if this is a lazy evaluation.
5127          */
5128         if (ap->a_waitfor != MNT_LAZY)
5129                 return (0);
5130
5131         /*
5132          * Move ourselves to the back of the sync list.
5133          */
5134         bo = &syncvp->v_bufobj;
5135         BO_LOCK(bo);
5136         vn_syncer_add_to_worklist(bo, syncdelay);
5137         BO_UNLOCK(bo);
5138
5139         /*
5140          * Walk the list of vnodes pushing all that are dirty and
5141          * not already on the sync list.
5142          */
5143         if (vfs_busy(mp, MBF_NOWAIT) != 0)
5144                 return (0);
5145         if (vn_start_write(NULL, &mp, V_NOWAIT) != 0) {
5146                 vfs_unbusy(mp);
5147                 return (0);
5148         }
5149         save = curthread_pflags_set(TDP_SYNCIO);
5150         /*
5151          * The filesystem at hand may be idle with free vnodes stored in the
5152          * batch.  Return them instead of letting them stay there indefinitely.
5153          */
5154         vfs_periodic(mp, MNT_NOWAIT);
5155         error = VFS_SYNC(mp, MNT_LAZY);
5156         curthread_pflags_restore(save);
5157         vn_finished_write(mp);
5158         vfs_unbusy(mp);
5159         return (error);
5160 }
5161
5162 /*
5163  * The syncer vnode is no referenced.
5164  */
5165 static int
5166 sync_inactive(struct vop_inactive_args *ap)
5167 {
5168
5169         vgone(ap->a_vp);
5170         return (0);
5171 }
5172
5173 /*
5174  * The syncer vnode is no longer needed and is being decommissioned.
5175  *
5176  * Modifications to the worklist must be protected by sync_mtx.
5177  */
5178 static int
5179 sync_reclaim(struct vop_reclaim_args *ap)
5180 {
5181         struct vnode *vp = ap->a_vp;
5182         struct bufobj *bo;
5183
5184         bo = &vp->v_bufobj;
5185         BO_LOCK(bo);
5186         mtx_lock(&sync_mtx);
5187         if (vp->v_mount->mnt_syncer == vp)
5188                 vp->v_mount->mnt_syncer = NULL;
5189         if (bo->bo_flag & BO_ONWORKLST) {
5190                 LIST_REMOVE(bo, bo_synclist);
5191                 syncer_worklist_len--;
5192                 sync_vnode_count--;
5193                 bo->bo_flag &= ~BO_ONWORKLST;
5194         }
5195         mtx_unlock(&sync_mtx);
5196         BO_UNLOCK(bo);
5197
5198         return (0);
5199 }
5200
5201 int
5202 vn_need_pageq_flush(struct vnode *vp)
5203 {
5204         struct vm_object *obj;
5205         int need;
5206
5207         MPASS(mtx_owned(VI_MTX(vp)));
5208         need = 0;
5209         if ((obj = vp->v_object) != NULL && (vp->v_vflag & VV_NOSYNC) == 0 &&
5210             vm_object_mightbedirty(obj))
5211                 need = 1;
5212         return (need);
5213 }
5214
5215 /*
5216  * Check if vnode represents a disk device
5217  */
5218 int
5219 vn_isdisk(struct vnode *vp, int *errp)
5220 {
5221         int error;
5222
5223         if (vp->v_type != VCHR) {
5224                 error = ENOTBLK;
5225                 goto out;
5226         }
5227         error = 0;
5228         dev_lock();
5229         if (vp->v_rdev == NULL)
5230                 error = ENXIO;
5231         else if (vp->v_rdev->si_devsw == NULL)
5232                 error = ENXIO;
5233         else if (!(vp->v_rdev->si_devsw->d_flags & D_DISK))
5234                 error = ENOTBLK;
5235         dev_unlock();
5236 out:
5237         if (errp != NULL)
5238                 *errp = error;
5239         return (error == 0);
5240 }
5241
5242 /*
5243  * Common filesystem object access control check routine.  Accepts a
5244  * vnode's type, "mode", uid and gid, requested access mode, credentials,
5245  * and optional call-by-reference privused argument allowing vaccess()
5246  * to indicate to the caller whether privilege was used to satisfy the
5247  * request (obsoleted).  Returns 0 on success, or an errno on failure.
5248  */
5249 int
5250 vaccess(enum vtype type, mode_t file_mode, uid_t file_uid, gid_t file_gid,
5251     accmode_t accmode, struct ucred *cred, int *privused)
5252 {
5253         accmode_t dac_granted;
5254         accmode_t priv_granted;
5255
5256         KASSERT((accmode & ~(VEXEC | VWRITE | VREAD | VADMIN | VAPPEND)) == 0,
5257             ("invalid bit in accmode"));
5258         KASSERT((accmode & VAPPEND) == 0 || (accmode & VWRITE),
5259             ("VAPPEND without VWRITE"));
5260
5261         /*
5262          * Look for a normal, non-privileged way to access the file/directory
5263          * as requested.  If it exists, go with that.
5264          */
5265
5266         if (privused != NULL)
5267                 *privused = 0;
5268
5269         dac_granted = 0;
5270
5271         /* Check the owner. */
5272         if (cred->cr_uid == file_uid) {
5273                 dac_granted |= VADMIN;
5274                 if (file_mode & S_IXUSR)
5275                         dac_granted |= VEXEC;
5276                 if (file_mode & S_IRUSR)
5277                         dac_granted |= VREAD;
5278                 if (file_mode & S_IWUSR)
5279                         dac_granted |= (VWRITE | VAPPEND);
5280
5281                 if ((accmode & dac_granted) == accmode)
5282                         return (0);
5283
5284                 goto privcheck;
5285         }
5286
5287         /* Otherwise, check the groups (first match) */
5288         if (groupmember(file_gid, cred)) {
5289                 if (file_mode & S_IXGRP)
5290                         dac_granted |= VEXEC;
5291                 if (file_mode & S_IRGRP)
5292                         dac_granted |= VREAD;
5293                 if (file_mode & S_IWGRP)
5294                         dac_granted |= (VWRITE | VAPPEND);
5295
5296                 if ((accmode & dac_granted) == accmode)
5297                         return (0);
5298
5299                 goto privcheck;
5300         }
5301
5302         /* Otherwise, check everyone else. */
5303         if (file_mode & S_IXOTH)
5304                 dac_granted |= VEXEC;
5305         if (file_mode & S_IROTH)
5306                 dac_granted |= VREAD;
5307         if (file_mode & S_IWOTH)
5308                 dac_granted |= (VWRITE | VAPPEND);
5309         if ((accmode & dac_granted) == accmode)
5310                 return (0);
5311
5312 privcheck:
5313         /*
5314          * Build a privilege mask to determine if the set of privileges
5315          * satisfies the requirements when combined with the granted mask
5316          * from above.  For each privilege, if the privilege is required,
5317          * bitwise or the request type onto the priv_granted mask.
5318          */
5319         priv_granted = 0;
5320
5321         if (type == VDIR) {
5322                 /*
5323                  * For directories, use PRIV_VFS_LOOKUP to satisfy VEXEC
5324                  * requests, instead of PRIV_VFS_EXEC.
5325                  */
5326                 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
5327                     !priv_check_cred(cred, PRIV_VFS_LOOKUP))
5328                         priv_granted |= VEXEC;
5329         } else {
5330                 /*
5331                  * Ensure that at least one execute bit is on. Otherwise,
5332                  * a privileged user will always succeed, and we don't want
5333                  * this to happen unless the file really is executable.
5334                  */
5335                 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
5336                     (file_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0 &&
5337                     !priv_check_cred(cred, PRIV_VFS_EXEC))
5338                         priv_granted |= VEXEC;
5339         }
5340
5341         if ((accmode & VREAD) && ((dac_granted & VREAD) == 0) &&
5342             !priv_check_cred(cred, PRIV_VFS_READ))
5343                 priv_granted |= VREAD;
5344
5345         if ((accmode & VWRITE) && ((dac_granted & VWRITE) == 0) &&
5346             !priv_check_cred(cred, PRIV_VFS_WRITE))
5347                 priv_granted |= (VWRITE | VAPPEND);
5348
5349         if ((accmode & VADMIN) && ((dac_granted & VADMIN) == 0) &&
5350             !priv_check_cred(cred, PRIV_VFS_ADMIN))
5351                 priv_granted |= VADMIN;
5352
5353         if ((accmode & (priv_granted | dac_granted)) == accmode) {
5354                 /* XXX audit: privilege used */
5355                 if (privused != NULL)
5356                         *privused = 1;
5357                 return (0);
5358         }
5359
5360         return ((accmode & VADMIN) ? EPERM : EACCES);
5361 }
5362
5363 /*
5364  * Credential check based on process requesting service, and per-attribute
5365  * permissions.
5366  */
5367 int
5368 extattr_check_cred(struct vnode *vp, int attrnamespace, struct ucred *cred,
5369     struct thread *td, accmode_t accmode)
5370 {
5371
5372         /*
5373          * Kernel-invoked always succeeds.
5374          */
5375         if (cred == NOCRED)
5376                 return (0);
5377
5378         /*
5379          * Do not allow privileged processes in jail to directly manipulate
5380          * system attributes.
5381          */
5382         switch (attrnamespace) {
5383         case EXTATTR_NAMESPACE_SYSTEM:
5384                 /* Potentially should be: return (EPERM); */
5385                 return (priv_check_cred(cred, PRIV_VFS_EXTATTR_SYSTEM));
5386         case EXTATTR_NAMESPACE_USER:
5387                 return (VOP_ACCESS(vp, accmode, cred, td));
5388         default:
5389                 return (EPERM);
5390         }
5391 }
5392
5393 #ifdef DEBUG_VFS_LOCKS
5394 /*
5395  * This only exists to suppress warnings from unlocked specfs accesses.  It is
5396  * no longer ok to have an unlocked VFS.
5397  */
5398 #define IGNORE_LOCK(vp) (KERNEL_PANICKED() || (vp) == NULL ||           \
5399         (vp)->v_type == VCHR || (vp)->v_type == VBAD)
5400
5401 int vfs_badlock_ddb = 1;        /* Drop into debugger on violation. */
5402 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_ddb, CTLFLAG_RW, &vfs_badlock_ddb, 0,
5403     "Drop into debugger on lock violation");
5404
5405 int vfs_badlock_mutex = 1;      /* Check for interlock across VOPs. */
5406 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_mutex, CTLFLAG_RW, &vfs_badlock_mutex,
5407     0, "Check for interlock across VOPs");
5408
5409 int vfs_badlock_print = 1;      /* Print lock violations. */
5410 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_print, CTLFLAG_RW, &vfs_badlock_print,
5411     0, "Print lock violations");
5412
5413 int vfs_badlock_vnode = 1;      /* Print vnode details on lock violations. */
5414 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_vnode, CTLFLAG_RW, &vfs_badlock_vnode,
5415     0, "Print vnode details on lock violations");
5416
5417 #ifdef KDB
5418 int vfs_badlock_backtrace = 1;  /* Print backtrace at lock violations. */
5419 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_backtrace, CTLFLAG_RW,
5420     &vfs_badlock_backtrace, 0, "Print backtrace at lock violations");
5421 #endif
5422
5423 static void
5424 vfs_badlock(const char *msg, const char *str, struct vnode *vp)
5425 {
5426
5427 #ifdef KDB
5428         if (vfs_badlock_backtrace)
5429                 kdb_backtrace();
5430 #endif
5431         if (vfs_badlock_vnode)
5432                 vn_printf(vp, "vnode ");
5433         if (vfs_badlock_print)
5434                 printf("%s: %p %s\n", str, (void *)vp, msg);
5435         if (vfs_badlock_ddb)
5436                 kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
5437 }
5438
5439 void
5440 assert_vi_locked(struct vnode *vp, const char *str)
5441 {
5442
5443         if (vfs_badlock_mutex && !mtx_owned(VI_MTX(vp)))
5444                 vfs_badlock("interlock is not locked but should be", str, vp);
5445 }
5446
5447 void
5448 assert_vi_unlocked(struct vnode *vp, const char *str)
5449 {
5450
5451         if (vfs_badlock_mutex && mtx_owned(VI_MTX(vp)))
5452                 vfs_badlock("interlock is locked but should not be", str, vp);
5453 }
5454
5455 void
5456 assert_vop_locked(struct vnode *vp, const char *str)
5457 {
5458         int locked;
5459
5460         if (!IGNORE_LOCK(vp)) {
5461                 locked = VOP_ISLOCKED(vp);
5462                 if (locked == 0 || locked == LK_EXCLOTHER)
5463                         vfs_badlock("is not locked but should be", str, vp);
5464         }
5465 }
5466
5467 void
5468 assert_vop_unlocked(struct vnode *vp, const char *str)
5469 {
5470
5471         if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) == LK_EXCLUSIVE)
5472                 vfs_badlock("is locked but should not be", str, vp);
5473 }
5474
5475 void
5476 assert_vop_elocked(struct vnode *vp, const char *str)
5477 {
5478
5479         if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) != LK_EXCLUSIVE)
5480                 vfs_badlock("is not exclusive locked but should be", str, vp);
5481 }
5482 #endif /* DEBUG_VFS_LOCKS */
5483
5484 void
5485 vop_rename_fail(struct vop_rename_args *ap)
5486 {
5487
5488         if (ap->a_tvp != NULL)
5489                 vput(ap->a_tvp);
5490         if (ap->a_tdvp == ap->a_tvp)
5491                 vrele(ap->a_tdvp);
5492         else
5493                 vput(ap->a_tdvp);
5494         vrele(ap->a_fdvp);
5495         vrele(ap->a_fvp);
5496 }
5497
5498 void
5499 vop_rename_pre(void *ap)
5500 {
5501         struct vop_rename_args *a = ap;
5502
5503 #ifdef DEBUG_VFS_LOCKS
5504         if (a->a_tvp)
5505                 ASSERT_VI_UNLOCKED(a->a_tvp, "VOP_RENAME");
5506         ASSERT_VI_UNLOCKED(a->a_tdvp, "VOP_RENAME");
5507         ASSERT_VI_UNLOCKED(a->a_fvp, "VOP_RENAME");
5508         ASSERT_VI_UNLOCKED(a->a_fdvp, "VOP_RENAME");
5509
5510         /* Check the source (from). */
5511         if (a->a_tdvp->v_vnlock != a->a_fdvp->v_vnlock &&
5512             (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fdvp->v_vnlock))
5513                 ASSERT_VOP_UNLOCKED(a->a_fdvp, "vop_rename: fdvp locked");
5514         if (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fvp->v_vnlock)
5515                 ASSERT_VOP_UNLOCKED(a->a_fvp, "vop_rename: fvp locked");
5516
5517         /* Check the target. */
5518         if (a->a_tvp)
5519                 ASSERT_VOP_LOCKED(a->a_tvp, "vop_rename: tvp not locked");
5520         ASSERT_VOP_LOCKED(a->a_tdvp, "vop_rename: tdvp not locked");
5521 #endif
5522         /*
5523          * It may be tempting to add vn_seqc_write_begin/end calls here and
5524          * in vop_rename_post but that's not going to work out since some
5525          * filesystems relookup vnodes mid-rename. This is probably a bug.
5526          *
5527          * For now filesystems are expected to do the relevant calls after they
5528          * decide what vnodes to operate on.
5529          */
5530         if (a->a_tdvp != a->a_fdvp)
5531                 vhold(a->a_fdvp);
5532         if (a->a_tvp != a->a_fvp)
5533                 vhold(a->a_fvp);
5534         vhold(a->a_tdvp);
5535         if (a->a_tvp)
5536                 vhold(a->a_tvp);
5537 }
5538
5539 #ifdef DEBUG_VFS_LOCKS
5540 void
5541 vop_strategy_pre(void *ap)
5542 {
5543         struct vop_strategy_args *a;
5544         struct buf *bp;
5545
5546         a = ap;
5547         bp = a->a_bp;
5548
5549         /*
5550          * Cluster ops lock their component buffers but not the IO container.
5551          */
5552         if ((bp->b_flags & B_CLUSTER) != 0)
5553                 return;
5554
5555         if (!KERNEL_PANICKED() && !BUF_ISLOCKED(bp)) {
5556                 if (vfs_badlock_print)
5557                         printf(
5558                             "VOP_STRATEGY: bp is not locked but should be\n");
5559                 if (vfs_badlock_ddb)
5560                         kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
5561         }
5562 }
5563
5564 void
5565 vop_lock_pre(void *ap)
5566 {
5567         struct vop_lock1_args *a = ap;
5568
5569         if ((a->a_flags & LK_INTERLOCK) == 0)
5570                 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
5571         else
5572                 ASSERT_VI_LOCKED(a->a_vp, "VOP_LOCK");
5573 }
5574
5575 void
5576 vop_lock_post(void *ap, int rc)
5577 {
5578         struct vop_lock1_args *a = ap;
5579
5580         ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
5581         if (rc == 0 && (a->a_flags & LK_EXCLOTHER) == 0)
5582                 ASSERT_VOP_LOCKED(a->a_vp, "VOP_LOCK");
5583 }
5584
5585 void
5586 vop_unlock_pre(void *ap)
5587 {
5588         struct vop_unlock_args *a = ap;
5589
5590         ASSERT_VOP_LOCKED(a->a_vp, "VOP_UNLOCK");
5591 }
5592
5593 void
5594 vop_need_inactive_pre(void *ap)
5595 {
5596         struct vop_need_inactive_args *a = ap;
5597
5598         ASSERT_VI_LOCKED(a->a_vp, "VOP_NEED_INACTIVE");
5599 }
5600
5601 void
5602 vop_need_inactive_post(void *ap, int rc)
5603 {
5604         struct vop_need_inactive_args *a = ap;
5605
5606         ASSERT_VI_LOCKED(a->a_vp, "VOP_NEED_INACTIVE");
5607 }
5608 #endif
5609
5610 void
5611 vop_create_pre(void *ap)
5612 {
5613         struct vop_create_args *a;
5614         struct vnode *dvp;
5615
5616         a = ap;
5617         dvp = a->a_dvp;
5618         vn_seqc_write_begin(dvp);
5619 }
5620
5621 void
5622 vop_create_post(void *ap, int rc)
5623 {
5624         struct vop_create_args *a;
5625         struct vnode *dvp;
5626
5627         a = ap;
5628         dvp = a->a_dvp;
5629         vn_seqc_write_end(dvp);
5630         if (!rc)
5631                 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE);
5632 }
5633
5634 void
5635 vop_whiteout_pre(void *ap)
5636 {
5637         struct vop_whiteout_args *a;
5638         struct vnode *dvp;
5639
5640         a = ap;
5641         dvp = a->a_dvp;
5642         vn_seqc_write_begin(dvp);
5643 }
5644
5645 void
5646 vop_whiteout_post(void *ap, int rc)
5647 {
5648         struct vop_whiteout_args *a;
5649         struct vnode *dvp;
5650
5651         a = ap;
5652         dvp = a->a_dvp;
5653         vn_seqc_write_end(dvp);
5654 }
5655
5656 void
5657 vop_deleteextattr_pre(void *ap)
5658 {
5659         struct vop_deleteextattr_args *a;
5660         struct vnode *vp;
5661
5662         a = ap;
5663         vp = a->a_vp;
5664         vn_seqc_write_begin(vp);
5665 }
5666
5667 void
5668 vop_deleteextattr_post(void *ap, int rc)
5669 {
5670         struct vop_deleteextattr_args *a;
5671         struct vnode *vp;
5672
5673         a = ap;
5674         vp = a->a_vp;
5675         vn_seqc_write_end(vp);
5676         if (!rc)
5677                 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
5678 }
5679
5680 void
5681 vop_link_pre(void *ap)
5682 {
5683         struct vop_link_args *a;
5684         struct vnode *vp, *tdvp;
5685
5686         a = ap;
5687         vp = a->a_vp;
5688         tdvp = a->a_tdvp;
5689         vn_seqc_write_begin(vp);
5690         vn_seqc_write_begin(tdvp);
5691 }
5692
5693 void
5694 vop_link_post(void *ap, int rc)
5695 {
5696         struct vop_link_args *a;
5697         struct vnode *vp, *tdvp;
5698
5699         a = ap;
5700         vp = a->a_vp;
5701         tdvp = a->a_tdvp;
5702         vn_seqc_write_end(vp);
5703         vn_seqc_write_end(tdvp);
5704         if (!rc) {
5705                 VFS_KNOTE_LOCKED(vp, NOTE_LINK);
5706                 VFS_KNOTE_LOCKED(tdvp, NOTE_WRITE);
5707         }
5708 }
5709
5710 void
5711 vop_mkdir_pre(void *ap)
5712 {
5713         struct vop_mkdir_args *a;
5714         struct vnode *dvp;
5715
5716         a = ap;
5717         dvp = a->a_dvp;
5718         vn_seqc_write_begin(dvp);
5719 }
5720
5721 void
5722 vop_mkdir_post(void *ap, int rc)
5723 {
5724         struct vop_mkdir_args *a;
5725         struct vnode *dvp;
5726
5727         a = ap;
5728         dvp = a->a_dvp;
5729         vn_seqc_write_end(dvp);
5730         if (!rc)
5731                 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE | NOTE_LINK);
5732 }
5733
5734 void
5735 vop_mknod_pre(void *ap)
5736 {
5737         struct vop_mknod_args *a;
5738         struct vnode *dvp;
5739
5740         a = ap;
5741         dvp = a->a_dvp;
5742         vn_seqc_write_begin(dvp);
5743 }
5744
5745 void
5746 vop_mknod_post(void *ap, int rc)
5747 {
5748         struct vop_mknod_args *a;
5749         struct vnode *dvp;
5750
5751         a = ap;
5752         dvp = a->a_dvp;
5753         vn_seqc_write_end(dvp);
5754         if (!rc)
5755                 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE);
5756 }
5757
5758 void
5759 vop_reclaim_post(void *ap, int rc)
5760 {
5761         struct vop_reclaim_args *a;
5762         struct vnode *vp;
5763
5764         a = ap;
5765         vp = a->a_vp;
5766         ASSERT_VOP_IN_SEQC(vp);
5767         if (!rc)
5768                 VFS_KNOTE_LOCKED(vp, NOTE_REVOKE);
5769 }
5770
5771 void
5772 vop_remove_pre(void *ap)
5773 {
5774         struct vop_remove_args *a;
5775         struct vnode *dvp, *vp;
5776
5777         a = ap;
5778         dvp = a->a_dvp;
5779         vp = a->a_vp;
5780         vn_seqc_write_begin(dvp);
5781         vn_seqc_write_begin(vp);
5782 }
5783
5784 void
5785 vop_remove_post(void *ap, int rc)
5786 {
5787         struct vop_remove_args *a;
5788         struct vnode *dvp, *vp;
5789
5790         a = ap;
5791         dvp = a->a_dvp;
5792         vp = a->a_vp;
5793         vn_seqc_write_end(dvp);
5794         vn_seqc_write_end(vp);
5795         if (!rc) {
5796                 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE);
5797                 VFS_KNOTE_LOCKED(vp, NOTE_DELETE);
5798         }
5799 }
5800
5801 void
5802 vop_rename_post(void *ap, int rc)
5803 {
5804         struct vop_rename_args *a = ap;
5805         long hint;
5806
5807         if (!rc) {
5808                 hint = NOTE_WRITE;
5809                 if (a->a_fdvp == a->a_tdvp) {
5810                         if (a->a_tvp != NULL && a->a_tvp->v_type == VDIR)
5811                                 hint |= NOTE_LINK;
5812                         VFS_KNOTE_UNLOCKED(a->a_fdvp, hint);
5813                         VFS_KNOTE_UNLOCKED(a->a_tdvp, hint);
5814                 } else {
5815                         hint |= NOTE_EXTEND;
5816                         if (a->a_fvp->v_type == VDIR)
5817                                 hint |= NOTE_LINK;
5818                         VFS_KNOTE_UNLOCKED(a->a_fdvp, hint);
5819
5820                         if (a->a_fvp->v_type == VDIR && a->a_tvp != NULL &&
5821                             a->a_tvp->v_type == VDIR)
5822                                 hint &= ~NOTE_LINK;
5823                         VFS_KNOTE_UNLOCKED(a->a_tdvp, hint);
5824                 }
5825
5826                 VFS_KNOTE_UNLOCKED(a->a_fvp, NOTE_RENAME);
5827                 if (a->a_tvp)
5828                         VFS_KNOTE_UNLOCKED(a->a_tvp, NOTE_DELETE);
5829         }
5830         if (a->a_tdvp != a->a_fdvp)
5831                 vdrop(a->a_fdvp);
5832         if (a->a_tvp != a->a_fvp)
5833                 vdrop(a->a_fvp);
5834         vdrop(a->a_tdvp);
5835         if (a->a_tvp)
5836                 vdrop(a->a_tvp);
5837 }
5838
5839 void
5840 vop_rmdir_pre(void *ap)
5841 {
5842         struct vop_rmdir_args *a;
5843         struct vnode *dvp, *vp;
5844
5845         a = ap;
5846         dvp = a->a_dvp;
5847         vp = a->a_vp;
5848         vn_seqc_write_begin(dvp);
5849         vn_seqc_write_begin(vp);
5850 }
5851
5852 void
5853 vop_rmdir_post(void *ap, int rc)
5854 {
5855         struct vop_rmdir_args *a;
5856         struct vnode *dvp, *vp;
5857
5858         a = ap;
5859         dvp = a->a_dvp;
5860         vp = a->a_vp;
5861         vn_seqc_write_end(dvp);
5862         vn_seqc_write_end(vp);
5863         if (!rc) {
5864                 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE | NOTE_LINK);
5865                 VFS_KNOTE_LOCKED(vp, NOTE_DELETE);
5866         }
5867 }
5868
5869 void
5870 vop_setattr_pre(void *ap)
5871 {
5872         struct vop_setattr_args *a;
5873         struct vnode *vp;
5874
5875         a = ap;
5876         vp = a->a_vp;
5877         vn_seqc_write_begin(vp);
5878 }
5879
5880 void
5881 vop_setattr_post(void *ap, int rc)
5882 {
5883         struct vop_setattr_args *a;
5884         struct vnode *vp;
5885
5886         a = ap;
5887         vp = a->a_vp;
5888         vn_seqc_write_end(vp);
5889         if (!rc)
5890                 VFS_KNOTE_LOCKED(vp, NOTE_ATTRIB);
5891 }
5892
5893 void
5894 vop_setacl_pre(void *ap)
5895 {
5896         struct vop_setacl_args *a;
5897         struct vnode *vp;
5898
5899         a = ap;
5900         vp = a->a_vp;
5901         vn_seqc_write_begin(vp);
5902 }
5903
5904 void
5905 vop_setacl_post(void *ap, int rc __unused)
5906 {
5907         struct vop_setacl_args *a;
5908         struct vnode *vp;
5909
5910         a = ap;
5911         vp = a->a_vp;
5912         vn_seqc_write_end(vp);
5913 }
5914
5915 void
5916 vop_setextattr_pre(void *ap)
5917 {
5918         struct vop_setextattr_args *a;
5919         struct vnode *vp;
5920
5921         a = ap;
5922         vp = a->a_vp;
5923         vn_seqc_write_begin(vp);
5924 }
5925
5926 void
5927 vop_setextattr_post(void *ap, int rc)
5928 {
5929         struct vop_setextattr_args *a;
5930         struct vnode *vp;
5931
5932         a = ap;
5933         vp = a->a_vp;
5934         vn_seqc_write_end(vp);
5935         if (!rc)
5936                 VFS_KNOTE_LOCKED(vp, NOTE_ATTRIB);
5937 }
5938
5939 void
5940 vop_symlink_pre(void *ap)
5941 {
5942         struct vop_symlink_args *a;
5943         struct vnode *dvp;
5944
5945         a = ap;
5946         dvp = a->a_dvp;
5947         vn_seqc_write_begin(dvp);
5948 }
5949
5950 void
5951 vop_symlink_post(void *ap, int rc)
5952 {
5953         struct vop_symlink_args *a;
5954         struct vnode *dvp;
5955
5956         a = ap;
5957         dvp = a->a_dvp;
5958         vn_seqc_write_end(dvp);
5959         if (!rc)
5960                 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE);
5961 }
5962
5963 void
5964 vop_open_post(void *ap, int rc)
5965 {
5966         struct vop_open_args *a = ap;
5967
5968         if (!rc)
5969                 VFS_KNOTE_LOCKED(a->a_vp, NOTE_OPEN);
5970 }
5971
5972 void
5973 vop_close_post(void *ap, int rc)
5974 {
5975         struct vop_close_args *a = ap;
5976
5977         if (!rc && (a->a_cred != NOCRED || /* filter out revokes */
5978             !VN_IS_DOOMED(a->a_vp))) {
5979                 VFS_KNOTE_LOCKED(a->a_vp, (a->a_fflag & FWRITE) != 0 ?
5980                     NOTE_CLOSE_WRITE : NOTE_CLOSE);
5981         }
5982 }
5983
5984 void
5985 vop_read_post(void *ap, int rc)
5986 {
5987         struct vop_read_args *a = ap;
5988
5989         if (!rc)
5990                 VFS_KNOTE_LOCKED(a->a_vp, NOTE_READ);
5991 }
5992
5993 void
5994 vop_readdir_post(void *ap, int rc)
5995 {
5996         struct vop_readdir_args *a = ap;
5997
5998         if (!rc)
5999                 VFS_KNOTE_LOCKED(a->a_vp, NOTE_READ);
6000 }
6001
6002 static struct knlist fs_knlist;
6003
6004 static void
6005 vfs_event_init(void *arg)
6006 {
6007         knlist_init_mtx(&fs_knlist, NULL);
6008 }
6009 /* XXX - correct order? */
6010 SYSINIT(vfs_knlist, SI_SUB_VFS, SI_ORDER_ANY, vfs_event_init, NULL);
6011
6012 void
6013 vfs_event_signal(fsid_t *fsid, uint32_t event, intptr_t data __unused)
6014 {
6015
6016         KNOTE_UNLOCKED(&fs_knlist, event);
6017 }
6018
6019 static int      filt_fsattach(struct knote *kn);
6020 static void     filt_fsdetach(struct knote *kn);
6021 static int      filt_fsevent(struct knote *kn, long hint);
6022
6023 struct filterops fs_filtops = {
6024         .f_isfd = 0,
6025         .f_attach = filt_fsattach,
6026         .f_detach = filt_fsdetach,
6027         .f_event = filt_fsevent
6028 };
6029
6030 static int
6031 filt_fsattach(struct knote *kn)
6032 {
6033
6034         kn->kn_flags |= EV_CLEAR;
6035         knlist_add(&fs_knlist, kn, 0);
6036         return (0);
6037 }
6038
6039 static void
6040 filt_fsdetach(struct knote *kn)
6041 {
6042
6043         knlist_remove(&fs_knlist, kn, 0);
6044 }
6045
6046 static int
6047 filt_fsevent(struct knote *kn, long hint)
6048 {
6049
6050         kn->kn_fflags |= hint;
6051         return (kn->kn_fflags != 0);
6052 }
6053
6054 static int
6055 sysctl_vfs_ctl(SYSCTL_HANDLER_ARGS)
6056 {
6057         struct vfsidctl vc;
6058         int error;
6059         struct mount *mp;
6060
6061         error = SYSCTL_IN(req, &vc, sizeof(vc));
6062         if (error)
6063                 return (error);
6064         if (vc.vc_vers != VFS_CTL_VERS1)
6065                 return (EINVAL);
6066         mp = vfs_getvfs(&vc.vc_fsid);
6067         if (mp == NULL)
6068                 return (ENOENT);
6069         /* ensure that a specific sysctl goes to the right filesystem. */
6070         if (strcmp(vc.vc_fstypename, "*") != 0 &&
6071             strcmp(vc.vc_fstypename, mp->mnt_vfc->vfc_name) != 0) {
6072                 vfs_rel(mp);
6073                 return (EINVAL);
6074         }
6075         VCTLTOREQ(&vc, req);
6076         error = VFS_SYSCTL(mp, vc.vc_op, req);
6077         vfs_rel(mp);
6078         return (error);
6079 }
6080
6081 SYSCTL_PROC(_vfs, OID_AUTO, ctl, CTLTYPE_OPAQUE | CTLFLAG_MPSAFE | CTLFLAG_WR,
6082     NULL, 0, sysctl_vfs_ctl, "",
6083     "Sysctl by fsid");
6084
6085 /*
6086  * Function to initialize a va_filerev field sensibly.
6087  * XXX: Wouldn't a random number make a lot more sense ??
6088  */
6089 u_quad_t
6090 init_va_filerev(void)
6091 {
6092         struct bintime bt;
6093
6094         getbinuptime(&bt);
6095         return (((u_quad_t)bt.sec << 32LL) | (bt.frac >> 32LL));
6096 }
6097
6098 static int      filt_vfsread(struct knote *kn, long hint);
6099 static int      filt_vfswrite(struct knote *kn, long hint);
6100 static int      filt_vfsvnode(struct knote *kn, long hint);
6101 static void     filt_vfsdetach(struct knote *kn);
6102 static struct filterops vfsread_filtops = {
6103         .f_isfd = 1,
6104         .f_detach = filt_vfsdetach,
6105         .f_event = filt_vfsread
6106 };
6107 static struct filterops vfswrite_filtops = {
6108         .f_isfd = 1,
6109         .f_detach = filt_vfsdetach,
6110         .f_event = filt_vfswrite
6111 };
6112 static struct filterops vfsvnode_filtops = {
6113         .f_isfd = 1,
6114         .f_detach = filt_vfsdetach,
6115         .f_event = filt_vfsvnode
6116 };
6117
6118 static void
6119 vfs_knllock(void *arg)
6120 {
6121         struct vnode *vp = arg;
6122
6123         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
6124 }
6125
6126 static void
6127 vfs_knlunlock(void *arg)
6128 {
6129         struct vnode *vp = arg;
6130
6131         VOP_UNLOCK(vp);
6132 }
6133
6134 static void
6135 vfs_knl_assert_locked(void *arg)
6136 {
6137 #ifdef DEBUG_VFS_LOCKS
6138         struct vnode *vp = arg;
6139
6140         ASSERT_VOP_LOCKED(vp, "vfs_knl_assert_locked");
6141 #endif
6142 }
6143
6144 static void
6145 vfs_knl_assert_unlocked(void *arg)
6146 {
6147 #ifdef DEBUG_VFS_LOCKS
6148         struct vnode *vp = arg;
6149
6150         ASSERT_VOP_UNLOCKED(vp, "vfs_knl_assert_unlocked");
6151 #endif
6152 }
6153
6154 int
6155 vfs_kqfilter(struct vop_kqfilter_args *ap)
6156 {
6157         struct vnode *vp = ap->a_vp;
6158         struct knote *kn = ap->a_kn;
6159         struct knlist *knl;
6160
6161         switch (kn->kn_filter) {
6162         case EVFILT_READ:
6163                 kn->kn_fop = &vfsread_filtops;
6164                 break;
6165         case EVFILT_WRITE:
6166                 kn->kn_fop = &vfswrite_filtops;
6167                 break;
6168         case EVFILT_VNODE:
6169                 kn->kn_fop = &vfsvnode_filtops;
6170                 break;
6171         default:
6172                 return (EINVAL);
6173         }
6174
6175         kn->kn_hook = (caddr_t)vp;
6176
6177         v_addpollinfo(vp);
6178         if (vp->v_pollinfo == NULL)
6179                 return (ENOMEM);
6180         knl = &vp->v_pollinfo->vpi_selinfo.si_note;
6181         vhold(vp);
6182         knlist_add(knl, kn, 0);
6183
6184         return (0);
6185 }
6186
6187 /*
6188  * Detach knote from vnode
6189  */
6190 static void
6191 filt_vfsdetach(struct knote *kn)
6192 {
6193         struct vnode *vp = (struct vnode *)kn->kn_hook;
6194
6195         KASSERT(vp->v_pollinfo != NULL, ("Missing v_pollinfo"));
6196         knlist_remove(&vp->v_pollinfo->vpi_selinfo.si_note, kn, 0);
6197         vdrop(vp);
6198 }
6199
6200 /*ARGSUSED*/
6201 static int
6202 filt_vfsread(struct knote *kn, long hint)
6203 {
6204         struct vnode *vp = (struct vnode *)kn->kn_hook;
6205         struct vattr va;
6206         int res;
6207
6208         /*
6209          * filesystem is gone, so set the EOF flag and schedule
6210          * the knote for deletion.
6211          */
6212         if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD)) {
6213                 VI_LOCK(vp);
6214                 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
6215                 VI_UNLOCK(vp);
6216                 return (1);
6217         }
6218
6219         if (VOP_GETATTR(vp, &va, curthread->td_ucred))
6220                 return (0);
6221
6222         VI_LOCK(vp);
6223         kn->kn_data = va.va_size - kn->kn_fp->f_offset;
6224         res = (kn->kn_sfflags & NOTE_FILE_POLL) != 0 || kn->kn_data != 0;
6225         VI_UNLOCK(vp);
6226         return (res);
6227 }
6228
6229 /*ARGSUSED*/
6230 static int
6231 filt_vfswrite(struct knote *kn, long hint)
6232 {
6233         struct vnode *vp = (struct vnode *)kn->kn_hook;
6234
6235         VI_LOCK(vp);
6236
6237         /*
6238          * filesystem is gone, so set the EOF flag and schedule
6239          * the knote for deletion.
6240          */
6241         if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD))
6242                 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
6243
6244         kn->kn_data = 0;
6245         VI_UNLOCK(vp);
6246         return (1);
6247 }
6248
6249 static int
6250 filt_vfsvnode(struct knote *kn, long hint)
6251 {
6252         struct vnode *vp = (struct vnode *)kn->kn_hook;
6253         int res;
6254
6255         VI_LOCK(vp);
6256         if (kn->kn_sfflags & hint)
6257                 kn->kn_fflags |= hint;
6258         if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD)) {
6259                 kn->kn_flags |= EV_EOF;
6260                 VI_UNLOCK(vp);
6261                 return (1);
6262         }
6263         res = (kn->kn_fflags != 0);
6264         VI_UNLOCK(vp);
6265         return (res);
6266 }
6267
6268 /*
6269  * Returns whether the directory is empty or not.
6270  * If it is empty, the return value is 0; otherwise
6271  * the return value is an error value (which may
6272  * be ENOTEMPTY).
6273  */
6274 int
6275 vfs_emptydir(struct vnode *vp)
6276 {
6277         struct uio uio;
6278         struct iovec iov;
6279         struct dirent *dirent, *dp, *endp;
6280         int error, eof;
6281
6282         error = 0;
6283         eof = 0;
6284
6285         ASSERT_VOP_LOCKED(vp, "vfs_emptydir");
6286
6287         dirent = malloc(sizeof(struct dirent), M_TEMP, M_WAITOK);
6288         iov.iov_base = dirent;
6289         iov.iov_len = sizeof(struct dirent);
6290
6291         uio.uio_iov = &iov;
6292         uio.uio_iovcnt = 1;
6293         uio.uio_offset = 0;
6294         uio.uio_resid = sizeof(struct dirent);
6295         uio.uio_segflg = UIO_SYSSPACE;
6296         uio.uio_rw = UIO_READ;
6297         uio.uio_td = curthread;
6298
6299         while (eof == 0 && error == 0) {
6300                 error = VOP_READDIR(vp, &uio, curthread->td_ucred, &eof,
6301                     NULL, NULL);
6302                 if (error != 0)
6303                         break;
6304                 endp = (void *)((uint8_t *)dirent +
6305                     sizeof(struct dirent) - uio.uio_resid);
6306                 for (dp = dirent; dp < endp;
6307                      dp = (void *)((uint8_t *)dp + GENERIC_DIRSIZ(dp))) {
6308                         if (dp->d_type == DT_WHT)
6309                                 continue;
6310                         if (dp->d_namlen == 0)
6311                                 continue;
6312                         if (dp->d_type != DT_DIR &&
6313                             dp->d_type != DT_UNKNOWN) {
6314                                 error = ENOTEMPTY;
6315                                 break;
6316                         }
6317                         if (dp->d_namlen > 2) {
6318                                 error = ENOTEMPTY;
6319                                 break;
6320                         }
6321                         if (dp->d_namlen == 1 &&
6322                             dp->d_name[0] != '.') {
6323                                 error = ENOTEMPTY;
6324                                 break;
6325                         }
6326                         if (dp->d_namlen == 2 &&
6327                             dp->d_name[1] != '.') {
6328                                 error = ENOTEMPTY;
6329                                 break;
6330                         }
6331                         uio.uio_resid = sizeof(struct dirent);
6332                 }
6333         }
6334         free(dirent, M_TEMP);
6335         return (error);
6336 }
6337
6338 int
6339 vfs_read_dirent(struct vop_readdir_args *ap, struct dirent *dp, off_t off)
6340 {
6341         int error;
6342
6343         if (dp->d_reclen > ap->a_uio->uio_resid)
6344                 return (ENAMETOOLONG);
6345         error = uiomove(dp, dp->d_reclen, ap->a_uio);
6346         if (error) {
6347                 if (ap->a_ncookies != NULL) {
6348                         if (ap->a_cookies != NULL)
6349                                 free(ap->a_cookies, M_TEMP);
6350                         ap->a_cookies = NULL;
6351                         *ap->a_ncookies = 0;
6352                 }
6353                 return (error);
6354         }
6355         if (ap->a_ncookies == NULL)
6356                 return (0);
6357
6358         KASSERT(ap->a_cookies,
6359             ("NULL ap->a_cookies value with non-NULL ap->a_ncookies!"));
6360
6361         *ap->a_cookies = realloc(*ap->a_cookies,
6362             (*ap->a_ncookies + 1) * sizeof(u_long), M_TEMP, M_WAITOK | M_ZERO);
6363         (*ap->a_cookies)[*ap->a_ncookies] = off;
6364         *ap->a_ncookies += 1;
6365         return (0);
6366 }
6367
6368 /*
6369  * The purpose of this routine is to remove granularity from accmode_t,
6370  * reducing it into standard unix access bits - VEXEC, VREAD, VWRITE,
6371  * VADMIN and VAPPEND.
6372  *
6373  * If it returns 0, the caller is supposed to continue with the usual
6374  * access checks using 'accmode' as modified by this routine.  If it
6375  * returns nonzero value, the caller is supposed to return that value
6376  * as errno.
6377  *
6378  * Note that after this routine runs, accmode may be zero.
6379  */
6380 int
6381 vfs_unixify_accmode(accmode_t *accmode)
6382 {
6383         /*
6384          * There is no way to specify explicit "deny" rule using
6385          * file mode or POSIX.1e ACLs.
6386          */
6387         if (*accmode & VEXPLICIT_DENY) {
6388                 *accmode = 0;
6389                 return (0);
6390         }
6391
6392         /*
6393          * None of these can be translated into usual access bits.
6394          * Also, the common case for NFSv4 ACLs is to not contain
6395          * either of these bits. Caller should check for VWRITE
6396          * on the containing directory instead.
6397          */
6398         if (*accmode & (VDELETE_CHILD | VDELETE))
6399                 return (EPERM);
6400
6401         if (*accmode & VADMIN_PERMS) {
6402                 *accmode &= ~VADMIN_PERMS;
6403                 *accmode |= VADMIN;
6404         }
6405
6406         /*
6407          * There is no way to deny VREAD_ATTRIBUTES, VREAD_ACL
6408          * or VSYNCHRONIZE using file mode or POSIX.1e ACL.
6409          */
6410         *accmode &= ~(VSTAT_PERMS | VSYNCHRONIZE);
6411
6412         return (0);
6413 }
6414
6415 /*
6416  * Clear out a doomed vnode (if any) and replace it with a new one as long
6417  * as the fs is not being unmounted. Return the root vnode to the caller.
6418  */
6419 static int __noinline
6420 vfs_cache_root_fallback(struct mount *mp, int flags, struct vnode **vpp)
6421 {
6422         struct vnode *vp;
6423         int error;
6424
6425 restart:
6426         if (mp->mnt_rootvnode != NULL) {
6427                 MNT_ILOCK(mp);
6428                 vp = mp->mnt_rootvnode;
6429                 if (vp != NULL) {
6430                         if (!VN_IS_DOOMED(vp)) {
6431                                 vrefact(vp);
6432                                 MNT_IUNLOCK(mp);
6433                                 error = vn_lock(vp, flags);
6434                                 if (error == 0) {
6435                                         *vpp = vp;
6436                                         return (0);
6437                                 }
6438                                 vrele(vp);
6439                                 goto restart;
6440                         }
6441                         /*
6442                          * Clear the old one.
6443                          */
6444                         mp->mnt_rootvnode = NULL;
6445                 }
6446                 MNT_IUNLOCK(mp);
6447                 if (vp != NULL) {
6448                         vfs_op_barrier_wait(mp);
6449                         vrele(vp);
6450                 }
6451         }
6452         error = VFS_CACHEDROOT(mp, flags, vpp);
6453         if (error != 0)
6454                 return (error);
6455         if (mp->mnt_vfs_ops == 0) {
6456                 MNT_ILOCK(mp);
6457                 if (mp->mnt_vfs_ops != 0) {
6458                         MNT_IUNLOCK(mp);
6459                         return (0);
6460                 }
6461                 if (mp->mnt_rootvnode == NULL) {
6462                         vrefact(*vpp);
6463                         mp->mnt_rootvnode = *vpp;
6464                 } else {
6465                         if (mp->mnt_rootvnode != *vpp) {
6466                                 if (!VN_IS_DOOMED(mp->mnt_rootvnode)) {
6467                                         panic("%s: mismatch between vnode returned "
6468                                             " by VFS_CACHEDROOT and the one cached "
6469                                             " (%p != %p)",
6470                                             __func__, *vpp, mp->mnt_rootvnode);
6471                                 }
6472                         }
6473                 }
6474                 MNT_IUNLOCK(mp);
6475         }
6476         return (0);
6477 }
6478
6479 int
6480 vfs_cache_root(struct mount *mp, int flags, struct vnode **vpp)
6481 {
6482         struct vnode *vp;
6483         int error;
6484
6485         if (!vfs_op_thread_enter(mp))
6486                 return (vfs_cache_root_fallback(mp, flags, vpp));
6487         vp = atomic_load_ptr(&mp->mnt_rootvnode);
6488         if (vp == NULL || VN_IS_DOOMED(vp)) {
6489                 vfs_op_thread_exit(mp);
6490                 return (vfs_cache_root_fallback(mp, flags, vpp));
6491         }
6492         vrefact(vp);
6493         vfs_op_thread_exit(mp);
6494         error = vn_lock(vp, flags);
6495         if (error != 0) {
6496                 vrele(vp);
6497                 return (vfs_cache_root_fallback(mp, flags, vpp));
6498         }
6499         *vpp = vp;
6500         return (0);
6501 }
6502
6503 struct vnode *
6504 vfs_cache_root_clear(struct mount *mp)
6505 {
6506         struct vnode *vp;
6507
6508         /*
6509          * ops > 0 guarantees there is nobody who can see this vnode
6510          */
6511         MPASS(mp->mnt_vfs_ops > 0);
6512         vp = mp->mnt_rootvnode;
6513         if (vp != NULL)
6514                 vn_seqc_write_begin(vp);
6515         mp->mnt_rootvnode = NULL;
6516         return (vp);
6517 }
6518
6519 void
6520 vfs_cache_root_set(struct mount *mp, struct vnode *vp)
6521 {
6522
6523         MPASS(mp->mnt_vfs_ops > 0);
6524         vrefact(vp);
6525         mp->mnt_rootvnode = vp;
6526 }
6527
6528 /*
6529  * These are helper functions for filesystems to traverse all
6530  * their vnodes.  See MNT_VNODE_FOREACH_ALL() in sys/mount.h.
6531  *
6532  * This interface replaces MNT_VNODE_FOREACH.
6533  */
6534
6535 struct vnode *
6536 __mnt_vnode_next_all(struct vnode **mvp, struct mount *mp)
6537 {
6538         struct vnode *vp;
6539
6540         if (should_yield())
6541                 kern_yield(PRI_USER);
6542         MNT_ILOCK(mp);
6543         KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6544         for (vp = TAILQ_NEXT(*mvp, v_nmntvnodes); vp != NULL;
6545             vp = TAILQ_NEXT(vp, v_nmntvnodes)) {
6546                 /* Allow a racy peek at VIRF_DOOMED to save a lock acquisition. */
6547                 if (vp->v_type == VMARKER || VN_IS_DOOMED(vp))
6548                         continue;
6549                 VI_LOCK(vp);
6550                 if (VN_IS_DOOMED(vp)) {
6551                         VI_UNLOCK(vp);
6552                         continue;
6553                 }
6554                 break;
6555         }
6556         if (vp == NULL) {
6557                 __mnt_vnode_markerfree_all(mvp, mp);
6558                 /* MNT_IUNLOCK(mp); -- done in above function */
6559                 mtx_assert(MNT_MTX(mp), MA_NOTOWNED);
6560                 return (NULL);
6561         }
6562         TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
6563         TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
6564         MNT_IUNLOCK(mp);
6565         return (vp);
6566 }
6567
6568 struct vnode *
6569 __mnt_vnode_first_all(struct vnode **mvp, struct mount *mp)
6570 {
6571         struct vnode *vp;
6572
6573         *mvp = vn_alloc_marker(mp);
6574         MNT_ILOCK(mp);
6575         MNT_REF(mp);
6576
6577         TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
6578                 /* Allow a racy peek at VIRF_DOOMED to save a lock acquisition. */
6579                 if (vp->v_type == VMARKER || VN_IS_DOOMED(vp))
6580                         continue;
6581                 VI_LOCK(vp);
6582                 if (VN_IS_DOOMED(vp)) {
6583                         VI_UNLOCK(vp);
6584                         continue;
6585                 }
6586                 break;
6587         }
6588         if (vp == NULL) {
6589                 MNT_REL(mp);
6590                 MNT_IUNLOCK(mp);
6591                 vn_free_marker(*mvp);
6592                 *mvp = NULL;
6593                 return (NULL);
6594         }
6595         TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
6596         MNT_IUNLOCK(mp);
6597         return (vp);
6598 }
6599
6600 void
6601 __mnt_vnode_markerfree_all(struct vnode **mvp, struct mount *mp)
6602 {
6603
6604         if (*mvp == NULL) {
6605                 MNT_IUNLOCK(mp);
6606                 return;
6607         }
6608
6609         mtx_assert(MNT_MTX(mp), MA_OWNED);
6610
6611         KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6612         TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
6613         MNT_REL(mp);
6614         MNT_IUNLOCK(mp);
6615         vn_free_marker(*mvp);
6616         *mvp = NULL;
6617 }
6618
6619 /*
6620  * These are helper functions for filesystems to traverse their
6621  * lazy vnodes.  See MNT_VNODE_FOREACH_LAZY() in sys/mount.h
6622  */
6623 static void
6624 mnt_vnode_markerfree_lazy(struct vnode **mvp, struct mount *mp)
6625 {
6626
6627         KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6628
6629         MNT_ILOCK(mp);
6630         MNT_REL(mp);
6631         MNT_IUNLOCK(mp);
6632         vn_free_marker(*mvp);
6633         *mvp = NULL;
6634 }
6635
6636 /*
6637  * Relock the mp mount vnode list lock with the vp vnode interlock in the
6638  * conventional lock order during mnt_vnode_next_lazy iteration.
6639  *
6640  * On entry, the mount vnode list lock is held and the vnode interlock is not.
6641  * The list lock is dropped and reacquired.  On success, both locks are held.
6642  * On failure, the mount vnode list lock is held but the vnode interlock is
6643  * not, and the procedure may have yielded.
6644  */
6645 static bool
6646 mnt_vnode_next_lazy_relock(struct vnode *mvp, struct mount *mp,
6647     struct vnode *vp)
6648 {
6649
6650         VNASSERT(mvp->v_mount == mp && mvp->v_type == VMARKER &&
6651             TAILQ_NEXT(mvp, v_lazylist) != NULL, mvp,
6652             ("%s: bad marker", __func__));
6653         VNASSERT(vp->v_mount == mp && vp->v_type != VMARKER, vp,
6654             ("%s: inappropriate vnode", __func__));
6655         ASSERT_VI_UNLOCKED(vp, __func__);
6656         mtx_assert(&mp->mnt_listmtx, MA_OWNED);
6657
6658         TAILQ_REMOVE(&mp->mnt_lazyvnodelist, mvp, v_lazylist);
6659         TAILQ_INSERT_BEFORE(vp, mvp, v_lazylist);
6660
6661         /*
6662          * Note we may be racing against vdrop which transitioned the hold
6663          * count to 0 and now waits for the ->mnt_listmtx lock. This is fine,
6664          * if we are the only user after we get the interlock we will just
6665          * vdrop.
6666          */
6667         vhold(vp);
6668         mtx_unlock(&mp->mnt_listmtx);
6669         VI_LOCK(vp);
6670         if (VN_IS_DOOMED(vp)) {
6671                 VNPASS((vp->v_mflag & VMP_LAZYLIST) == 0, vp);
6672                 goto out_lost;
6673         }
6674         VNPASS(vp->v_mflag & VMP_LAZYLIST, vp);
6675         /*
6676          * There is nothing to do if we are the last user.
6677          */
6678         if (!refcount_release_if_not_last(&vp->v_holdcnt))
6679                 goto out_lost;
6680         mtx_lock(&mp->mnt_listmtx);
6681         return (true);
6682 out_lost:
6683         vdropl(vp);
6684         maybe_yield();
6685         mtx_lock(&mp->mnt_listmtx);
6686         return (false);
6687 }
6688
6689 static struct vnode *
6690 mnt_vnode_next_lazy(struct vnode **mvp, struct mount *mp, mnt_lazy_cb_t *cb,
6691     void *cbarg)
6692 {
6693         struct vnode *vp;
6694
6695         mtx_assert(&mp->mnt_listmtx, MA_OWNED);
6696         KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6697 restart:
6698         vp = TAILQ_NEXT(*mvp, v_lazylist);
6699         while (vp != NULL) {
6700                 if (vp->v_type == VMARKER) {
6701                         vp = TAILQ_NEXT(vp, v_lazylist);
6702                         continue;
6703                 }
6704                 /*
6705                  * See if we want to process the vnode. Note we may encounter a
6706                  * long string of vnodes we don't care about and hog the list
6707                  * as a result. Check for it and requeue the marker.
6708                  */
6709                 VNPASS(!VN_IS_DOOMED(vp), vp);
6710                 if (!cb(vp, cbarg)) {
6711                         if (!should_yield()) {
6712                                 vp = TAILQ_NEXT(vp, v_lazylist);
6713                                 continue;
6714                         }
6715                         TAILQ_REMOVE(&mp->mnt_lazyvnodelist, *mvp,
6716                             v_lazylist);
6717                         TAILQ_INSERT_AFTER(&mp->mnt_lazyvnodelist, vp, *mvp,
6718                             v_lazylist);
6719                         mtx_unlock(&mp->mnt_listmtx);
6720                         kern_yield(PRI_USER);
6721                         mtx_lock(&mp->mnt_listmtx);
6722                         goto restart;
6723                 }
6724                 /*
6725                  * Try-lock because this is the wrong lock order.
6726                  */
6727                 if (!VI_TRYLOCK(vp) &&
6728                     !mnt_vnode_next_lazy_relock(*mvp, mp, vp))
6729                         goto restart;
6730                 KASSERT(vp->v_type != VMARKER, ("locked marker %p", vp));
6731                 KASSERT(vp->v_mount == mp || vp->v_mount == NULL,
6732                     ("alien vnode on the lazy list %p %p", vp, mp));
6733                 VNPASS(vp->v_mount == mp, vp);
6734                 VNPASS(!VN_IS_DOOMED(vp), vp);
6735                 break;
6736         }
6737         TAILQ_REMOVE(&mp->mnt_lazyvnodelist, *mvp, v_lazylist);
6738
6739         /* Check if we are done */
6740         if (vp == NULL) {
6741                 mtx_unlock(&mp->mnt_listmtx);
6742                 mnt_vnode_markerfree_lazy(mvp, mp);
6743                 return (NULL);
6744         }
6745         TAILQ_INSERT_AFTER(&mp->mnt_lazyvnodelist, vp, *mvp, v_lazylist);
6746         mtx_unlock(&mp->mnt_listmtx);
6747         ASSERT_VI_LOCKED(vp, "lazy iter");
6748         return (vp);
6749 }
6750
6751 struct vnode *
6752 __mnt_vnode_next_lazy(struct vnode **mvp, struct mount *mp, mnt_lazy_cb_t *cb,
6753     void *cbarg)
6754 {
6755
6756         if (should_yield())
6757                 kern_yield(PRI_USER);
6758         mtx_lock(&mp->mnt_listmtx);
6759         return (mnt_vnode_next_lazy(mvp, mp, cb, cbarg));
6760 }
6761
6762 struct vnode *
6763 __mnt_vnode_first_lazy(struct vnode **mvp, struct mount *mp, mnt_lazy_cb_t *cb,
6764     void *cbarg)
6765 {
6766         struct vnode *vp;
6767
6768         if (TAILQ_EMPTY(&mp->mnt_lazyvnodelist))
6769                 return (NULL);
6770
6771         *mvp = vn_alloc_marker(mp);
6772         MNT_ILOCK(mp);
6773         MNT_REF(mp);
6774         MNT_IUNLOCK(mp);
6775
6776         mtx_lock(&mp->mnt_listmtx);
6777         vp = TAILQ_FIRST(&mp->mnt_lazyvnodelist);
6778         if (vp == NULL) {
6779                 mtx_unlock(&mp->mnt_listmtx);
6780                 mnt_vnode_markerfree_lazy(mvp, mp);
6781                 return (NULL);
6782         }
6783         TAILQ_INSERT_BEFORE(vp, *mvp, v_lazylist);
6784         return (mnt_vnode_next_lazy(mvp, mp, cb, cbarg));
6785 }
6786
6787 void
6788 __mnt_vnode_markerfree_lazy(struct vnode **mvp, struct mount *mp)
6789 {
6790
6791         if (*mvp == NULL)
6792                 return;
6793
6794         mtx_lock(&mp->mnt_listmtx);
6795         TAILQ_REMOVE(&mp->mnt_lazyvnodelist, *mvp, v_lazylist);
6796         mtx_unlock(&mp->mnt_listmtx);
6797         mnt_vnode_markerfree_lazy(mvp, mp);
6798 }
6799
6800 int
6801 vn_dir_check_exec(struct vnode *vp, struct componentname *cnp)
6802 {
6803
6804         if ((cnp->cn_flags & NOEXECCHECK) != 0) {
6805                 cnp->cn_flags &= ~NOEXECCHECK;
6806                 return (0);
6807         }
6808
6809         return (VOP_ACCESS(vp, VEXEC, cnp->cn_cred, cnp->cn_thread));
6810 }
6811
6812 void
6813 vn_seqc_write_begin_locked(struct vnode *vp)
6814 {
6815
6816         ASSERT_VI_LOCKED(vp, __func__);
6817         VNPASS(vp->v_holdcnt > 0, vp);
6818         VNPASS(vp->v_seqc_users >= 0, vp);
6819         vp->v_seqc_users++;
6820         if (vp->v_seqc_users == 1)
6821                 seqc_sleepable_write_begin(&vp->v_seqc);
6822 }
6823
6824 void
6825 vn_seqc_write_begin(struct vnode *vp)
6826 {
6827
6828         VI_LOCK(vp);
6829         vn_seqc_write_begin_locked(vp);
6830         VI_UNLOCK(vp);
6831 }
6832
6833 void
6834 vn_seqc_write_end_locked(struct vnode *vp)
6835 {
6836
6837         ASSERT_VI_LOCKED(vp, __func__);
6838         VNPASS(vp->v_seqc_users > 0, vp);
6839         vp->v_seqc_users--;
6840         if (vp->v_seqc_users == 0)
6841                 seqc_sleepable_write_end(&vp->v_seqc);
6842 }
6843
6844 void
6845 vn_seqc_write_end(struct vnode *vp)
6846 {
6847
6848         VI_LOCK(vp);
6849         vn_seqc_write_end_locked(vp);
6850         VI_UNLOCK(vp);
6851 }