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