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