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