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