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