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