]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/vfs_subr.c
VFS: Remove VV_READLINK flag
[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         flags = vp->v_vflag & ~(VV_ROOT | VV_ISTTY | VV_NOSYNC | VV_ETERNALDEV |
4267             VV_CACHEDLABEL | VV_VMSIZEVNLOCK | VV_COPYONWRITE | VV_SYSTEM |
4268             VV_PROCDEP | VV_NOKNOTE | VV_DELETED | VV_MD | VV_FORCEINSMQ);
4269         if (flags != 0) {
4270                 snprintf(buf2, sizeof(buf2), "|VV(0x%lx)", flags);
4271                 strlcat(buf, buf2, sizeof(buf));
4272         }
4273         if (vp->v_iflag & VI_TEXT_REF)
4274                 strlcat(buf, "|VI_TEXT_REF", sizeof(buf));
4275         if (vp->v_iflag & VI_MOUNT)
4276                 strlcat(buf, "|VI_MOUNT", sizeof(buf));
4277         if (vp->v_iflag & VI_DOINGINACT)
4278                 strlcat(buf, "|VI_DOINGINACT", sizeof(buf));
4279         if (vp->v_iflag & VI_OWEINACT)
4280                 strlcat(buf, "|VI_OWEINACT", sizeof(buf));
4281         if (vp->v_iflag & VI_DEFINACT)
4282                 strlcat(buf, "|VI_DEFINACT", sizeof(buf));
4283         if (vp->v_iflag & VI_FOPENING)
4284                 strlcat(buf, "|VI_FOPENING", sizeof(buf));
4285         flags = vp->v_iflag & ~(VI_TEXT_REF | VI_MOUNT | VI_DOINGINACT |
4286             VI_OWEINACT | VI_DEFINACT | VI_FOPENING);
4287         if (flags != 0) {
4288                 snprintf(buf2, sizeof(buf2), "|VI(0x%lx)", flags);
4289                 strlcat(buf, buf2, sizeof(buf));
4290         }
4291         if (vp->v_mflag & VMP_LAZYLIST)
4292                 strlcat(buf, "|VMP_LAZYLIST", sizeof(buf));
4293         flags = vp->v_mflag & ~(VMP_LAZYLIST);
4294         if (flags != 0) {
4295                 snprintf(buf2, sizeof(buf2), "|VMP(0x%lx)", flags);
4296                 strlcat(buf, buf2, sizeof(buf));
4297         }
4298         printf("    flags (%s)", buf + 1);
4299         if (mtx_owned(VI_MTX(vp)))
4300                 printf(" VI_LOCKed");
4301         printf("\n");
4302         if (vp->v_object != NULL)
4303                 printf("    v_object %p ref %d pages %d "
4304                     "cleanbuf %d dirtybuf %d\n",
4305                     vp->v_object, vp->v_object->ref_count,
4306                     vp->v_object->resident_page_count,
4307                     vp->v_bufobj.bo_clean.bv_cnt,
4308                     vp->v_bufobj.bo_dirty.bv_cnt);
4309         printf("    ");
4310         lockmgr_printinfo(vp->v_vnlock);
4311         if (vp->v_data != NULL)
4312                 VOP_PRINT(vp);
4313 }
4314
4315 #ifdef DDB
4316 /*
4317  * List all of the locked vnodes in the system.
4318  * Called when debugging the kernel.
4319  */
4320 DB_SHOW_COMMAND(lockedvnods, lockedvnodes)
4321 {
4322         struct mount *mp;
4323         struct vnode *vp;
4324
4325         /*
4326          * Note: because this is DDB, we can't obey the locking semantics
4327          * for these structures, which means we could catch an inconsistent
4328          * state and dereference a nasty pointer.  Not much to be done
4329          * about that.
4330          */
4331         db_printf("Locked vnodes\n");
4332         TAILQ_FOREACH(mp, &mountlist, mnt_list) {
4333                 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4334                         if (vp->v_type != VMARKER && VOP_ISLOCKED(vp))
4335                                 vn_printf(vp, "vnode ");
4336                 }
4337         }
4338 }
4339
4340 /*
4341  * Show details about the given vnode.
4342  */
4343 DB_SHOW_COMMAND(vnode, db_show_vnode)
4344 {
4345         struct vnode *vp;
4346
4347         if (!have_addr)
4348                 return;
4349         vp = (struct vnode *)addr;
4350         vn_printf(vp, "vnode ");
4351 }
4352
4353 /*
4354  * Show details about the given mount point.
4355  */
4356 DB_SHOW_COMMAND(mount, db_show_mount)
4357 {
4358         struct mount *mp;
4359         struct vfsopt *opt;
4360         struct statfs *sp;
4361         struct vnode *vp;
4362         char buf[512];
4363         uint64_t mflags;
4364         u_int flags;
4365
4366         if (!have_addr) {
4367                 /* No address given, print short info about all mount points. */
4368                 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
4369                         db_printf("%p %s on %s (%s)\n", mp,
4370                             mp->mnt_stat.f_mntfromname,
4371                             mp->mnt_stat.f_mntonname,
4372                             mp->mnt_stat.f_fstypename);
4373                         if (db_pager_quit)
4374                                 break;
4375                 }
4376                 db_printf("\nMore info: show mount <addr>\n");
4377                 return;
4378         }
4379
4380         mp = (struct mount *)addr;
4381         db_printf("%p %s on %s (%s)\n", mp, mp->mnt_stat.f_mntfromname,
4382             mp->mnt_stat.f_mntonname, mp->mnt_stat.f_fstypename);
4383
4384         buf[0] = '\0';
4385         mflags = mp->mnt_flag;
4386 #define MNT_FLAG(flag)  do {                                            \
4387         if (mflags & (flag)) {                                          \
4388                 if (buf[0] != '\0')                                     \
4389                         strlcat(buf, ", ", sizeof(buf));                \
4390                 strlcat(buf, (#flag) + 4, sizeof(buf));                 \
4391                 mflags &= ~(flag);                                      \
4392         }                                                               \
4393 } while (0)
4394         MNT_FLAG(MNT_RDONLY);
4395         MNT_FLAG(MNT_SYNCHRONOUS);
4396         MNT_FLAG(MNT_NOEXEC);
4397         MNT_FLAG(MNT_NOSUID);
4398         MNT_FLAG(MNT_NFS4ACLS);
4399         MNT_FLAG(MNT_UNION);
4400         MNT_FLAG(MNT_ASYNC);
4401         MNT_FLAG(MNT_SUIDDIR);
4402         MNT_FLAG(MNT_SOFTDEP);
4403         MNT_FLAG(MNT_NOSYMFOLLOW);
4404         MNT_FLAG(MNT_GJOURNAL);
4405         MNT_FLAG(MNT_MULTILABEL);
4406         MNT_FLAG(MNT_ACLS);
4407         MNT_FLAG(MNT_NOATIME);
4408         MNT_FLAG(MNT_NOCLUSTERR);
4409         MNT_FLAG(MNT_NOCLUSTERW);
4410         MNT_FLAG(MNT_SUJ);
4411         MNT_FLAG(MNT_EXRDONLY);
4412         MNT_FLAG(MNT_EXPORTED);
4413         MNT_FLAG(MNT_DEFEXPORTED);
4414         MNT_FLAG(MNT_EXPORTANON);
4415         MNT_FLAG(MNT_EXKERB);
4416         MNT_FLAG(MNT_EXPUBLIC);
4417         MNT_FLAG(MNT_LOCAL);
4418         MNT_FLAG(MNT_QUOTA);
4419         MNT_FLAG(MNT_ROOTFS);
4420         MNT_FLAG(MNT_USER);
4421         MNT_FLAG(MNT_IGNORE);
4422         MNT_FLAG(MNT_UPDATE);
4423         MNT_FLAG(MNT_DELEXPORT);
4424         MNT_FLAG(MNT_RELOAD);
4425         MNT_FLAG(MNT_FORCE);
4426         MNT_FLAG(MNT_SNAPSHOT);
4427         MNT_FLAG(MNT_BYFSID);
4428 #undef MNT_FLAG
4429         if (mflags != 0) {
4430                 if (buf[0] != '\0')
4431                         strlcat(buf, ", ", sizeof(buf));
4432                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
4433                     "0x%016jx", mflags);
4434         }
4435         db_printf("    mnt_flag = %s\n", buf);
4436
4437         buf[0] = '\0';
4438         flags = mp->mnt_kern_flag;
4439 #define MNT_KERN_FLAG(flag)     do {                                    \
4440         if (flags & (flag)) {                                           \
4441                 if (buf[0] != '\0')                                     \
4442                         strlcat(buf, ", ", sizeof(buf));                \
4443                 strlcat(buf, (#flag) + 5, sizeof(buf));                 \
4444                 flags &= ~(flag);                                       \
4445         }                                                               \
4446 } while (0)
4447         MNT_KERN_FLAG(MNTK_UNMOUNTF);
4448         MNT_KERN_FLAG(MNTK_ASYNC);
4449         MNT_KERN_FLAG(MNTK_SOFTDEP);
4450         MNT_KERN_FLAG(MNTK_DRAINING);
4451         MNT_KERN_FLAG(MNTK_REFEXPIRE);
4452         MNT_KERN_FLAG(MNTK_EXTENDED_SHARED);
4453         MNT_KERN_FLAG(MNTK_SHARED_WRITES);
4454         MNT_KERN_FLAG(MNTK_NO_IOPF);
4455         MNT_KERN_FLAG(MNTK_VGONE_UPPER);
4456         MNT_KERN_FLAG(MNTK_VGONE_WAITER);
4457         MNT_KERN_FLAG(MNTK_LOOKUP_EXCL_DOTDOT);
4458         MNT_KERN_FLAG(MNTK_MARKER);
4459         MNT_KERN_FLAG(MNTK_USES_BCACHE);
4460         MNT_KERN_FLAG(MNTK_FPLOOKUP);
4461         MNT_KERN_FLAG(MNTK_NOASYNC);
4462         MNT_KERN_FLAG(MNTK_UNMOUNT);
4463         MNT_KERN_FLAG(MNTK_MWAIT);
4464         MNT_KERN_FLAG(MNTK_SUSPEND);
4465         MNT_KERN_FLAG(MNTK_SUSPEND2);
4466         MNT_KERN_FLAG(MNTK_SUSPENDED);
4467         MNT_KERN_FLAG(MNTK_LOOKUP_SHARED);
4468         MNT_KERN_FLAG(MNTK_NOKNOTE);
4469 #undef MNT_KERN_FLAG
4470         if (flags != 0) {
4471                 if (buf[0] != '\0')
4472                         strlcat(buf, ", ", sizeof(buf));
4473                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
4474                     "0x%08x", flags);
4475         }
4476         db_printf("    mnt_kern_flag = %s\n", buf);
4477
4478         db_printf("    mnt_opt = ");
4479         opt = TAILQ_FIRST(mp->mnt_opt);
4480         if (opt != NULL) {
4481                 db_printf("%s", opt->name);
4482                 opt = TAILQ_NEXT(opt, link);
4483                 while (opt != NULL) {
4484                         db_printf(", %s", opt->name);
4485                         opt = TAILQ_NEXT(opt, link);
4486                 }
4487         }
4488         db_printf("\n");
4489
4490         sp = &mp->mnt_stat;
4491         db_printf("    mnt_stat = { version=%u type=%u flags=0x%016jx "
4492             "bsize=%ju iosize=%ju blocks=%ju bfree=%ju bavail=%jd files=%ju "
4493             "ffree=%jd syncwrites=%ju asyncwrites=%ju syncreads=%ju "
4494             "asyncreads=%ju namemax=%u owner=%u fsid=[%d, %d] }\n",
4495             (u_int)sp->f_version, (u_int)sp->f_type, (uintmax_t)sp->f_flags,
4496             (uintmax_t)sp->f_bsize, (uintmax_t)sp->f_iosize,
4497             (uintmax_t)sp->f_blocks, (uintmax_t)sp->f_bfree,
4498             (intmax_t)sp->f_bavail, (uintmax_t)sp->f_files,
4499             (intmax_t)sp->f_ffree, (uintmax_t)sp->f_syncwrites,
4500             (uintmax_t)sp->f_asyncwrites, (uintmax_t)sp->f_syncreads,
4501             (uintmax_t)sp->f_asyncreads, (u_int)sp->f_namemax,
4502             (u_int)sp->f_owner, (int)sp->f_fsid.val[0], (int)sp->f_fsid.val[1]);
4503
4504         db_printf("    mnt_cred = { uid=%u ruid=%u",
4505             (u_int)mp->mnt_cred->cr_uid, (u_int)mp->mnt_cred->cr_ruid);
4506         if (jailed(mp->mnt_cred))
4507                 db_printf(", jail=%d", mp->mnt_cred->cr_prison->pr_id);
4508         db_printf(" }\n");
4509         db_printf("    mnt_ref = %d (with %d in the struct)\n",
4510             vfs_mount_fetch_counter(mp, MNT_COUNT_REF), mp->mnt_ref);
4511         db_printf("    mnt_gen = %d\n", mp->mnt_gen);
4512         db_printf("    mnt_nvnodelistsize = %d\n", mp->mnt_nvnodelistsize);
4513         db_printf("    mnt_lazyvnodelistsize = %d\n",
4514             mp->mnt_lazyvnodelistsize);
4515         db_printf("    mnt_writeopcount = %d (with %d in the struct)\n",
4516             vfs_mount_fetch_counter(mp, MNT_COUNT_WRITEOPCOUNT), mp->mnt_writeopcount);
4517         db_printf("    mnt_iosize_max = %d\n", mp->mnt_iosize_max);
4518         db_printf("    mnt_hashseed = %u\n", mp->mnt_hashseed);
4519         db_printf("    mnt_lockref = %d (with %d in the struct)\n",
4520             vfs_mount_fetch_counter(mp, MNT_COUNT_LOCKREF), mp->mnt_lockref);
4521         db_printf("    mnt_secondary_writes = %d\n", mp->mnt_secondary_writes);
4522         db_printf("    mnt_secondary_accwrites = %d\n",
4523             mp->mnt_secondary_accwrites);
4524         db_printf("    mnt_gjprovider = %s\n",
4525             mp->mnt_gjprovider != NULL ? mp->mnt_gjprovider : "NULL");
4526         db_printf("    mnt_vfs_ops = %d\n", mp->mnt_vfs_ops);
4527
4528         db_printf("\n\nList of active vnodes\n");
4529         TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4530                 if (vp->v_type != VMARKER && vp->v_holdcnt > 0) {
4531                         vn_printf(vp, "vnode ");
4532                         if (db_pager_quit)
4533                                 break;
4534                 }
4535         }
4536         db_printf("\n\nList of inactive vnodes\n");
4537         TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4538                 if (vp->v_type != VMARKER && vp->v_holdcnt == 0) {
4539                         vn_printf(vp, "vnode ");
4540                         if (db_pager_quit)
4541                                 break;
4542                 }
4543         }
4544 }
4545 #endif  /* DDB */
4546
4547 /*
4548  * Fill in a struct xvfsconf based on a struct vfsconf.
4549  */
4550 static int
4551 vfsconf2x(struct sysctl_req *req, struct vfsconf *vfsp)
4552 {
4553         struct xvfsconf xvfsp;
4554
4555         bzero(&xvfsp, sizeof(xvfsp));
4556         strcpy(xvfsp.vfc_name, vfsp->vfc_name);
4557         xvfsp.vfc_typenum = vfsp->vfc_typenum;
4558         xvfsp.vfc_refcount = vfsp->vfc_refcount;
4559         xvfsp.vfc_flags = vfsp->vfc_flags;
4560         /*
4561          * These are unused in userland, we keep them
4562          * to not break binary compatibility.
4563          */
4564         xvfsp.vfc_vfsops = NULL;
4565         xvfsp.vfc_next = NULL;
4566         return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
4567 }
4568
4569 #ifdef COMPAT_FREEBSD32
4570 struct xvfsconf32 {
4571         uint32_t        vfc_vfsops;
4572         char            vfc_name[MFSNAMELEN];
4573         int32_t         vfc_typenum;
4574         int32_t         vfc_refcount;
4575         int32_t         vfc_flags;
4576         uint32_t        vfc_next;
4577 };
4578
4579 static int
4580 vfsconf2x32(struct sysctl_req *req, struct vfsconf *vfsp)
4581 {
4582         struct xvfsconf32 xvfsp;
4583
4584         bzero(&xvfsp, sizeof(xvfsp));
4585         strcpy(xvfsp.vfc_name, vfsp->vfc_name);
4586         xvfsp.vfc_typenum = vfsp->vfc_typenum;
4587         xvfsp.vfc_refcount = vfsp->vfc_refcount;
4588         xvfsp.vfc_flags = vfsp->vfc_flags;
4589         return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
4590 }
4591 #endif
4592
4593 /*
4594  * Top level filesystem related information gathering.
4595  */
4596 static int
4597 sysctl_vfs_conflist(SYSCTL_HANDLER_ARGS)
4598 {
4599         struct vfsconf *vfsp;
4600         int error;
4601
4602         error = 0;
4603         vfsconf_slock();
4604         TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4605 #ifdef COMPAT_FREEBSD32
4606                 if (req->flags & SCTL_MASK32)
4607                         error = vfsconf2x32(req, vfsp);
4608                 else
4609 #endif
4610                         error = vfsconf2x(req, vfsp);
4611                 if (error)
4612                         break;
4613         }
4614         vfsconf_sunlock();
4615         return (error);
4616 }
4617
4618 SYSCTL_PROC(_vfs, OID_AUTO, conflist, CTLTYPE_OPAQUE | CTLFLAG_RD |
4619     CTLFLAG_MPSAFE, NULL, 0, sysctl_vfs_conflist,
4620     "S,xvfsconf", "List of all configured filesystems");
4621
4622 #ifndef BURN_BRIDGES
4623 static int      sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS);
4624
4625 static int
4626 vfs_sysctl(SYSCTL_HANDLER_ARGS)
4627 {
4628         int *name = (int *)arg1 - 1;    /* XXX */
4629         u_int namelen = arg2 + 1;       /* XXX */
4630         struct vfsconf *vfsp;
4631
4632         log(LOG_WARNING, "userland calling deprecated sysctl, "
4633             "please rebuild world\n");
4634
4635 #if 1 || defined(COMPAT_PRELITE2)
4636         /* Resolve ambiguity between VFS_VFSCONF and VFS_GENERIC. */
4637         if (namelen == 1)
4638                 return (sysctl_ovfs_conf(oidp, arg1, arg2, req));
4639 #endif
4640
4641         switch (name[1]) {
4642         case VFS_MAXTYPENUM:
4643                 if (namelen != 2)
4644                         return (ENOTDIR);
4645                 return (SYSCTL_OUT(req, &maxvfsconf, sizeof(int)));
4646         case VFS_CONF:
4647                 if (namelen != 3)
4648                         return (ENOTDIR);       /* overloaded */
4649                 vfsconf_slock();
4650                 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4651                         if (vfsp->vfc_typenum == name[2])
4652                                 break;
4653                 }
4654                 vfsconf_sunlock();
4655                 if (vfsp == NULL)
4656                         return (EOPNOTSUPP);
4657 #ifdef COMPAT_FREEBSD32
4658                 if (req->flags & SCTL_MASK32)
4659                         return (vfsconf2x32(req, vfsp));
4660                 else
4661 #endif
4662                         return (vfsconf2x(req, vfsp));
4663         }
4664         return (EOPNOTSUPP);
4665 }
4666
4667 static SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RD | CTLFLAG_SKIP |
4668     CTLFLAG_MPSAFE, vfs_sysctl,
4669     "Generic filesystem");
4670
4671 #if 1 || defined(COMPAT_PRELITE2)
4672
4673 static int
4674 sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS)
4675 {
4676         int error;
4677         struct vfsconf *vfsp;
4678         struct ovfsconf ovfs;
4679
4680         vfsconf_slock();
4681         TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4682                 bzero(&ovfs, sizeof(ovfs));
4683                 ovfs.vfc_vfsops = vfsp->vfc_vfsops;     /* XXX used as flag */
4684                 strcpy(ovfs.vfc_name, vfsp->vfc_name);
4685                 ovfs.vfc_index = vfsp->vfc_typenum;
4686                 ovfs.vfc_refcount = vfsp->vfc_refcount;
4687                 ovfs.vfc_flags = vfsp->vfc_flags;
4688                 error = SYSCTL_OUT(req, &ovfs, sizeof ovfs);
4689                 if (error != 0) {
4690                         vfsconf_sunlock();
4691                         return (error);
4692                 }
4693         }
4694         vfsconf_sunlock();
4695         return (0);
4696 }
4697
4698 #endif /* 1 || COMPAT_PRELITE2 */
4699 #endif /* !BURN_BRIDGES */
4700
4701 #define KINFO_VNODESLOP         10
4702 #ifdef notyet
4703 /*
4704  * Dump vnode list (via sysctl).
4705  */
4706 /* ARGSUSED */
4707 static int
4708 sysctl_vnode(SYSCTL_HANDLER_ARGS)
4709 {
4710         struct xvnode *xvn;
4711         struct mount *mp;
4712         struct vnode *vp;
4713         int error, len, n;
4714
4715         /*
4716          * Stale numvnodes access is not fatal here.
4717          */
4718         req->lock = 0;
4719         len = (numvnodes + KINFO_VNODESLOP) * sizeof *xvn;
4720         if (!req->oldptr)
4721                 /* Make an estimate */
4722                 return (SYSCTL_OUT(req, 0, len));
4723
4724         error = sysctl_wire_old_buffer(req, 0);
4725         if (error != 0)
4726                 return (error);
4727         xvn = malloc(len, M_TEMP, M_ZERO | M_WAITOK);
4728         n = 0;
4729         mtx_lock(&mountlist_mtx);
4730         TAILQ_FOREACH(mp, &mountlist, mnt_list) {
4731                 if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK))
4732                         continue;
4733                 MNT_ILOCK(mp);
4734                 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4735                         if (n == len)
4736                                 break;
4737                         vref(vp);
4738                         xvn[n].xv_size = sizeof *xvn;
4739                         xvn[n].xv_vnode = vp;
4740                         xvn[n].xv_id = 0;       /* XXX compat */
4741 #define XV_COPY(field) xvn[n].xv_##field = vp->v_##field
4742                         XV_COPY(usecount);
4743                         XV_COPY(writecount);
4744                         XV_COPY(holdcnt);
4745                         XV_COPY(mount);
4746                         XV_COPY(numoutput);
4747                         XV_COPY(type);
4748 #undef XV_COPY
4749                         xvn[n].xv_flag = vp->v_vflag;
4750
4751                         switch (vp->v_type) {
4752                         case VREG:
4753                         case VDIR:
4754                         case VLNK:
4755                                 break;
4756                         case VBLK:
4757                         case VCHR:
4758                                 if (vp->v_rdev == NULL) {
4759                                         vrele(vp);
4760                                         continue;
4761                                 }
4762                                 xvn[n].xv_dev = dev2udev(vp->v_rdev);
4763                                 break;
4764                         case VSOCK:
4765                                 xvn[n].xv_socket = vp->v_socket;
4766                                 break;
4767                         case VFIFO:
4768                                 xvn[n].xv_fifo = vp->v_fifoinfo;
4769                                 break;
4770                         case VNON:
4771                         case VBAD:
4772                         default:
4773                                 /* shouldn't happen? */
4774                                 vrele(vp);
4775                                 continue;
4776                         }
4777                         vrele(vp);
4778                         ++n;
4779                 }
4780                 MNT_IUNLOCK(mp);
4781                 mtx_lock(&mountlist_mtx);
4782                 vfs_unbusy(mp);
4783                 if (n == len)
4784                         break;
4785         }
4786         mtx_unlock(&mountlist_mtx);
4787
4788         error = SYSCTL_OUT(req, xvn, n * sizeof *xvn);
4789         free(xvn, M_TEMP);
4790         return (error);
4791 }
4792
4793 SYSCTL_PROC(_kern, KERN_VNODE, vnode, CTLTYPE_OPAQUE | CTLFLAG_RD |
4794     CTLFLAG_MPSAFE, 0, 0, sysctl_vnode, "S,xvnode",
4795     "");
4796 #endif
4797
4798 static void
4799 unmount_or_warn(struct mount *mp)
4800 {
4801         int error;
4802
4803         error = dounmount(mp, MNT_FORCE, curthread);
4804         if (error != 0) {
4805                 printf("unmount of %s failed (", mp->mnt_stat.f_mntonname);
4806                 if (error == EBUSY)
4807                         printf("BUSY)\n");
4808                 else
4809                         printf("%d)\n", error);
4810         }
4811 }
4812
4813 /*
4814  * Unmount all filesystems. The list is traversed in reverse order
4815  * of mounting to avoid dependencies.
4816  */
4817 void
4818 vfs_unmountall(void)
4819 {
4820         struct mount *mp, *tmp;
4821
4822         CTR1(KTR_VFS, "%s: unmounting all filesystems", __func__);
4823
4824         /*
4825          * Since this only runs when rebooting, it is not interlocked.
4826          */
4827         TAILQ_FOREACH_REVERSE_SAFE(mp, &mountlist, mntlist, mnt_list, tmp) {
4828                 vfs_ref(mp);
4829
4830                 /*
4831                  * Forcibly unmounting "/dev" before "/" would prevent clean
4832                  * unmount of the latter.
4833                  */
4834                 if (mp == rootdevmp)
4835                         continue;
4836
4837                 unmount_or_warn(mp);
4838         }
4839
4840         if (rootdevmp != NULL)
4841                 unmount_or_warn(rootdevmp);
4842 }
4843
4844 static void
4845 vfs_deferred_inactive(struct vnode *vp, int lkflags)
4846 {
4847
4848         ASSERT_VI_LOCKED(vp, __func__);
4849         VNASSERT((vp->v_iflag & VI_DEFINACT) == 0, vp, ("VI_DEFINACT still set"));
4850         if ((vp->v_iflag & VI_OWEINACT) == 0) {
4851                 vdropl(vp);
4852                 return;
4853         }
4854         if (vn_lock(vp, lkflags) == 0) {
4855                 VI_LOCK(vp);
4856                 vinactive(vp);
4857                 VOP_UNLOCK(vp);
4858                 vdropl(vp);
4859                 return;
4860         }
4861         vdefer_inactive_unlocked(vp);
4862 }
4863
4864 static int
4865 vfs_periodic_inactive_filter(struct vnode *vp, void *arg)
4866 {
4867
4868         return (vp->v_iflag & VI_DEFINACT);
4869 }
4870
4871 static void __noinline
4872 vfs_periodic_inactive(struct mount *mp, int flags)
4873 {
4874         struct vnode *vp, *mvp;
4875         int lkflags;
4876
4877         lkflags = LK_EXCLUSIVE | LK_INTERLOCK;
4878         if (flags != MNT_WAIT)
4879                 lkflags |= LK_NOWAIT;
4880
4881         MNT_VNODE_FOREACH_LAZY(vp, mp, mvp, vfs_periodic_inactive_filter, NULL) {
4882                 if ((vp->v_iflag & VI_DEFINACT) == 0) {
4883                         VI_UNLOCK(vp);
4884                         continue;
4885                 }
4886                 vp->v_iflag &= ~VI_DEFINACT;
4887                 vfs_deferred_inactive(vp, lkflags);
4888         }
4889 }
4890
4891 static inline bool
4892 vfs_want_msync(struct vnode *vp)
4893 {
4894         struct vm_object *obj;
4895
4896         /*
4897          * This test may be performed without any locks held.
4898          * We rely on vm_object's type stability.
4899          */
4900         if (vp->v_vflag & VV_NOSYNC)
4901                 return (false);
4902         obj = vp->v_object;
4903         return (obj != NULL && vm_object_mightbedirty(obj));
4904 }
4905
4906 static int
4907 vfs_periodic_msync_inactive_filter(struct vnode *vp, void *arg __unused)
4908 {
4909
4910         if (vp->v_vflag & VV_NOSYNC)
4911                 return (false);
4912         if (vp->v_iflag & VI_DEFINACT)
4913                 return (true);
4914         return (vfs_want_msync(vp));
4915 }
4916
4917 static void __noinline
4918 vfs_periodic_msync_inactive(struct mount *mp, int flags)
4919 {
4920         struct vnode *vp, *mvp;
4921         struct vm_object *obj;
4922         int lkflags, objflags;
4923         bool seen_defer;
4924
4925         lkflags = LK_EXCLUSIVE | LK_INTERLOCK;
4926         if (flags != MNT_WAIT) {
4927                 lkflags |= LK_NOWAIT;
4928                 objflags = OBJPC_NOSYNC;
4929         } else {
4930                 objflags = OBJPC_SYNC;
4931         }
4932
4933         MNT_VNODE_FOREACH_LAZY(vp, mp, mvp, vfs_periodic_msync_inactive_filter, NULL) {
4934                 seen_defer = false;
4935                 if (vp->v_iflag & VI_DEFINACT) {
4936                         vp->v_iflag &= ~VI_DEFINACT;
4937                         seen_defer = true;
4938                 }
4939                 if (!vfs_want_msync(vp)) {
4940                         if (seen_defer)
4941                                 vfs_deferred_inactive(vp, lkflags);
4942                         else
4943                                 VI_UNLOCK(vp);
4944                         continue;
4945                 }
4946                 if (vget(vp, lkflags) == 0) {
4947                         obj = vp->v_object;
4948                         if (obj != NULL && (vp->v_vflag & VV_NOSYNC) == 0) {
4949                                 VM_OBJECT_WLOCK(obj);
4950                                 vm_object_page_clean(obj, 0, 0, objflags);
4951                                 VM_OBJECT_WUNLOCK(obj);
4952                         }
4953                         vput(vp);
4954                         if (seen_defer)
4955                                 vdrop(vp);
4956                 } else {
4957                         if (seen_defer)
4958                                 vdefer_inactive_unlocked(vp);
4959                 }
4960         }
4961 }
4962
4963 void
4964 vfs_periodic(struct mount *mp, int flags)
4965 {
4966
4967         CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
4968
4969         if ((mp->mnt_kern_flag & MNTK_NOMSYNC) != 0)
4970                 vfs_periodic_inactive(mp, flags);
4971         else
4972                 vfs_periodic_msync_inactive(mp, flags);
4973 }
4974
4975 static void
4976 destroy_vpollinfo_free(struct vpollinfo *vi)
4977 {
4978
4979         knlist_destroy(&vi->vpi_selinfo.si_note);
4980         mtx_destroy(&vi->vpi_lock);
4981         free(vi, M_VNODEPOLL);
4982 }
4983
4984 static void
4985 destroy_vpollinfo(struct vpollinfo *vi)
4986 {
4987
4988         knlist_clear(&vi->vpi_selinfo.si_note, 1);
4989         seldrain(&vi->vpi_selinfo);
4990         destroy_vpollinfo_free(vi);
4991 }
4992
4993 /*
4994  * Initialize per-vnode helper structure to hold poll-related state.
4995  */
4996 void
4997 v_addpollinfo(struct vnode *vp)
4998 {
4999         struct vpollinfo *vi;
5000
5001         if (vp->v_pollinfo != NULL)
5002                 return;
5003         vi = malloc(sizeof(*vi), M_VNODEPOLL, M_WAITOK | M_ZERO);
5004         mtx_init(&vi->vpi_lock, "vnode pollinfo", NULL, MTX_DEF);
5005         knlist_init(&vi->vpi_selinfo.si_note, vp, vfs_knllock,
5006             vfs_knlunlock, vfs_knl_assert_lock);
5007         VI_LOCK(vp);
5008         if (vp->v_pollinfo != NULL) {
5009                 VI_UNLOCK(vp);
5010                 destroy_vpollinfo_free(vi);
5011                 return;
5012         }
5013         vp->v_pollinfo = vi;
5014         VI_UNLOCK(vp);
5015 }
5016
5017 /*
5018  * Record a process's interest in events which might happen to
5019  * a vnode.  Because poll uses the historic select-style interface
5020  * internally, this routine serves as both the ``check for any
5021  * pending events'' and the ``record my interest in future events''
5022  * functions.  (These are done together, while the lock is held,
5023  * to avoid race conditions.)
5024  */
5025 int
5026 vn_pollrecord(struct vnode *vp, struct thread *td, int events)
5027 {
5028
5029         v_addpollinfo(vp);
5030         mtx_lock(&vp->v_pollinfo->vpi_lock);
5031         if (vp->v_pollinfo->vpi_revents & events) {
5032                 /*
5033                  * This leaves events we are not interested
5034                  * in available for the other process which
5035                  * which presumably had requested them
5036                  * (otherwise they would never have been
5037                  * recorded).
5038                  */
5039                 events &= vp->v_pollinfo->vpi_revents;
5040                 vp->v_pollinfo->vpi_revents &= ~events;
5041
5042                 mtx_unlock(&vp->v_pollinfo->vpi_lock);
5043                 return (events);
5044         }
5045         vp->v_pollinfo->vpi_events |= events;
5046         selrecord(td, &vp->v_pollinfo->vpi_selinfo);
5047         mtx_unlock(&vp->v_pollinfo->vpi_lock);
5048         return (0);
5049 }
5050
5051 /*
5052  * Routine to create and manage a filesystem syncer vnode.
5053  */
5054 #define sync_close ((int (*)(struct  vop_close_args *))nullop)
5055 static int      sync_fsync(struct  vop_fsync_args *);
5056 static int      sync_inactive(struct  vop_inactive_args *);
5057 static int      sync_reclaim(struct  vop_reclaim_args *);
5058
5059 static struct vop_vector sync_vnodeops = {
5060         .vop_bypass =   VOP_EOPNOTSUPP,
5061         .vop_close =    sync_close,             /* close */
5062         .vop_fsync =    sync_fsync,             /* fsync */
5063         .vop_getwritemount = vop_stdgetwritemount,
5064         .vop_inactive = sync_inactive,  /* inactive */
5065         .vop_need_inactive = vop_stdneed_inactive, /* need_inactive */
5066         .vop_reclaim =  sync_reclaim,   /* reclaim */
5067         .vop_lock1 =    vop_stdlock,    /* lock */
5068         .vop_unlock =   vop_stdunlock,  /* unlock */
5069         .vop_islocked = vop_stdislocked,        /* islocked */
5070 };
5071 VFS_VOP_VECTOR_REGISTER(sync_vnodeops);
5072
5073 /*
5074  * Create a new filesystem syncer vnode for the specified mount point.
5075  */
5076 void
5077 vfs_allocate_syncvnode(struct mount *mp)
5078 {
5079         struct vnode *vp;
5080         struct bufobj *bo;
5081         static long start, incr, next;
5082         int error;
5083
5084         /* Allocate a new vnode */
5085         error = getnewvnode("syncer", mp, &sync_vnodeops, &vp);
5086         if (error != 0)
5087                 panic("vfs_allocate_syncvnode: getnewvnode() failed");
5088         vp->v_type = VNON;
5089         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
5090         vp->v_vflag |= VV_FORCEINSMQ;
5091         error = insmntque(vp, mp);
5092         if (error != 0)
5093                 panic("vfs_allocate_syncvnode: insmntque() failed");
5094         vp->v_vflag &= ~VV_FORCEINSMQ;
5095         VOP_UNLOCK(vp);
5096         /*
5097          * Place the vnode onto the syncer worklist. We attempt to
5098          * scatter them about on the list so that they will go off
5099          * at evenly distributed times even if all the filesystems
5100          * are mounted at once.
5101          */
5102         next += incr;
5103         if (next == 0 || next > syncer_maxdelay) {
5104                 start /= 2;
5105                 incr /= 2;
5106                 if (start == 0) {
5107                         start = syncer_maxdelay / 2;
5108                         incr = syncer_maxdelay;
5109                 }
5110                 next = start;
5111         }
5112         bo = &vp->v_bufobj;
5113         BO_LOCK(bo);
5114         vn_syncer_add_to_worklist(bo, syncdelay > 0 ? next % syncdelay : 0);
5115         /* XXX - vn_syncer_add_to_worklist() also grabs and drops sync_mtx. */
5116         mtx_lock(&sync_mtx);
5117         sync_vnode_count++;
5118         if (mp->mnt_syncer == NULL) {
5119                 mp->mnt_syncer = vp;
5120                 vp = NULL;
5121         }
5122         mtx_unlock(&sync_mtx);
5123         BO_UNLOCK(bo);
5124         if (vp != NULL) {
5125                 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
5126                 vgone(vp);
5127                 vput(vp);
5128         }
5129 }
5130
5131 void
5132 vfs_deallocate_syncvnode(struct mount *mp)
5133 {
5134         struct vnode *vp;
5135
5136         mtx_lock(&sync_mtx);
5137         vp = mp->mnt_syncer;
5138         if (vp != NULL)
5139                 mp->mnt_syncer = NULL;
5140         mtx_unlock(&sync_mtx);
5141         if (vp != NULL)
5142                 vrele(vp);
5143 }
5144
5145 /*
5146  * Do a lazy sync of the filesystem.
5147  */
5148 static int
5149 sync_fsync(struct vop_fsync_args *ap)
5150 {
5151         struct vnode *syncvp = ap->a_vp;
5152         struct mount *mp = syncvp->v_mount;
5153         int error, save;
5154         struct bufobj *bo;
5155
5156         /*
5157          * We only need to do something if this is a lazy evaluation.
5158          */
5159         if (ap->a_waitfor != MNT_LAZY)
5160                 return (0);
5161
5162         /*
5163          * Move ourselves to the back of the sync list.
5164          */
5165         bo = &syncvp->v_bufobj;
5166         BO_LOCK(bo);
5167         vn_syncer_add_to_worklist(bo, syncdelay);
5168         BO_UNLOCK(bo);
5169
5170         /*
5171          * Walk the list of vnodes pushing all that are dirty and
5172          * not already on the sync list.
5173          */
5174         if (vfs_busy(mp, MBF_NOWAIT) != 0)
5175                 return (0);
5176         VOP_UNLOCK(syncvp);
5177         save = curthread_pflags_set(TDP_SYNCIO);
5178         /*
5179          * The filesystem at hand may be idle with free vnodes stored in the
5180          * batch.  Return them instead of letting them stay there indefinitely.
5181          */
5182         vfs_periodic(mp, MNT_NOWAIT);
5183         error = VFS_SYNC(mp, MNT_LAZY);
5184         curthread_pflags_restore(save);
5185         vn_lock(syncvp, LK_EXCLUSIVE | LK_RETRY);
5186         vfs_unbusy(mp);
5187         return (error);
5188 }
5189
5190 /*
5191  * The syncer vnode is no referenced.
5192  */
5193 static int
5194 sync_inactive(struct vop_inactive_args *ap)
5195 {
5196
5197         vgone(ap->a_vp);
5198         return (0);
5199 }
5200
5201 /*
5202  * The syncer vnode is no longer needed and is being decommissioned.
5203  *
5204  * Modifications to the worklist must be protected by sync_mtx.
5205  */
5206 static int
5207 sync_reclaim(struct vop_reclaim_args *ap)
5208 {
5209         struct vnode *vp = ap->a_vp;
5210         struct bufobj *bo;
5211
5212         bo = &vp->v_bufobj;
5213         BO_LOCK(bo);
5214         mtx_lock(&sync_mtx);
5215         if (vp->v_mount->mnt_syncer == vp)
5216                 vp->v_mount->mnt_syncer = NULL;
5217         if (bo->bo_flag & BO_ONWORKLST) {
5218                 LIST_REMOVE(bo, bo_synclist);
5219                 syncer_worklist_len--;
5220                 sync_vnode_count--;
5221                 bo->bo_flag &= ~BO_ONWORKLST;
5222         }
5223         mtx_unlock(&sync_mtx);
5224         BO_UNLOCK(bo);
5225
5226         return (0);
5227 }
5228
5229 int
5230 vn_need_pageq_flush(struct vnode *vp)
5231 {
5232         struct vm_object *obj;
5233
5234         obj = vp->v_object;
5235         return (obj != NULL && (vp->v_vflag & VV_NOSYNC) == 0 &&
5236             vm_object_mightbedirty(obj));
5237 }
5238
5239 /*
5240  * Check if vnode represents a disk device
5241  */
5242 bool
5243 vn_isdisk_error(struct vnode *vp, int *errp)
5244 {
5245         int error;
5246
5247         if (vp->v_type != VCHR) {
5248                 error = ENOTBLK;
5249                 goto out;
5250         }
5251         error = 0;
5252         dev_lock();
5253         if (vp->v_rdev == NULL)
5254                 error = ENXIO;
5255         else if (vp->v_rdev->si_devsw == NULL)
5256                 error = ENXIO;
5257         else if (!(vp->v_rdev->si_devsw->d_flags & D_DISK))
5258                 error = ENOTBLK;
5259         dev_unlock();
5260 out:
5261         *errp = error;
5262         return (error == 0);
5263 }
5264
5265 bool
5266 vn_isdisk(struct vnode *vp)
5267 {
5268         int error;
5269
5270         return (vn_isdisk_error(vp, &error));
5271 }
5272
5273 /*
5274  * VOP_FPLOOKUP_VEXEC routines are subject to special circumstances, see
5275  * the comment above cache_fplookup for details.
5276  */
5277 int
5278 vaccess_vexec_smr(mode_t file_mode, uid_t file_uid, gid_t file_gid, struct ucred *cred)
5279 {
5280         int error;
5281
5282         VFS_SMR_ASSERT_ENTERED();
5283
5284         /* Check the owner. */
5285         if (cred->cr_uid == file_uid) {
5286                 if (file_mode & S_IXUSR)
5287                         return (0);
5288                 goto out_error;
5289         }
5290
5291         /* Otherwise, check the groups (first match) */
5292         if (groupmember(file_gid, cred)) {
5293                 if (file_mode & S_IXGRP)
5294                         return (0);
5295                 goto out_error;
5296         }
5297
5298         /* Otherwise, check everyone else. */
5299         if (file_mode & S_IXOTH)
5300                 return (0);
5301 out_error:
5302         /*
5303          * Permission check failed, but it is possible denial will get overwritten
5304          * (e.g., when root is traversing through a 700 directory owned by someone
5305          * else).
5306          *
5307          * vaccess() calls priv_check_cred which in turn can descent into MAC
5308          * modules overriding this result. It's quite unclear what semantics
5309          * are allowed for them to operate, thus for safety we don't call them
5310          * from within the SMR section. This also means if any such modules
5311          * are present, we have to let the regular lookup decide.
5312          */
5313         error = priv_check_cred_vfs_lookup_nomac(cred);
5314         switch (error) {
5315         case 0:
5316                 return (0);
5317         case EAGAIN:
5318                 /*
5319                  * MAC modules present.
5320                  */
5321                 return (EAGAIN);
5322         case EPERM:
5323                 return (EACCES);
5324         default:
5325                 return (error);
5326         }
5327 }
5328
5329 /*
5330  * Common filesystem object access control check routine.  Accepts a
5331  * vnode's type, "mode", uid and gid, requested access mode, and credentials.
5332  * Returns 0 on success, or an errno on failure.
5333  */
5334 int
5335 vaccess(enum vtype type, mode_t file_mode, uid_t file_uid, gid_t file_gid,
5336     accmode_t accmode, struct ucred *cred)
5337 {
5338         accmode_t dac_granted;
5339         accmode_t priv_granted;
5340
5341         KASSERT((accmode & ~(VEXEC | VWRITE | VREAD | VADMIN | VAPPEND)) == 0,
5342             ("invalid bit in accmode"));
5343         KASSERT((accmode & VAPPEND) == 0 || (accmode & VWRITE),
5344             ("VAPPEND without VWRITE"));
5345
5346         /*
5347          * Look for a normal, non-privileged way to access the file/directory
5348          * as requested.  If it exists, go with that.
5349          */
5350
5351         dac_granted = 0;
5352
5353         /* Check the owner. */
5354         if (cred->cr_uid == file_uid) {
5355                 dac_granted |= VADMIN;
5356                 if (file_mode & S_IXUSR)
5357                         dac_granted |= VEXEC;
5358                 if (file_mode & S_IRUSR)
5359                         dac_granted |= VREAD;
5360                 if (file_mode & S_IWUSR)
5361                         dac_granted |= (VWRITE | VAPPEND);
5362
5363                 if ((accmode & dac_granted) == accmode)
5364                         return (0);
5365
5366                 goto privcheck;
5367         }
5368
5369         /* Otherwise, check the groups (first match) */
5370         if (groupmember(file_gid, cred)) {
5371                 if (file_mode & S_IXGRP)
5372                         dac_granted |= VEXEC;
5373                 if (file_mode & S_IRGRP)
5374                         dac_granted |= VREAD;
5375                 if (file_mode & S_IWGRP)
5376                         dac_granted |= (VWRITE | VAPPEND);
5377
5378                 if ((accmode & dac_granted) == accmode)
5379                         return (0);
5380
5381                 goto privcheck;
5382         }
5383
5384         /* Otherwise, check everyone else. */
5385         if (file_mode & S_IXOTH)
5386                 dac_granted |= VEXEC;
5387         if (file_mode & S_IROTH)
5388                 dac_granted |= VREAD;
5389         if (file_mode & S_IWOTH)
5390                 dac_granted |= (VWRITE | VAPPEND);
5391         if ((accmode & dac_granted) == accmode)
5392                 return (0);
5393
5394 privcheck:
5395         /*
5396          * Build a privilege mask to determine if the set of privileges
5397          * satisfies the requirements when combined with the granted mask
5398          * from above.  For each privilege, if the privilege is required,
5399          * bitwise or the request type onto the priv_granted mask.
5400          */
5401         priv_granted = 0;
5402
5403         if (type == VDIR) {
5404                 /*
5405                  * For directories, use PRIV_VFS_LOOKUP to satisfy VEXEC
5406                  * requests, instead of PRIV_VFS_EXEC.
5407                  */
5408                 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
5409                     !priv_check_cred(cred, PRIV_VFS_LOOKUP))
5410                         priv_granted |= VEXEC;
5411         } else {
5412                 /*
5413                  * Ensure that at least one execute bit is on. Otherwise,
5414                  * a privileged user will always succeed, and we don't want
5415                  * this to happen unless the file really is executable.
5416                  */
5417                 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
5418                     (file_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0 &&
5419                     !priv_check_cred(cred, PRIV_VFS_EXEC))
5420                         priv_granted |= VEXEC;
5421         }
5422
5423         if ((accmode & VREAD) && ((dac_granted & VREAD) == 0) &&
5424             !priv_check_cred(cred, PRIV_VFS_READ))
5425                 priv_granted |= VREAD;
5426
5427         if ((accmode & VWRITE) && ((dac_granted & VWRITE) == 0) &&
5428             !priv_check_cred(cred, PRIV_VFS_WRITE))
5429                 priv_granted |= (VWRITE | VAPPEND);
5430
5431         if ((accmode & VADMIN) && ((dac_granted & VADMIN) == 0) &&
5432             !priv_check_cred(cred, PRIV_VFS_ADMIN))
5433                 priv_granted |= VADMIN;
5434
5435         if ((accmode & (priv_granted | dac_granted)) == accmode) {
5436                 return (0);
5437         }
5438
5439         return ((accmode & VADMIN) ? EPERM : EACCES);
5440 }
5441
5442 /*
5443  * Credential check based on process requesting service, and per-attribute
5444  * permissions.
5445  */
5446 int
5447 extattr_check_cred(struct vnode *vp, int attrnamespace, struct ucred *cred,
5448     struct thread *td, accmode_t accmode)
5449 {
5450
5451         /*
5452          * Kernel-invoked always succeeds.
5453          */
5454         if (cred == NOCRED)
5455                 return (0);
5456
5457         /*
5458          * Do not allow privileged processes in jail to directly manipulate
5459          * system attributes.
5460          */
5461         switch (attrnamespace) {
5462         case EXTATTR_NAMESPACE_SYSTEM:
5463                 /* Potentially should be: return (EPERM); */
5464                 return (priv_check_cred(cred, PRIV_VFS_EXTATTR_SYSTEM));
5465         case EXTATTR_NAMESPACE_USER:
5466                 return (VOP_ACCESS(vp, accmode, cred, td));
5467         default:
5468                 return (EPERM);
5469         }
5470 }
5471
5472 #ifdef DEBUG_VFS_LOCKS
5473 int vfs_badlock_ddb = 1;        /* Drop into debugger on violation. */
5474 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_ddb, CTLFLAG_RW, &vfs_badlock_ddb, 0,
5475     "Drop into debugger on lock violation");
5476
5477 int vfs_badlock_mutex = 1;      /* Check for interlock across VOPs. */
5478 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_mutex, CTLFLAG_RW, &vfs_badlock_mutex,
5479     0, "Check for interlock across VOPs");
5480
5481 int vfs_badlock_print = 1;      /* Print lock violations. */
5482 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_print, CTLFLAG_RW, &vfs_badlock_print,
5483     0, "Print lock violations");
5484
5485 int vfs_badlock_vnode = 1;      /* Print vnode details on lock violations. */
5486 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_vnode, CTLFLAG_RW, &vfs_badlock_vnode,
5487     0, "Print vnode details on lock violations");
5488
5489 #ifdef KDB
5490 int vfs_badlock_backtrace = 1;  /* Print backtrace at lock violations. */
5491 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_backtrace, CTLFLAG_RW,
5492     &vfs_badlock_backtrace, 0, "Print backtrace at lock violations");
5493 #endif
5494
5495 static void
5496 vfs_badlock(const char *msg, const char *str, struct vnode *vp)
5497 {
5498
5499 #ifdef KDB
5500         if (vfs_badlock_backtrace)
5501                 kdb_backtrace();
5502 #endif
5503         if (vfs_badlock_vnode)
5504                 vn_printf(vp, "vnode ");
5505         if (vfs_badlock_print)
5506                 printf("%s: %p %s\n", str, (void *)vp, msg);
5507         if (vfs_badlock_ddb)
5508                 kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
5509 }
5510
5511 void
5512 assert_vi_locked(struct vnode *vp, const char *str)
5513 {
5514
5515         if (vfs_badlock_mutex && !mtx_owned(VI_MTX(vp)))
5516                 vfs_badlock("interlock is not locked but should be", str, vp);
5517 }
5518
5519 void
5520 assert_vi_unlocked(struct vnode *vp, const char *str)
5521 {
5522
5523         if (vfs_badlock_mutex && mtx_owned(VI_MTX(vp)))
5524                 vfs_badlock("interlock is locked but should not be", str, vp);
5525 }
5526
5527 void
5528 assert_vop_locked(struct vnode *vp, const char *str)
5529 {
5530         if (KERNEL_PANICKED() || vp == NULL)
5531                 return;
5532
5533 #ifdef WITNESS
5534         if ((vp->v_irflag & VIRF_CROSSMP) == 0 &&
5535             witness_is_owned(&vp->v_vnlock->lock_object) == -1)
5536 #else
5537         int locked = VOP_ISLOCKED(vp);
5538         if (locked == 0 || locked == LK_EXCLOTHER)
5539 #endif
5540                 vfs_badlock("is not locked but should be", str, vp);
5541 }
5542
5543 void
5544 assert_vop_unlocked(struct vnode *vp, const char *str)
5545 {
5546         if (KERNEL_PANICKED() || vp == NULL)
5547                 return;
5548
5549 #ifdef WITNESS
5550         if ((vp->v_irflag & VIRF_CROSSMP) == 0 &&
5551             witness_is_owned(&vp->v_vnlock->lock_object) == 1)
5552 #else
5553         if (VOP_ISLOCKED(vp) == LK_EXCLUSIVE)
5554 #endif
5555                 vfs_badlock("is locked but should not be", str, vp);
5556 }
5557
5558 void
5559 assert_vop_elocked(struct vnode *vp, const char *str)
5560 {
5561         if (KERNEL_PANICKED() || vp == NULL)
5562                 return;
5563
5564         if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE)
5565                 vfs_badlock("is not exclusive locked but should be", str, vp);
5566 }
5567 #endif /* DEBUG_VFS_LOCKS */
5568
5569 void
5570 vop_rename_fail(struct vop_rename_args *ap)
5571 {
5572
5573         if (ap->a_tvp != NULL)
5574                 vput(ap->a_tvp);
5575         if (ap->a_tdvp == ap->a_tvp)
5576                 vrele(ap->a_tdvp);
5577         else
5578                 vput(ap->a_tdvp);
5579         vrele(ap->a_fdvp);
5580         vrele(ap->a_fvp);
5581 }
5582
5583 void
5584 vop_rename_pre(void *ap)
5585 {
5586         struct vop_rename_args *a = ap;
5587
5588 #ifdef DEBUG_VFS_LOCKS
5589         if (a->a_tvp)
5590                 ASSERT_VI_UNLOCKED(a->a_tvp, "VOP_RENAME");
5591         ASSERT_VI_UNLOCKED(a->a_tdvp, "VOP_RENAME");
5592         ASSERT_VI_UNLOCKED(a->a_fvp, "VOP_RENAME");
5593         ASSERT_VI_UNLOCKED(a->a_fdvp, "VOP_RENAME");
5594
5595         /* Check the source (from). */
5596         if (a->a_tdvp->v_vnlock != a->a_fdvp->v_vnlock &&
5597             (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fdvp->v_vnlock))
5598                 ASSERT_VOP_UNLOCKED(a->a_fdvp, "vop_rename: fdvp locked");
5599         if (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fvp->v_vnlock)
5600                 ASSERT_VOP_UNLOCKED(a->a_fvp, "vop_rename: fvp locked");
5601
5602         /* Check the target. */
5603         if (a->a_tvp)
5604                 ASSERT_VOP_LOCKED(a->a_tvp, "vop_rename: tvp not locked");
5605         ASSERT_VOP_LOCKED(a->a_tdvp, "vop_rename: tdvp not locked");
5606 #endif
5607         /*
5608          * It may be tempting to add vn_seqc_write_begin/end calls here and
5609          * in vop_rename_post but that's not going to work out since some
5610          * filesystems relookup vnodes mid-rename. This is probably a bug.
5611          *
5612          * For now filesystems are expected to do the relevant calls after they
5613          * decide what vnodes to operate on.
5614          */
5615         if (a->a_tdvp != a->a_fdvp)
5616                 vhold(a->a_fdvp);
5617         if (a->a_tvp != a->a_fvp)
5618                 vhold(a->a_fvp);
5619         vhold(a->a_tdvp);
5620         if (a->a_tvp)
5621                 vhold(a->a_tvp);
5622 }
5623
5624 #ifdef DEBUG_VFS_LOCKS
5625 void
5626 vop_fplookup_vexec_debugpre(void *ap __unused)
5627 {
5628
5629         VFS_SMR_ASSERT_ENTERED();
5630 }
5631
5632 void
5633 vop_fplookup_vexec_debugpost(void *ap __unused, int rc __unused)
5634 {
5635
5636         VFS_SMR_ASSERT_ENTERED();
5637 }
5638
5639 void
5640 vop_fplookup_symlink_debugpre(void *ap __unused)
5641 {
5642
5643         VFS_SMR_ASSERT_ENTERED();
5644 }
5645
5646 void
5647 vop_fplookup_symlink_debugpost(void *ap __unused, int rc __unused)
5648 {
5649
5650         VFS_SMR_ASSERT_ENTERED();
5651 }
5652
5653 static void
5654 vop_fsync_debugprepost(struct vnode *vp, const char *name)
5655 {
5656         if (vp->v_type == VCHR)
5657                 ;
5658         else if (MNT_EXTENDED_SHARED(vp->v_mount))
5659                 ASSERT_VOP_LOCKED(vp, name);
5660         else
5661                 ASSERT_VOP_ELOCKED(vp, name);
5662 }
5663
5664 void
5665 vop_fsync_debugpre(void *a)
5666 {
5667         struct vop_fsync_args *ap;
5668
5669         ap = a;
5670         vop_fsync_debugprepost(ap->a_vp, "fsync");
5671 }
5672
5673 void
5674 vop_fsync_debugpost(void *a, int rc __unused)
5675 {
5676         struct vop_fsync_args *ap;
5677
5678         ap = a;
5679         vop_fsync_debugprepost(ap->a_vp, "fsync");
5680 }
5681
5682 void
5683 vop_fdatasync_debugpre(void *a)
5684 {
5685         struct vop_fdatasync_args *ap;
5686
5687         ap = a;
5688         vop_fsync_debugprepost(ap->a_vp, "fsync");
5689 }
5690
5691 void
5692 vop_fdatasync_debugpost(void *a, int rc __unused)
5693 {
5694         struct vop_fdatasync_args *ap;
5695
5696         ap = a;
5697         vop_fsync_debugprepost(ap->a_vp, "fsync");
5698 }
5699
5700 void
5701 vop_strategy_debugpre(void *ap)
5702 {
5703         struct vop_strategy_args *a;
5704         struct buf *bp;
5705
5706         a = ap;
5707         bp = a->a_bp;
5708
5709         /*
5710          * Cluster ops lock their component buffers but not the IO container.
5711          */
5712         if ((bp->b_flags & B_CLUSTER) != 0)
5713                 return;
5714
5715         if (!KERNEL_PANICKED() && !BUF_ISLOCKED(bp)) {
5716                 if (vfs_badlock_print)
5717                         printf(
5718                             "VOP_STRATEGY: bp is not locked but should be\n");
5719                 if (vfs_badlock_ddb)
5720                         kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
5721         }
5722 }
5723
5724 void
5725 vop_lock_debugpre(void *ap)
5726 {
5727         struct vop_lock1_args *a = ap;
5728
5729         if ((a->a_flags & LK_INTERLOCK) == 0)
5730                 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
5731         else
5732                 ASSERT_VI_LOCKED(a->a_vp, "VOP_LOCK");
5733 }
5734
5735 void
5736 vop_lock_debugpost(void *ap, int rc)
5737 {
5738         struct vop_lock1_args *a = ap;
5739
5740         ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
5741         if (rc == 0 && (a->a_flags & LK_EXCLOTHER) == 0)
5742                 ASSERT_VOP_LOCKED(a->a_vp, "VOP_LOCK");
5743 }
5744
5745 void
5746 vop_unlock_debugpre(void *ap)
5747 {
5748         struct vop_unlock_args *a = ap;
5749
5750         ASSERT_VOP_LOCKED(a->a_vp, "VOP_UNLOCK");
5751 }
5752
5753 void
5754 vop_need_inactive_debugpre(void *ap)
5755 {
5756         struct vop_need_inactive_args *a = ap;
5757
5758         ASSERT_VI_LOCKED(a->a_vp, "VOP_NEED_INACTIVE");
5759 }
5760
5761 void
5762 vop_need_inactive_debugpost(void *ap, int rc)
5763 {
5764         struct vop_need_inactive_args *a = ap;
5765
5766         ASSERT_VI_LOCKED(a->a_vp, "VOP_NEED_INACTIVE");
5767 }
5768 #endif
5769
5770 void
5771 vop_create_pre(void *ap)
5772 {
5773         struct vop_create_args *a;
5774         struct vnode *dvp;
5775
5776         a = ap;
5777         dvp = a->a_dvp;
5778         vn_seqc_write_begin(dvp);
5779 }
5780
5781 void
5782 vop_create_post(void *ap, int rc)
5783 {
5784         struct vop_create_args *a;
5785         struct vnode *dvp;
5786
5787         a = ap;
5788         dvp = a->a_dvp;
5789         vn_seqc_write_end(dvp);
5790         if (!rc)
5791                 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE);
5792 }
5793
5794 void
5795 vop_whiteout_pre(void *ap)
5796 {
5797         struct vop_whiteout_args *a;
5798         struct vnode *dvp;
5799
5800         a = ap;
5801         dvp = a->a_dvp;
5802         vn_seqc_write_begin(dvp);
5803 }
5804
5805 void
5806 vop_whiteout_post(void *ap, int rc)
5807 {
5808         struct vop_whiteout_args *a;
5809         struct vnode *dvp;
5810
5811         a = ap;
5812         dvp = a->a_dvp;
5813         vn_seqc_write_end(dvp);
5814 }
5815
5816 void
5817 vop_deleteextattr_pre(void *ap)
5818 {
5819         struct vop_deleteextattr_args *a;
5820         struct vnode *vp;
5821
5822         a = ap;
5823         vp = a->a_vp;
5824         vn_seqc_write_begin(vp);
5825 }
5826
5827 void
5828 vop_deleteextattr_post(void *ap, int rc)
5829 {
5830         struct vop_deleteextattr_args *a;
5831         struct vnode *vp;
5832
5833         a = ap;
5834         vp = a->a_vp;
5835         vn_seqc_write_end(vp);
5836         if (!rc)
5837                 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
5838 }
5839
5840 void
5841 vop_link_pre(void *ap)
5842 {
5843         struct vop_link_args *a;
5844         struct vnode *vp, *tdvp;
5845
5846         a = ap;
5847         vp = a->a_vp;
5848         tdvp = a->a_tdvp;
5849         vn_seqc_write_begin(vp);
5850         vn_seqc_write_begin(tdvp);
5851 }
5852
5853 void
5854 vop_link_post(void *ap, int rc)
5855 {
5856         struct vop_link_args *a;
5857         struct vnode *vp, *tdvp;
5858
5859         a = ap;
5860         vp = a->a_vp;
5861         tdvp = a->a_tdvp;
5862         vn_seqc_write_end(vp);
5863         vn_seqc_write_end(tdvp);
5864         if (!rc) {
5865                 VFS_KNOTE_LOCKED(vp, NOTE_LINK);
5866                 VFS_KNOTE_LOCKED(tdvp, NOTE_WRITE);
5867         }
5868 }
5869
5870 void
5871 vop_mkdir_pre(void *ap)
5872 {
5873         struct vop_mkdir_args *a;
5874         struct vnode *dvp;
5875
5876         a = ap;
5877         dvp = a->a_dvp;
5878         vn_seqc_write_begin(dvp);
5879 }
5880
5881 void
5882 vop_mkdir_post(void *ap, int rc)
5883 {
5884         struct vop_mkdir_args *a;
5885         struct vnode *dvp;
5886
5887         a = ap;
5888         dvp = a->a_dvp;
5889         vn_seqc_write_end(dvp);
5890         if (!rc)
5891                 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE | NOTE_LINK);
5892 }
5893
5894 #ifdef DEBUG_VFS_LOCKS
5895 void
5896 vop_mkdir_debugpost(void *ap, int rc)
5897 {
5898         struct vop_mkdir_args *a;
5899
5900         a = ap;
5901         if (!rc)
5902                 cache_validate(a->a_dvp, *a->a_vpp, a->a_cnp);
5903 }
5904 #endif
5905
5906 void
5907 vop_mknod_pre(void *ap)
5908 {
5909         struct vop_mknod_args *a;
5910         struct vnode *dvp;
5911
5912         a = ap;
5913         dvp = a->a_dvp;
5914         vn_seqc_write_begin(dvp);
5915 }
5916
5917 void
5918 vop_mknod_post(void *ap, int rc)
5919 {
5920         struct vop_mknod_args *a;
5921         struct vnode *dvp;
5922
5923         a = ap;
5924         dvp = a->a_dvp;
5925         vn_seqc_write_end(dvp);
5926         if (!rc)
5927                 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE);
5928 }
5929
5930 void
5931 vop_reclaim_post(void *ap, int rc)
5932 {
5933         struct vop_reclaim_args *a;
5934         struct vnode *vp;
5935
5936         a = ap;
5937         vp = a->a_vp;
5938         ASSERT_VOP_IN_SEQC(vp);
5939         if (!rc)
5940                 VFS_KNOTE_LOCKED(vp, NOTE_REVOKE);
5941 }
5942
5943 void
5944 vop_remove_pre(void *ap)
5945 {
5946         struct vop_remove_args *a;
5947         struct vnode *dvp, *vp;
5948
5949         a = ap;
5950         dvp = a->a_dvp;
5951         vp = a->a_vp;
5952         vn_seqc_write_begin(dvp);
5953         vn_seqc_write_begin(vp);
5954 }
5955
5956 void
5957 vop_remove_post(void *ap, int rc)
5958 {
5959         struct vop_remove_args *a;
5960         struct vnode *dvp, *vp;
5961
5962         a = ap;
5963         dvp = a->a_dvp;
5964         vp = a->a_vp;
5965         vn_seqc_write_end(dvp);
5966         vn_seqc_write_end(vp);
5967         if (!rc) {
5968                 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE);
5969                 VFS_KNOTE_LOCKED(vp, NOTE_DELETE);
5970         }
5971 }
5972
5973 void
5974 vop_rename_post(void *ap, int rc)
5975 {
5976         struct vop_rename_args *a = ap;
5977         long hint;
5978
5979         if (!rc) {
5980                 hint = NOTE_WRITE;
5981                 if (a->a_fdvp == a->a_tdvp) {
5982                         if (a->a_tvp != NULL && a->a_tvp->v_type == VDIR)
5983                                 hint |= NOTE_LINK;
5984                         VFS_KNOTE_UNLOCKED(a->a_fdvp, hint);
5985                         VFS_KNOTE_UNLOCKED(a->a_tdvp, hint);
5986                 } else {
5987                         hint |= NOTE_EXTEND;
5988                         if (a->a_fvp->v_type == VDIR)
5989                                 hint |= NOTE_LINK;
5990                         VFS_KNOTE_UNLOCKED(a->a_fdvp, hint);
5991
5992                         if (a->a_fvp->v_type == VDIR && a->a_tvp != NULL &&
5993                             a->a_tvp->v_type == VDIR)
5994                                 hint &= ~NOTE_LINK;
5995                         VFS_KNOTE_UNLOCKED(a->a_tdvp, hint);
5996                 }
5997
5998                 VFS_KNOTE_UNLOCKED(a->a_fvp, NOTE_RENAME);
5999                 if (a->a_tvp)
6000                         VFS_KNOTE_UNLOCKED(a->a_tvp, NOTE_DELETE);
6001         }
6002         if (a->a_tdvp != a->a_fdvp)
6003                 vdrop(a->a_fdvp);
6004         if (a->a_tvp != a->a_fvp)
6005                 vdrop(a->a_fvp);
6006         vdrop(a->a_tdvp);
6007         if (a->a_tvp)
6008                 vdrop(a->a_tvp);
6009 }
6010
6011 void
6012 vop_rmdir_pre(void *ap)
6013 {
6014         struct vop_rmdir_args *a;
6015         struct vnode *dvp, *vp;
6016
6017         a = ap;
6018         dvp = a->a_dvp;
6019         vp = a->a_vp;
6020         vn_seqc_write_begin(dvp);
6021         vn_seqc_write_begin(vp);
6022 }
6023
6024 void
6025 vop_rmdir_post(void *ap, int rc)
6026 {
6027         struct vop_rmdir_args *a;
6028         struct vnode *dvp, *vp;
6029
6030         a = ap;
6031         dvp = a->a_dvp;
6032         vp = a->a_vp;
6033         vn_seqc_write_end(dvp);
6034         vn_seqc_write_end(vp);
6035         if (!rc) {
6036                 vp->v_vflag |= VV_UNLINKED;
6037                 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE | NOTE_LINK);
6038                 VFS_KNOTE_LOCKED(vp, NOTE_DELETE);
6039         }
6040 }
6041
6042 void
6043 vop_setattr_pre(void *ap)
6044 {
6045         struct vop_setattr_args *a;
6046         struct vnode *vp;
6047
6048         a = ap;
6049         vp = a->a_vp;
6050         vn_seqc_write_begin(vp);
6051 }
6052
6053 void
6054 vop_setattr_post(void *ap, int rc)
6055 {
6056         struct vop_setattr_args *a;
6057         struct vnode *vp;
6058
6059         a = ap;
6060         vp = a->a_vp;
6061         vn_seqc_write_end(vp);
6062         if (!rc)
6063                 VFS_KNOTE_LOCKED(vp, NOTE_ATTRIB);
6064 }
6065
6066 void
6067 vop_setacl_pre(void *ap)
6068 {
6069         struct vop_setacl_args *a;
6070         struct vnode *vp;
6071
6072         a = ap;
6073         vp = a->a_vp;
6074         vn_seqc_write_begin(vp);
6075 }
6076
6077 void
6078 vop_setacl_post(void *ap, int rc __unused)
6079 {
6080         struct vop_setacl_args *a;
6081         struct vnode *vp;
6082
6083         a = ap;
6084         vp = a->a_vp;
6085         vn_seqc_write_end(vp);
6086 }
6087
6088 void
6089 vop_setextattr_pre(void *ap)
6090 {
6091         struct vop_setextattr_args *a;
6092         struct vnode *vp;
6093
6094         a = ap;
6095         vp = a->a_vp;
6096         vn_seqc_write_begin(vp);
6097 }
6098
6099 void
6100 vop_setextattr_post(void *ap, int rc)
6101 {
6102         struct vop_setextattr_args *a;
6103         struct vnode *vp;
6104
6105         a = ap;
6106         vp = a->a_vp;
6107         vn_seqc_write_end(vp);
6108         if (!rc)
6109                 VFS_KNOTE_LOCKED(vp, NOTE_ATTRIB);
6110 }
6111
6112 void
6113 vop_symlink_pre(void *ap)
6114 {
6115         struct vop_symlink_args *a;
6116         struct vnode *dvp;
6117
6118         a = ap;
6119         dvp = a->a_dvp;
6120         vn_seqc_write_begin(dvp);
6121 }
6122
6123 void
6124 vop_symlink_post(void *ap, int rc)
6125 {
6126         struct vop_symlink_args *a;
6127         struct vnode *dvp;
6128
6129         a = ap;
6130         dvp = a->a_dvp;
6131         vn_seqc_write_end(dvp);
6132         if (!rc)
6133                 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE);
6134 }
6135
6136 void
6137 vop_open_post(void *ap, int rc)
6138 {
6139         struct vop_open_args *a = ap;
6140
6141         if (!rc)
6142                 VFS_KNOTE_LOCKED(a->a_vp, NOTE_OPEN);
6143 }
6144
6145 void
6146 vop_close_post(void *ap, int rc)
6147 {
6148         struct vop_close_args *a = ap;
6149
6150         if (!rc && (a->a_cred != NOCRED || /* filter out revokes */
6151             !VN_IS_DOOMED(a->a_vp))) {
6152                 VFS_KNOTE_LOCKED(a->a_vp, (a->a_fflag & FWRITE) != 0 ?
6153                     NOTE_CLOSE_WRITE : NOTE_CLOSE);
6154         }
6155 }
6156
6157 void
6158 vop_read_post(void *ap, int rc)
6159 {
6160         struct vop_read_args *a = ap;
6161
6162         if (!rc)
6163                 VFS_KNOTE_LOCKED(a->a_vp, NOTE_READ);
6164 }
6165
6166 void
6167 vop_read_pgcache_post(void *ap, int rc)
6168 {
6169         struct vop_read_pgcache_args *a = ap;
6170
6171         if (!rc)
6172                 VFS_KNOTE_UNLOCKED(a->a_vp, NOTE_READ);
6173 }
6174
6175 void
6176 vop_readdir_post(void *ap, int rc)
6177 {
6178         struct vop_readdir_args *a = ap;
6179
6180         if (!rc)
6181                 VFS_KNOTE_LOCKED(a->a_vp, NOTE_READ);
6182 }
6183
6184 static struct knlist fs_knlist;
6185
6186 static void
6187 vfs_event_init(void *arg)
6188 {
6189         knlist_init_mtx(&fs_knlist, NULL);
6190 }
6191 /* XXX - correct order? */
6192 SYSINIT(vfs_knlist, SI_SUB_VFS, SI_ORDER_ANY, vfs_event_init, NULL);
6193
6194 void
6195 vfs_event_signal(fsid_t *fsid, uint32_t event, intptr_t data __unused)
6196 {
6197
6198         KNOTE_UNLOCKED(&fs_knlist, event);
6199 }
6200
6201 static int      filt_fsattach(struct knote *kn);
6202 static void     filt_fsdetach(struct knote *kn);
6203 static int      filt_fsevent(struct knote *kn, long hint);
6204
6205 struct filterops fs_filtops = {
6206         .f_isfd = 0,
6207         .f_attach = filt_fsattach,
6208         .f_detach = filt_fsdetach,
6209         .f_event = filt_fsevent
6210 };
6211
6212 static int
6213 filt_fsattach(struct knote *kn)
6214 {
6215
6216         kn->kn_flags |= EV_CLEAR;
6217         knlist_add(&fs_knlist, kn, 0);
6218         return (0);
6219 }
6220
6221 static void
6222 filt_fsdetach(struct knote *kn)
6223 {
6224
6225         knlist_remove(&fs_knlist, kn, 0);
6226 }
6227
6228 static int
6229 filt_fsevent(struct knote *kn, long hint)
6230 {
6231
6232         kn->kn_fflags |= hint;
6233         return (kn->kn_fflags != 0);
6234 }
6235
6236 static int
6237 sysctl_vfs_ctl(SYSCTL_HANDLER_ARGS)
6238 {
6239         struct vfsidctl vc;
6240         int error;
6241         struct mount *mp;
6242
6243         error = SYSCTL_IN(req, &vc, sizeof(vc));
6244         if (error)
6245                 return (error);
6246         if (vc.vc_vers != VFS_CTL_VERS1)
6247                 return (EINVAL);
6248         mp = vfs_getvfs(&vc.vc_fsid);
6249         if (mp == NULL)
6250                 return (ENOENT);
6251         /* ensure that a specific sysctl goes to the right filesystem. */
6252         if (strcmp(vc.vc_fstypename, "*") != 0 &&
6253             strcmp(vc.vc_fstypename, mp->mnt_vfc->vfc_name) != 0) {
6254                 vfs_rel(mp);
6255                 return (EINVAL);
6256         }
6257         VCTLTOREQ(&vc, req);
6258         error = VFS_SYSCTL(mp, vc.vc_op, req);
6259         vfs_rel(mp);
6260         return (error);
6261 }
6262
6263 SYSCTL_PROC(_vfs, OID_AUTO, ctl, CTLTYPE_OPAQUE | CTLFLAG_MPSAFE | CTLFLAG_WR,
6264     NULL, 0, sysctl_vfs_ctl, "",
6265     "Sysctl by fsid");
6266
6267 /*
6268  * Function to initialize a va_filerev field sensibly.
6269  * XXX: Wouldn't a random number make a lot more sense ??
6270  */
6271 u_quad_t
6272 init_va_filerev(void)
6273 {
6274         struct bintime bt;
6275
6276         getbinuptime(&bt);
6277         return (((u_quad_t)bt.sec << 32LL) | (bt.frac >> 32LL));
6278 }
6279
6280 static int      filt_vfsread(struct knote *kn, long hint);
6281 static int      filt_vfswrite(struct knote *kn, long hint);
6282 static int      filt_vfsvnode(struct knote *kn, long hint);
6283 static void     filt_vfsdetach(struct knote *kn);
6284 static struct filterops vfsread_filtops = {
6285         .f_isfd = 1,
6286         .f_detach = filt_vfsdetach,
6287         .f_event = filt_vfsread
6288 };
6289 static struct filterops vfswrite_filtops = {
6290         .f_isfd = 1,
6291         .f_detach = filt_vfsdetach,
6292         .f_event = filt_vfswrite
6293 };
6294 static struct filterops vfsvnode_filtops = {
6295         .f_isfd = 1,
6296         .f_detach = filt_vfsdetach,
6297         .f_event = filt_vfsvnode
6298 };
6299
6300 static void
6301 vfs_knllock(void *arg)
6302 {
6303         struct vnode *vp = arg;
6304
6305         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
6306 }
6307
6308 static void
6309 vfs_knlunlock(void *arg)
6310 {
6311         struct vnode *vp = arg;
6312
6313         VOP_UNLOCK(vp);
6314 }
6315
6316 static void
6317 vfs_knl_assert_lock(void *arg, int what)
6318 {
6319 #ifdef DEBUG_VFS_LOCKS
6320         struct vnode *vp = arg;
6321
6322         if (what == LA_LOCKED)
6323                 ASSERT_VOP_LOCKED(vp, "vfs_knl_assert_locked");
6324         else
6325                 ASSERT_VOP_UNLOCKED(vp, "vfs_knl_assert_unlocked");
6326 #endif
6327 }
6328
6329 int
6330 vfs_kqfilter(struct vop_kqfilter_args *ap)
6331 {
6332         struct vnode *vp = ap->a_vp;
6333         struct knote *kn = ap->a_kn;
6334         struct knlist *knl;
6335
6336         switch (kn->kn_filter) {
6337         case EVFILT_READ:
6338                 kn->kn_fop = &vfsread_filtops;
6339                 break;
6340         case EVFILT_WRITE:
6341                 kn->kn_fop = &vfswrite_filtops;
6342                 break;
6343         case EVFILT_VNODE:
6344                 kn->kn_fop = &vfsvnode_filtops;
6345                 break;
6346         default:
6347                 return (EINVAL);
6348         }
6349
6350         kn->kn_hook = (caddr_t)vp;
6351
6352         v_addpollinfo(vp);
6353         if (vp->v_pollinfo == NULL)
6354                 return (ENOMEM);
6355         knl = &vp->v_pollinfo->vpi_selinfo.si_note;
6356         vhold(vp);
6357         knlist_add(knl, kn, 0);
6358
6359         return (0);
6360 }
6361
6362 /*
6363  * Detach knote from vnode
6364  */
6365 static void
6366 filt_vfsdetach(struct knote *kn)
6367 {
6368         struct vnode *vp = (struct vnode *)kn->kn_hook;
6369
6370         KASSERT(vp->v_pollinfo != NULL, ("Missing v_pollinfo"));
6371         knlist_remove(&vp->v_pollinfo->vpi_selinfo.si_note, kn, 0);
6372         vdrop(vp);
6373 }
6374
6375 /*ARGSUSED*/
6376 static int
6377 filt_vfsread(struct knote *kn, long hint)
6378 {
6379         struct vnode *vp = (struct vnode *)kn->kn_hook;
6380         struct vattr va;
6381         int res;
6382
6383         /*
6384          * filesystem is gone, so set the EOF flag and schedule
6385          * the knote for deletion.
6386          */
6387         if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD)) {
6388                 VI_LOCK(vp);
6389                 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
6390                 VI_UNLOCK(vp);
6391                 return (1);
6392         }
6393
6394         if (VOP_GETATTR(vp, &va, curthread->td_ucred))
6395                 return (0);
6396
6397         VI_LOCK(vp);
6398         kn->kn_data = va.va_size - kn->kn_fp->f_offset;
6399         res = (kn->kn_sfflags & NOTE_FILE_POLL) != 0 || kn->kn_data != 0;
6400         VI_UNLOCK(vp);
6401         return (res);
6402 }
6403
6404 /*ARGSUSED*/
6405 static int
6406 filt_vfswrite(struct knote *kn, long hint)
6407 {
6408         struct vnode *vp = (struct vnode *)kn->kn_hook;
6409
6410         VI_LOCK(vp);
6411
6412         /*
6413          * filesystem is gone, so set the EOF flag and schedule
6414          * the knote for deletion.
6415          */
6416         if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD))
6417                 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
6418
6419         kn->kn_data = 0;
6420         VI_UNLOCK(vp);
6421         return (1);
6422 }
6423
6424 static int
6425 filt_vfsvnode(struct knote *kn, long hint)
6426 {
6427         struct vnode *vp = (struct vnode *)kn->kn_hook;
6428         int res;
6429
6430         VI_LOCK(vp);
6431         if (kn->kn_sfflags & hint)
6432                 kn->kn_fflags |= hint;
6433         if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD)) {
6434                 kn->kn_flags |= EV_EOF;
6435                 VI_UNLOCK(vp);
6436                 return (1);
6437         }
6438         res = (kn->kn_fflags != 0);
6439         VI_UNLOCK(vp);
6440         return (res);
6441 }
6442
6443 int
6444 vfs_read_dirent(struct vop_readdir_args *ap, struct dirent *dp, off_t off)
6445 {
6446         int error;
6447
6448         if (dp->d_reclen > ap->a_uio->uio_resid)
6449                 return (ENAMETOOLONG);
6450         error = uiomove(dp, dp->d_reclen, ap->a_uio);
6451         if (error) {
6452                 if (ap->a_ncookies != NULL) {
6453                         if (ap->a_cookies != NULL)
6454                                 free(ap->a_cookies, M_TEMP);
6455                         ap->a_cookies = NULL;
6456                         *ap->a_ncookies = 0;
6457                 }
6458                 return (error);
6459         }
6460         if (ap->a_ncookies == NULL)
6461                 return (0);
6462
6463         KASSERT(ap->a_cookies,
6464             ("NULL ap->a_cookies value with non-NULL ap->a_ncookies!"));
6465
6466         *ap->a_cookies = realloc(*ap->a_cookies,
6467             (*ap->a_ncookies + 1) * sizeof(u_long), M_TEMP, M_WAITOK | M_ZERO);
6468         (*ap->a_cookies)[*ap->a_ncookies] = off;
6469         *ap->a_ncookies += 1;
6470         return (0);
6471 }
6472
6473 /*
6474  * The purpose of this routine is to remove granularity from accmode_t,
6475  * reducing it into standard unix access bits - VEXEC, VREAD, VWRITE,
6476  * VADMIN and VAPPEND.
6477  *
6478  * If it returns 0, the caller is supposed to continue with the usual
6479  * access checks using 'accmode' as modified by this routine.  If it
6480  * returns nonzero value, the caller is supposed to return that value
6481  * as errno.
6482  *
6483  * Note that after this routine runs, accmode may be zero.
6484  */
6485 int
6486 vfs_unixify_accmode(accmode_t *accmode)
6487 {
6488         /*
6489          * There is no way to specify explicit "deny" rule using
6490          * file mode or POSIX.1e ACLs.
6491          */
6492         if (*accmode & VEXPLICIT_DENY) {
6493                 *accmode = 0;
6494                 return (0);
6495         }
6496
6497         /*
6498          * None of these can be translated into usual access bits.
6499          * Also, the common case for NFSv4 ACLs is to not contain
6500          * either of these bits. Caller should check for VWRITE
6501          * on the containing directory instead.
6502          */
6503         if (*accmode & (VDELETE_CHILD | VDELETE))
6504                 return (EPERM);
6505
6506         if (*accmode & VADMIN_PERMS) {
6507                 *accmode &= ~VADMIN_PERMS;
6508                 *accmode |= VADMIN;
6509         }
6510
6511         /*
6512          * There is no way to deny VREAD_ATTRIBUTES, VREAD_ACL
6513          * or VSYNCHRONIZE using file mode or POSIX.1e ACL.
6514          */
6515         *accmode &= ~(VSTAT_PERMS | VSYNCHRONIZE);
6516
6517         return (0);
6518 }
6519
6520 /*
6521  * Clear out a doomed vnode (if any) and replace it with a new one as long
6522  * as the fs is not being unmounted. Return the root vnode to the caller.
6523  */
6524 static int __noinline
6525 vfs_cache_root_fallback(struct mount *mp, int flags, struct vnode **vpp)
6526 {
6527         struct vnode *vp;
6528         int error;
6529
6530 restart:
6531         if (mp->mnt_rootvnode != NULL) {
6532                 MNT_ILOCK(mp);
6533                 vp = mp->mnt_rootvnode;
6534                 if (vp != NULL) {
6535                         if (!VN_IS_DOOMED(vp)) {
6536                                 vrefact(vp);
6537                                 MNT_IUNLOCK(mp);
6538                                 error = vn_lock(vp, flags);
6539                                 if (error == 0) {
6540                                         *vpp = vp;
6541                                         return (0);
6542                                 }
6543                                 vrele(vp);
6544                                 goto restart;
6545                         }
6546                         /*
6547                          * Clear the old one.
6548                          */
6549                         mp->mnt_rootvnode = NULL;
6550                 }
6551                 MNT_IUNLOCK(mp);
6552                 if (vp != NULL) {
6553                         vfs_op_barrier_wait(mp);
6554                         vrele(vp);
6555                 }
6556         }
6557         error = VFS_CACHEDROOT(mp, flags, vpp);
6558         if (error != 0)
6559                 return (error);
6560         if (mp->mnt_vfs_ops == 0) {
6561                 MNT_ILOCK(mp);
6562                 if (mp->mnt_vfs_ops != 0) {
6563                         MNT_IUNLOCK(mp);
6564                         return (0);
6565                 }
6566                 if (mp->mnt_rootvnode == NULL) {
6567                         vrefact(*vpp);
6568                         mp->mnt_rootvnode = *vpp;
6569                 } else {
6570                         if (mp->mnt_rootvnode != *vpp) {
6571                                 if (!VN_IS_DOOMED(mp->mnt_rootvnode)) {
6572                                         panic("%s: mismatch between vnode returned "
6573                                             " by VFS_CACHEDROOT and the one cached "
6574                                             " (%p != %p)",
6575                                             __func__, *vpp, mp->mnt_rootvnode);
6576                                 }
6577                         }
6578                 }
6579                 MNT_IUNLOCK(mp);
6580         }
6581         return (0);
6582 }
6583
6584 int
6585 vfs_cache_root(struct mount *mp, int flags, struct vnode **vpp)
6586 {
6587         struct mount_pcpu *mpcpu;
6588         struct vnode *vp;
6589         int error;
6590
6591         if (!vfs_op_thread_enter(mp, mpcpu))
6592                 return (vfs_cache_root_fallback(mp, flags, vpp));
6593         vp = atomic_load_ptr(&mp->mnt_rootvnode);
6594         if (vp == NULL || VN_IS_DOOMED(vp)) {
6595                 vfs_op_thread_exit(mp, mpcpu);
6596                 return (vfs_cache_root_fallback(mp, flags, vpp));
6597         }
6598         vrefact(vp);
6599         vfs_op_thread_exit(mp, mpcpu);
6600         error = vn_lock(vp, flags);
6601         if (error != 0) {
6602                 vrele(vp);
6603                 return (vfs_cache_root_fallback(mp, flags, vpp));
6604         }
6605         *vpp = vp;
6606         return (0);
6607 }
6608
6609 struct vnode *
6610 vfs_cache_root_clear(struct mount *mp)
6611 {
6612         struct vnode *vp;
6613
6614         /*
6615          * ops > 0 guarantees there is nobody who can see this vnode
6616          */
6617         MPASS(mp->mnt_vfs_ops > 0);
6618         vp = mp->mnt_rootvnode;
6619         if (vp != NULL)
6620                 vn_seqc_write_begin(vp);
6621         mp->mnt_rootvnode = NULL;
6622         return (vp);
6623 }
6624
6625 void
6626 vfs_cache_root_set(struct mount *mp, struct vnode *vp)
6627 {
6628
6629         MPASS(mp->mnt_vfs_ops > 0);
6630         vrefact(vp);
6631         mp->mnt_rootvnode = vp;
6632 }
6633
6634 /*
6635  * These are helper functions for filesystems to traverse all
6636  * their vnodes.  See MNT_VNODE_FOREACH_ALL() in sys/mount.h.
6637  *
6638  * This interface replaces MNT_VNODE_FOREACH.
6639  */
6640
6641 struct vnode *
6642 __mnt_vnode_next_all(struct vnode **mvp, struct mount *mp)
6643 {
6644         struct vnode *vp;
6645
6646         maybe_yield();
6647         MNT_ILOCK(mp);
6648         KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6649         for (vp = TAILQ_NEXT(*mvp, v_nmntvnodes); vp != NULL;
6650             vp = TAILQ_NEXT(vp, v_nmntvnodes)) {
6651                 /* Allow a racy peek at VIRF_DOOMED to save a lock acquisition. */
6652                 if (vp->v_type == VMARKER || VN_IS_DOOMED(vp))
6653                         continue;
6654                 VI_LOCK(vp);
6655                 if (VN_IS_DOOMED(vp)) {
6656                         VI_UNLOCK(vp);
6657                         continue;
6658                 }
6659                 break;
6660         }
6661         if (vp == NULL) {
6662                 __mnt_vnode_markerfree_all(mvp, mp);
6663                 /* MNT_IUNLOCK(mp); -- done in above function */
6664                 mtx_assert(MNT_MTX(mp), MA_NOTOWNED);
6665                 return (NULL);
6666         }
6667         TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
6668         TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
6669         MNT_IUNLOCK(mp);
6670         return (vp);
6671 }
6672
6673 struct vnode *
6674 __mnt_vnode_first_all(struct vnode **mvp, struct mount *mp)
6675 {
6676         struct vnode *vp;
6677
6678         *mvp = vn_alloc_marker(mp);
6679         MNT_ILOCK(mp);
6680         MNT_REF(mp);
6681
6682         TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
6683                 /* Allow a racy peek at VIRF_DOOMED to save a lock acquisition. */
6684                 if (vp->v_type == VMARKER || VN_IS_DOOMED(vp))
6685                         continue;
6686                 VI_LOCK(vp);
6687                 if (VN_IS_DOOMED(vp)) {
6688                         VI_UNLOCK(vp);
6689                         continue;
6690                 }
6691                 break;
6692         }
6693         if (vp == NULL) {
6694                 MNT_REL(mp);
6695                 MNT_IUNLOCK(mp);
6696                 vn_free_marker(*mvp);
6697                 *mvp = NULL;
6698                 return (NULL);
6699         }
6700         TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
6701         MNT_IUNLOCK(mp);
6702         return (vp);
6703 }
6704
6705 void
6706 __mnt_vnode_markerfree_all(struct vnode **mvp, struct mount *mp)
6707 {
6708
6709         if (*mvp == NULL) {
6710                 MNT_IUNLOCK(mp);
6711                 return;
6712         }
6713
6714         mtx_assert(MNT_MTX(mp), MA_OWNED);
6715
6716         KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6717         TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
6718         MNT_REL(mp);
6719         MNT_IUNLOCK(mp);
6720         vn_free_marker(*mvp);
6721         *mvp = NULL;
6722 }
6723
6724 /*
6725  * These are helper functions for filesystems to traverse their
6726  * lazy vnodes.  See MNT_VNODE_FOREACH_LAZY() in sys/mount.h
6727  */
6728 static void
6729 mnt_vnode_markerfree_lazy(struct vnode **mvp, struct mount *mp)
6730 {
6731
6732         KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6733
6734         MNT_ILOCK(mp);
6735         MNT_REL(mp);
6736         MNT_IUNLOCK(mp);
6737         vn_free_marker(*mvp);
6738         *mvp = NULL;
6739 }
6740
6741 /*
6742  * Relock the mp mount vnode list lock with the vp vnode interlock in the
6743  * conventional lock order during mnt_vnode_next_lazy iteration.
6744  *
6745  * On entry, the mount vnode list lock is held and the vnode interlock is not.
6746  * The list lock is dropped and reacquired.  On success, both locks are held.
6747  * On failure, the mount vnode list lock is held but the vnode interlock is
6748  * not, and the procedure may have yielded.
6749  */
6750 static bool
6751 mnt_vnode_next_lazy_relock(struct vnode *mvp, struct mount *mp,
6752     struct vnode *vp)
6753 {
6754
6755         VNASSERT(mvp->v_mount == mp && mvp->v_type == VMARKER &&
6756             TAILQ_NEXT(mvp, v_lazylist) != NULL, mvp,
6757             ("%s: bad marker", __func__));
6758         VNASSERT(vp->v_mount == mp && vp->v_type != VMARKER, vp,
6759             ("%s: inappropriate vnode", __func__));
6760         ASSERT_VI_UNLOCKED(vp, __func__);
6761         mtx_assert(&mp->mnt_listmtx, MA_OWNED);
6762
6763         TAILQ_REMOVE(&mp->mnt_lazyvnodelist, mvp, v_lazylist);
6764         TAILQ_INSERT_BEFORE(vp, mvp, v_lazylist);
6765
6766         /*
6767          * Note we may be racing against vdrop which transitioned the hold
6768          * count to 0 and now waits for the ->mnt_listmtx lock. This is fine,
6769          * if we are the only user after we get the interlock we will just
6770          * vdrop.
6771          */
6772         vhold(vp);
6773         mtx_unlock(&mp->mnt_listmtx);
6774         VI_LOCK(vp);
6775         if (VN_IS_DOOMED(vp)) {
6776                 VNPASS((vp->v_mflag & VMP_LAZYLIST) == 0, vp);
6777                 goto out_lost;
6778         }
6779         VNPASS(vp->v_mflag & VMP_LAZYLIST, vp);
6780         /*
6781          * There is nothing to do if we are the last user.
6782          */
6783         if (!refcount_release_if_not_last(&vp->v_holdcnt))
6784                 goto out_lost;
6785         mtx_lock(&mp->mnt_listmtx);
6786         return (true);
6787 out_lost:
6788         vdropl(vp);
6789         maybe_yield();
6790         mtx_lock(&mp->mnt_listmtx);
6791         return (false);
6792 }
6793
6794 static struct vnode *
6795 mnt_vnode_next_lazy(struct vnode **mvp, struct mount *mp, mnt_lazy_cb_t *cb,
6796     void *cbarg)
6797 {
6798         struct vnode *vp;
6799
6800         mtx_assert(&mp->mnt_listmtx, MA_OWNED);
6801         KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
6802 restart:
6803         vp = TAILQ_NEXT(*mvp, v_lazylist);
6804         while (vp != NULL) {
6805                 if (vp->v_type == VMARKER) {
6806                         vp = TAILQ_NEXT(vp, v_lazylist);
6807                         continue;
6808                 }
6809                 /*
6810                  * See if we want to process the vnode. Note we may encounter a
6811                  * long string of vnodes we don't care about and hog the list
6812                  * as a result. Check for it and requeue the marker.
6813                  */
6814                 VNPASS(!VN_IS_DOOMED(vp), vp);
6815                 if (!cb(vp, cbarg)) {
6816                         if (!should_yield()) {
6817                                 vp = TAILQ_NEXT(vp, v_lazylist);
6818                                 continue;
6819                         }
6820                         TAILQ_REMOVE(&mp->mnt_lazyvnodelist, *mvp,
6821                             v_lazylist);
6822                         TAILQ_INSERT_AFTER(&mp->mnt_lazyvnodelist, vp, *mvp,
6823                             v_lazylist);
6824                         mtx_unlock(&mp->mnt_listmtx);
6825                         kern_yield(PRI_USER);
6826                         mtx_lock(&mp->mnt_listmtx);
6827                         goto restart;
6828                 }
6829                 /*
6830                  * Try-lock because this is the wrong lock order.
6831                  */
6832                 if (!VI_TRYLOCK(vp) &&
6833                     !mnt_vnode_next_lazy_relock(*mvp, mp, vp))
6834                         goto restart;
6835                 KASSERT(vp->v_type != VMARKER, ("locked marker %p", vp));
6836                 KASSERT(vp->v_mount == mp || vp->v_mount == NULL,
6837                     ("alien vnode on the lazy list %p %p", vp, mp));
6838                 VNPASS(vp->v_mount == mp, vp);
6839                 VNPASS(!VN_IS_DOOMED(vp), vp);
6840                 break;
6841         }
6842         TAILQ_REMOVE(&mp->mnt_lazyvnodelist, *mvp, v_lazylist);
6843
6844         /* Check if we are done */
6845         if (vp == NULL) {
6846                 mtx_unlock(&mp->mnt_listmtx);
6847                 mnt_vnode_markerfree_lazy(mvp, mp);
6848                 return (NULL);
6849         }
6850         TAILQ_INSERT_AFTER(&mp->mnt_lazyvnodelist, vp, *mvp, v_lazylist);
6851         mtx_unlock(&mp->mnt_listmtx);
6852         ASSERT_VI_LOCKED(vp, "lazy iter");
6853         return (vp);
6854 }
6855
6856 struct vnode *
6857 __mnt_vnode_next_lazy(struct vnode **mvp, struct mount *mp, mnt_lazy_cb_t *cb,
6858     void *cbarg)
6859 {
6860
6861         maybe_yield();
6862         mtx_lock(&mp->mnt_listmtx);
6863         return (mnt_vnode_next_lazy(mvp, mp, cb, cbarg));
6864 }
6865
6866 struct vnode *
6867 __mnt_vnode_first_lazy(struct vnode **mvp, struct mount *mp, mnt_lazy_cb_t *cb,
6868     void *cbarg)
6869 {
6870         struct vnode *vp;
6871
6872         if (TAILQ_EMPTY(&mp->mnt_lazyvnodelist))
6873                 return (NULL);
6874
6875         *mvp = vn_alloc_marker(mp);
6876         MNT_ILOCK(mp);
6877         MNT_REF(mp);
6878         MNT_IUNLOCK(mp);
6879
6880         mtx_lock(&mp->mnt_listmtx);
6881         vp = TAILQ_FIRST(&mp->mnt_lazyvnodelist);
6882         if (vp == NULL) {
6883                 mtx_unlock(&mp->mnt_listmtx);
6884                 mnt_vnode_markerfree_lazy(mvp, mp);
6885                 return (NULL);
6886         }
6887         TAILQ_INSERT_BEFORE(vp, *mvp, v_lazylist);
6888         return (mnt_vnode_next_lazy(mvp, mp, cb, cbarg));
6889 }
6890
6891 void
6892 __mnt_vnode_markerfree_lazy(struct vnode **mvp, struct mount *mp)
6893 {
6894
6895         if (*mvp == NULL)
6896                 return;
6897
6898         mtx_lock(&mp->mnt_listmtx);
6899         TAILQ_REMOVE(&mp->mnt_lazyvnodelist, *mvp, v_lazylist);
6900         mtx_unlock(&mp->mnt_listmtx);
6901         mnt_vnode_markerfree_lazy(mvp, mp);
6902 }
6903
6904 int
6905 vn_dir_check_exec(struct vnode *vp, struct componentname *cnp)
6906 {
6907
6908         if ((cnp->cn_flags & NOEXECCHECK) != 0) {
6909                 cnp->cn_flags &= ~NOEXECCHECK;
6910                 return (0);
6911         }
6912
6913         return (VOP_ACCESS(vp, VEXEC, cnp->cn_cred, cnp->cn_thread));
6914 }
6915
6916 /*
6917  * Do not use this variant unless you have means other than the hold count
6918  * to prevent the vnode from getting freed.
6919  */
6920 void
6921 vn_seqc_write_begin_locked(struct vnode *vp)
6922 {
6923
6924         ASSERT_VI_LOCKED(vp, __func__);
6925         VNPASS(vp->v_holdcnt > 0, vp);
6926         VNPASS(vp->v_seqc_users >= 0, vp);
6927         vp->v_seqc_users++;
6928         if (vp->v_seqc_users == 1)
6929                 seqc_sleepable_write_begin(&vp->v_seqc);
6930 }
6931
6932 void
6933 vn_seqc_write_begin(struct vnode *vp)
6934 {
6935
6936         VI_LOCK(vp);
6937         vn_seqc_write_begin_locked(vp);
6938         VI_UNLOCK(vp);
6939 }
6940
6941 void
6942 vn_seqc_write_end_locked(struct vnode *vp)
6943 {
6944
6945         ASSERT_VI_LOCKED(vp, __func__);
6946         VNPASS(vp->v_seqc_users > 0, vp);
6947         vp->v_seqc_users--;
6948         if (vp->v_seqc_users == 0)
6949                 seqc_sleepable_write_end(&vp->v_seqc);
6950 }
6951
6952 void
6953 vn_seqc_write_end(struct vnode *vp)
6954 {
6955
6956         VI_LOCK(vp);
6957         vn_seqc_write_end_locked(vp);
6958         VI_UNLOCK(vp);
6959 }
6960
6961 /*
6962  * Special case handling for allocating and freeing vnodes.
6963  *
6964  * The counter remains unchanged on free so that a doomed vnode will
6965  * keep testing as in modify as long as it is accessible with SMR.
6966  */
6967 static void
6968 vn_seqc_init(struct vnode *vp)
6969 {
6970
6971         vp->v_seqc = 0;
6972         vp->v_seqc_users = 0;
6973 }
6974
6975 static void
6976 vn_seqc_write_end_free(struct vnode *vp)
6977 {
6978
6979         VNPASS(seqc_in_modify(vp->v_seqc), vp);
6980         VNPASS(vp->v_seqc_users == 1, vp);
6981 }
6982
6983 void
6984 vn_irflag_set_locked(struct vnode *vp, short toset)
6985 {
6986         short flags;
6987
6988         ASSERT_VI_LOCKED(vp, __func__);
6989         flags = vn_irflag_read(vp);
6990         VNASSERT((flags & toset) == 0, vp,
6991             ("%s: some of the passed flags already set (have %d, passed %d)\n",
6992             __func__, flags, toset));
6993         atomic_store_short(&vp->v_irflag, flags | toset);
6994 }
6995
6996 void
6997 vn_irflag_set(struct vnode *vp, short toset)
6998 {
6999
7000         VI_LOCK(vp);
7001         vn_irflag_set_locked(vp, toset);
7002         VI_UNLOCK(vp);
7003 }
7004
7005 void
7006 vn_irflag_set_cond_locked(struct vnode *vp, short toset)
7007 {
7008         short flags;
7009
7010         ASSERT_VI_LOCKED(vp, __func__);
7011         flags = vn_irflag_read(vp);
7012         atomic_store_short(&vp->v_irflag, flags | toset);
7013 }
7014
7015 void
7016 vn_irflag_set_cond(struct vnode *vp, short toset)
7017 {
7018
7019         VI_LOCK(vp);
7020         vn_irflag_set_cond_locked(vp, toset);
7021         VI_UNLOCK(vp);
7022 }
7023
7024 void
7025 vn_irflag_unset_locked(struct vnode *vp, short tounset)
7026 {
7027         short flags;
7028
7029         ASSERT_VI_LOCKED(vp, __func__);
7030         flags = vn_irflag_read(vp);
7031         VNASSERT((flags & tounset) == tounset, vp,
7032             ("%s: some of the passed flags not set (have %d, passed %d)\n",
7033             __func__, flags, tounset));
7034         atomic_store_short(&vp->v_irflag, flags & ~tounset);
7035 }
7036
7037 void
7038 vn_irflag_unset(struct vnode *vp, short tounset)
7039 {
7040
7041         VI_LOCK(vp);
7042         vn_irflag_unset_locked(vp, tounset);
7043         VI_UNLOCK(vp);
7044 }