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