]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/vfs_subr.c
vfs: clean up vputx a little
[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 static void
1667 freevnode(struct vnode *vp)
1668 {
1669         struct bufobj *bo;
1670
1671         /*
1672          * The vnode has been marked for destruction, so free it.
1673          *
1674          * The vnode will be returned to the zone where it will
1675          * normally remain until it is needed for another vnode. We
1676          * need to cleanup (or verify that the cleanup has already
1677          * been done) any residual data left from its current use
1678          * so as not to contaminate the freshly allocated vnode.
1679          */
1680         CTR2(KTR_VFS, "%s: destroying the vnode %p", __func__, vp);
1681         atomic_subtract_long(&numvnodes, 1);
1682         bo = &vp->v_bufobj;
1683         VNASSERT((vp->v_iflag & VI_FREE) == 0, vp,
1684             ("cleaned vnode still on the free list."));
1685         VNASSERT(vp->v_data == NULL, vp, ("cleaned vnode isn't"));
1686         VNASSERT(vp->v_holdcnt == 0, vp, ("Non-zero hold count"));
1687         VNASSERT(vp->v_usecount == 0, vp, ("Non-zero use count"));
1688         VNASSERT(vp->v_writecount == 0, vp, ("Non-zero write count"));
1689         VNASSERT(bo->bo_numoutput == 0, vp, ("Clean vnode has pending I/O's"));
1690         VNASSERT(bo->bo_clean.bv_cnt == 0, vp, ("cleanbufcnt not 0"));
1691         VNASSERT(pctrie_is_empty(&bo->bo_clean.bv_root), vp,
1692             ("clean blk trie not empty"));
1693         VNASSERT(bo->bo_dirty.bv_cnt == 0, vp, ("dirtybufcnt not 0"));
1694         VNASSERT(pctrie_is_empty(&bo->bo_dirty.bv_root), vp,
1695             ("dirty blk trie not empty"));
1696         VNASSERT(TAILQ_EMPTY(&vp->v_cache_dst), vp, ("vp has namecache dst"));
1697         VNASSERT(LIST_EMPTY(&vp->v_cache_src), vp, ("vp has namecache src"));
1698         VNASSERT(vp->v_cache_dd == NULL, vp, ("vp has namecache for .."));
1699         VNASSERT(TAILQ_EMPTY(&vp->v_rl.rl_waiters), vp,
1700             ("Dangling rangelock waiters"));
1701         VI_UNLOCK(vp);
1702 #ifdef MAC
1703         mac_vnode_destroy(vp);
1704 #endif
1705         if (vp->v_pollinfo != NULL) {
1706                 destroy_vpollinfo(vp->v_pollinfo);
1707                 vp->v_pollinfo = NULL;
1708         }
1709 #ifdef INVARIANTS
1710         /* XXX Elsewhere we detect an already freed vnode via NULL v_op. */
1711         vp->v_op = NULL;
1712 #endif
1713         vp->v_mountedhere = NULL;
1714         vp->v_unpcb = NULL;
1715         vp->v_rdev = NULL;
1716         vp->v_fifoinfo = NULL;
1717         vp->v_lasta = vp->v_clen = vp->v_cstart = vp->v_lastw = 0;
1718         vp->v_iflag = 0;
1719         vp->v_vflag = 0;
1720         bo->bo_flag = 0;
1721         uma_zfree(vnode_zone, vp);
1722 }
1723
1724 /*
1725  * Delete from old mount point vnode list, if on one.
1726  */
1727 static void
1728 delmntque(struct vnode *vp)
1729 {
1730         struct mount *mp;
1731
1732         mp = vp->v_mount;
1733         if (mp == NULL)
1734                 return;
1735         MNT_ILOCK(mp);
1736         VI_LOCK(vp);
1737         KASSERT(mp->mnt_activevnodelistsize <= mp->mnt_nvnodelistsize,
1738             ("Active vnode list size %d > Vnode list size %d",
1739              mp->mnt_activevnodelistsize, mp->mnt_nvnodelistsize));
1740         if (vp->v_iflag & VI_ACTIVE) {
1741                 vp->v_iflag &= ~VI_ACTIVE;
1742                 mtx_lock(&mp->mnt_listmtx);
1743                 TAILQ_REMOVE(&mp->mnt_activevnodelist, vp, v_actfreelist);
1744                 mp->mnt_activevnodelistsize--;
1745                 mtx_unlock(&mp->mnt_listmtx);
1746         }
1747         vp->v_mount = NULL;
1748         VI_UNLOCK(vp);
1749         VNASSERT(mp->mnt_nvnodelistsize > 0, vp,
1750                 ("bad mount point vnode list size"));
1751         TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1752         mp->mnt_nvnodelistsize--;
1753         MNT_REL(mp);
1754         MNT_IUNLOCK(mp);
1755 }
1756
1757 static void
1758 insmntque_stddtr(struct vnode *vp, void *dtr_arg)
1759 {
1760
1761         vp->v_data = NULL;
1762         vp->v_op = &dead_vnodeops;
1763         vgone(vp);
1764         vput(vp);
1765 }
1766
1767 /*
1768  * Insert into list of vnodes for the new mount point, if available.
1769  */
1770 int
1771 insmntque1(struct vnode *vp, struct mount *mp,
1772         void (*dtr)(struct vnode *, void *), void *dtr_arg)
1773 {
1774
1775         KASSERT(vp->v_mount == NULL,
1776                 ("insmntque: vnode already on per mount vnode list"));
1777         VNASSERT(mp != NULL, vp, ("Don't call insmntque(foo, NULL)"));
1778         ASSERT_VOP_ELOCKED(vp, "insmntque: non-locked vp");
1779
1780         /*
1781          * We acquire the vnode interlock early to ensure that the
1782          * vnode cannot be recycled by another process releasing a
1783          * holdcnt on it before we get it on both the vnode list
1784          * and the active vnode list. The mount mutex protects only
1785          * manipulation of the vnode list and the vnode freelist
1786          * mutex protects only manipulation of the active vnode list.
1787          * Hence the need to hold the vnode interlock throughout.
1788          */
1789         MNT_ILOCK(mp);
1790         VI_LOCK(vp);
1791         if (((mp->mnt_kern_flag & MNTK_UNMOUNT) != 0 &&
1792             ((mp->mnt_kern_flag & MNTK_UNMOUNTF) != 0 ||
1793             mp->mnt_nvnodelistsize == 0)) &&
1794             (vp->v_vflag & VV_FORCEINSMQ) == 0) {
1795                 VI_UNLOCK(vp);
1796                 MNT_IUNLOCK(mp);
1797                 if (dtr != NULL)
1798                         dtr(vp, dtr_arg);
1799                 return (EBUSY);
1800         }
1801         vp->v_mount = mp;
1802         MNT_REF(mp);
1803         TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1804         VNASSERT(mp->mnt_nvnodelistsize >= 0, vp,
1805                 ("neg mount point vnode list size"));
1806         mp->mnt_nvnodelistsize++;
1807         KASSERT((vp->v_iflag & VI_ACTIVE) == 0,
1808             ("Activating already active vnode"));
1809         vp->v_iflag |= VI_ACTIVE;
1810         mtx_lock(&mp->mnt_listmtx);
1811         TAILQ_INSERT_HEAD(&mp->mnt_activevnodelist, vp, v_actfreelist);
1812         mp->mnt_activevnodelistsize++;
1813         mtx_unlock(&mp->mnt_listmtx);
1814         VI_UNLOCK(vp);
1815         MNT_IUNLOCK(mp);
1816         return (0);
1817 }
1818
1819 int
1820 insmntque(struct vnode *vp, struct mount *mp)
1821 {
1822
1823         return (insmntque1(vp, mp, insmntque_stddtr, NULL));
1824 }
1825
1826 /*
1827  * Flush out and invalidate all buffers associated with a bufobj
1828  * Called with the underlying object locked.
1829  */
1830 int
1831 bufobj_invalbuf(struct bufobj *bo, int flags, int slpflag, int slptimeo)
1832 {
1833         int error;
1834
1835         BO_LOCK(bo);
1836         if (flags & V_SAVE) {
1837                 error = bufobj_wwait(bo, slpflag, slptimeo);
1838                 if (error) {
1839                         BO_UNLOCK(bo);
1840                         return (error);
1841                 }
1842                 if (bo->bo_dirty.bv_cnt > 0) {
1843                         BO_UNLOCK(bo);
1844                         if ((error = BO_SYNC(bo, MNT_WAIT)) != 0)
1845                                 return (error);
1846                         /*
1847                          * XXX We could save a lock/unlock if this was only
1848                          * enabled under INVARIANTS
1849                          */
1850                         BO_LOCK(bo);
1851                         if (bo->bo_numoutput > 0 || bo->bo_dirty.bv_cnt > 0)
1852                                 panic("vinvalbuf: dirty bufs");
1853                 }
1854         }
1855         /*
1856          * If you alter this loop please notice that interlock is dropped and
1857          * reacquired in flushbuflist.  Special care is needed to ensure that
1858          * no race conditions occur from this.
1859          */
1860         do {
1861                 error = flushbuflist(&bo->bo_clean,
1862                     flags, bo, slpflag, slptimeo);
1863                 if (error == 0 && !(flags & V_CLEANONLY))
1864                         error = flushbuflist(&bo->bo_dirty,
1865                             flags, bo, slpflag, slptimeo);
1866                 if (error != 0 && error != EAGAIN) {
1867                         BO_UNLOCK(bo);
1868                         return (error);
1869                 }
1870         } while (error != 0);
1871
1872         /*
1873          * Wait for I/O to complete.  XXX needs cleaning up.  The vnode can
1874          * have write I/O in-progress but if there is a VM object then the
1875          * VM object can also have read-I/O in-progress.
1876          */
1877         do {
1878                 bufobj_wwait(bo, 0, 0);
1879                 if ((flags & V_VMIO) == 0 && bo->bo_object != NULL) {
1880                         BO_UNLOCK(bo);
1881                         vm_object_pip_wait_unlocked(bo->bo_object, "bovlbx");
1882                         BO_LOCK(bo);
1883                 }
1884         } while (bo->bo_numoutput > 0);
1885         BO_UNLOCK(bo);
1886
1887         /*
1888          * Destroy the copy in the VM cache, too.
1889          */
1890         if (bo->bo_object != NULL &&
1891             (flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO)) == 0) {
1892                 VM_OBJECT_WLOCK(bo->bo_object);
1893                 vm_object_page_remove(bo->bo_object, 0, 0, (flags & V_SAVE) ?
1894                     OBJPR_CLEANONLY : 0);
1895                 VM_OBJECT_WUNLOCK(bo->bo_object);
1896         }
1897
1898 #ifdef INVARIANTS
1899         BO_LOCK(bo);
1900         if ((flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO |
1901             V_ALLOWCLEAN)) == 0 && (bo->bo_dirty.bv_cnt > 0 ||
1902             bo->bo_clean.bv_cnt > 0))
1903                 panic("vinvalbuf: flush failed");
1904         if ((flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO)) == 0 &&
1905             bo->bo_dirty.bv_cnt > 0)
1906                 panic("vinvalbuf: flush dirty failed");
1907         BO_UNLOCK(bo);
1908 #endif
1909         return (0);
1910 }
1911
1912 /*
1913  * Flush out and invalidate all buffers associated with a vnode.
1914  * Called with the underlying object locked.
1915  */
1916 int
1917 vinvalbuf(struct vnode *vp, int flags, int slpflag, int slptimeo)
1918 {
1919
1920         CTR3(KTR_VFS, "%s: vp %p with flags %d", __func__, vp, flags);
1921         ASSERT_VOP_LOCKED(vp, "vinvalbuf");
1922         if (vp->v_object != NULL && vp->v_object->handle != vp)
1923                 return (0);
1924         return (bufobj_invalbuf(&vp->v_bufobj, flags, slpflag, slptimeo));
1925 }
1926
1927 /*
1928  * Flush out buffers on the specified list.
1929  *
1930  */
1931 static int
1932 flushbuflist(struct bufv *bufv, int flags, struct bufobj *bo, int slpflag,
1933     int slptimeo)
1934 {
1935         struct buf *bp, *nbp;
1936         int retval, error;
1937         daddr_t lblkno;
1938         b_xflags_t xflags;
1939
1940         ASSERT_BO_WLOCKED(bo);
1941
1942         retval = 0;
1943         TAILQ_FOREACH_SAFE(bp, &bufv->bv_hd, b_bobufs, nbp) {
1944                 /*
1945                  * If we are flushing both V_NORMAL and V_ALT buffers then
1946                  * do not skip any buffers. If we are flushing only V_NORMAL
1947                  * buffers then skip buffers marked as BX_ALTDATA. If we are
1948                  * flushing only V_ALT buffers then skip buffers not marked
1949                  * as BX_ALTDATA.
1950                  */
1951                 if (((flags & (V_NORMAL | V_ALT)) != (V_NORMAL | V_ALT)) &&
1952                    (((flags & V_NORMAL) && (bp->b_xflags & BX_ALTDATA) != 0) ||
1953                     ((flags & V_ALT) && (bp->b_xflags & BX_ALTDATA) == 0))) {
1954                         continue;
1955                 }
1956                 if (nbp != NULL) {
1957                         lblkno = nbp->b_lblkno;
1958                         xflags = nbp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN);
1959                 }
1960                 retval = EAGAIN;
1961                 error = BUF_TIMELOCK(bp,
1962                     LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, BO_LOCKPTR(bo),
1963                     "flushbuf", slpflag, slptimeo);
1964                 if (error) {
1965                         BO_LOCK(bo);
1966                         return (error != ENOLCK ? error : EAGAIN);
1967                 }
1968                 KASSERT(bp->b_bufobj == bo,
1969                     ("bp %p wrong b_bufobj %p should be %p",
1970                     bp, bp->b_bufobj, bo));
1971                 /*
1972                  * XXX Since there are no node locks for NFS, I
1973                  * believe there is a slight chance that a delayed
1974                  * write will occur while sleeping just above, so
1975                  * check for it.
1976                  */
1977                 if (((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI) &&
1978                     (flags & V_SAVE)) {
1979                         bremfree(bp);
1980                         bp->b_flags |= B_ASYNC;
1981                         bwrite(bp);
1982                         BO_LOCK(bo);
1983                         return (EAGAIN);        /* XXX: why not loop ? */
1984                 }
1985                 bremfree(bp);
1986                 bp->b_flags |= (B_INVAL | B_RELBUF);
1987                 bp->b_flags &= ~B_ASYNC;
1988                 brelse(bp);
1989                 BO_LOCK(bo);
1990                 if (nbp == NULL)
1991                         break;
1992                 nbp = gbincore(bo, lblkno);
1993                 if (nbp == NULL || (nbp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
1994                     != xflags)
1995                         break;                  /* nbp invalid */
1996         }
1997         return (retval);
1998 }
1999
2000 int
2001 bnoreuselist(struct bufv *bufv, struct bufobj *bo, daddr_t startn, daddr_t endn)
2002 {
2003         struct buf *bp;
2004         int error;
2005         daddr_t lblkno;
2006
2007         ASSERT_BO_LOCKED(bo);
2008
2009         for (lblkno = startn;;) {
2010 again:
2011                 bp = BUF_PCTRIE_LOOKUP_GE(&bufv->bv_root, lblkno);
2012                 if (bp == NULL || bp->b_lblkno >= endn ||
2013                     bp->b_lblkno < startn)
2014                         break;
2015                 error = BUF_TIMELOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
2016                     LK_INTERLOCK, BO_LOCKPTR(bo), "brlsfl", 0, 0);
2017                 if (error != 0) {
2018                         BO_RLOCK(bo);
2019                         if (error == ENOLCK)
2020                                 goto again;
2021                         return (error);
2022                 }
2023                 KASSERT(bp->b_bufobj == bo,
2024                     ("bp %p wrong b_bufobj %p should be %p",
2025                     bp, bp->b_bufobj, bo));
2026                 lblkno = bp->b_lblkno + 1;
2027                 if ((bp->b_flags & B_MANAGED) == 0)
2028                         bremfree(bp);
2029                 bp->b_flags |= B_RELBUF;
2030                 /*
2031                  * In the VMIO case, use the B_NOREUSE flag to hint that the
2032                  * pages backing each buffer in the range are unlikely to be
2033                  * reused.  Dirty buffers will have the hint applied once
2034                  * they've been written.
2035                  */
2036                 if ((bp->b_flags & B_VMIO) != 0)
2037                         bp->b_flags |= B_NOREUSE;
2038                 brelse(bp);
2039                 BO_RLOCK(bo);
2040         }
2041         return (0);
2042 }
2043
2044 /*
2045  * Truncate a file's buffer and pages to a specified length.  This
2046  * is in lieu of the old vinvalbuf mechanism, which performed unneeded
2047  * sync activity.
2048  */
2049 int
2050 vtruncbuf(struct vnode *vp, off_t length, int blksize)
2051 {
2052         struct buf *bp, *nbp;
2053         struct bufobj *bo;
2054         daddr_t startlbn;
2055
2056         CTR4(KTR_VFS, "%s: vp %p with block %d:%ju", __func__,
2057             vp, blksize, (uintmax_t)length);
2058
2059         /*
2060          * Round up to the *next* lbn.
2061          */
2062         startlbn = howmany(length, blksize);
2063
2064         ASSERT_VOP_LOCKED(vp, "vtruncbuf");
2065
2066         bo = &vp->v_bufobj;
2067 restart_unlocked:
2068         BO_LOCK(bo);
2069
2070         while (v_inval_buf_range_locked(vp, bo, startlbn, INT64_MAX) == EAGAIN)
2071                 ;
2072
2073         if (length > 0) {
2074 restartsync:
2075                 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
2076                         if (bp->b_lblkno > 0)
2077                                 continue;
2078                         /*
2079                          * Since we hold the vnode lock this should only
2080                          * fail if we're racing with the buf daemon.
2081                          */
2082                         if (BUF_LOCK(bp,
2083                             LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2084                             BO_LOCKPTR(bo)) == ENOLCK)
2085                                 goto restart_unlocked;
2086
2087                         VNASSERT((bp->b_flags & B_DELWRI), vp,
2088                             ("buf(%p) on dirty queue without DELWRI", bp));
2089
2090                         bremfree(bp);
2091                         bawrite(bp);
2092                         BO_LOCK(bo);
2093                         goto restartsync;
2094                 }
2095         }
2096
2097         bufobj_wwait(bo, 0, 0);
2098         BO_UNLOCK(bo);
2099         vnode_pager_setsize(vp, length);
2100
2101         return (0);
2102 }
2103
2104 /*
2105  * Invalidate the cached pages of a file's buffer within the range of block
2106  * numbers [startlbn, endlbn).
2107  */
2108 void
2109 v_inval_buf_range(struct vnode *vp, daddr_t startlbn, daddr_t endlbn,
2110     int blksize)
2111 {
2112         struct bufobj *bo;
2113         off_t start, end;
2114
2115         ASSERT_VOP_LOCKED(vp, "v_inval_buf_range");
2116
2117         start = blksize * startlbn;
2118         end = blksize * endlbn;
2119
2120         bo = &vp->v_bufobj;
2121         BO_LOCK(bo);
2122         MPASS(blksize == bo->bo_bsize);
2123
2124         while (v_inval_buf_range_locked(vp, bo, startlbn, endlbn) == EAGAIN)
2125                 ;
2126
2127         BO_UNLOCK(bo);
2128         vn_pages_remove(vp, OFF_TO_IDX(start), OFF_TO_IDX(end + PAGE_SIZE - 1));
2129 }
2130
2131 static int
2132 v_inval_buf_range_locked(struct vnode *vp, struct bufobj *bo,
2133     daddr_t startlbn, daddr_t endlbn)
2134 {
2135         struct buf *bp, *nbp;
2136         bool anyfreed;
2137
2138         ASSERT_VOP_LOCKED(vp, "v_inval_buf_range_locked");
2139         ASSERT_BO_LOCKED(bo);
2140
2141         do {
2142                 anyfreed = false;
2143                 TAILQ_FOREACH_SAFE(bp, &bo->bo_clean.bv_hd, b_bobufs, nbp) {
2144                         if (bp->b_lblkno < startlbn || bp->b_lblkno >= endlbn)
2145                                 continue;
2146                         if (BUF_LOCK(bp,
2147                             LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2148                             BO_LOCKPTR(bo)) == ENOLCK) {
2149                                 BO_LOCK(bo);
2150                                 return (EAGAIN);
2151                         }
2152
2153                         bremfree(bp);
2154                         bp->b_flags |= B_INVAL | B_RELBUF;
2155                         bp->b_flags &= ~B_ASYNC;
2156                         brelse(bp);
2157                         anyfreed = true;
2158
2159                         BO_LOCK(bo);
2160                         if (nbp != NULL &&
2161                             (((nbp->b_xflags & BX_VNCLEAN) == 0) ||
2162                             nbp->b_vp != vp ||
2163                             (nbp->b_flags & B_DELWRI) != 0))
2164                                 return (EAGAIN);
2165                 }
2166
2167                 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
2168                         if (bp->b_lblkno < startlbn || bp->b_lblkno >= endlbn)
2169                                 continue;
2170                         if (BUF_LOCK(bp,
2171                             LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2172                             BO_LOCKPTR(bo)) == ENOLCK) {
2173                                 BO_LOCK(bo);
2174                                 return (EAGAIN);
2175                         }
2176                         bremfree(bp);
2177                         bp->b_flags |= B_INVAL | B_RELBUF;
2178                         bp->b_flags &= ~B_ASYNC;
2179                         brelse(bp);
2180                         anyfreed = true;
2181
2182                         BO_LOCK(bo);
2183                         if (nbp != NULL &&
2184                             (((nbp->b_xflags & BX_VNDIRTY) == 0) ||
2185                             (nbp->b_vp != vp) ||
2186                             (nbp->b_flags & B_DELWRI) == 0))
2187                                 return (EAGAIN);
2188                 }
2189         } while (anyfreed);
2190         return (0);
2191 }
2192
2193 static void
2194 buf_vlist_remove(struct buf *bp)
2195 {
2196         struct bufv *bv;
2197
2198         KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
2199         ASSERT_BO_WLOCKED(bp->b_bufobj);
2200         KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) !=
2201             (BX_VNDIRTY|BX_VNCLEAN),
2202             ("buf_vlist_remove: Buf %p is on two lists", bp));
2203         if (bp->b_xflags & BX_VNDIRTY)
2204                 bv = &bp->b_bufobj->bo_dirty;
2205         else
2206                 bv = &bp->b_bufobj->bo_clean;
2207         BUF_PCTRIE_REMOVE(&bv->bv_root, bp->b_lblkno);
2208         TAILQ_REMOVE(&bv->bv_hd, bp, b_bobufs);
2209         bv->bv_cnt--;
2210         bp->b_xflags &= ~(BX_VNDIRTY | BX_VNCLEAN);
2211 }
2212
2213 /*
2214  * Add the buffer to the sorted clean or dirty block list.
2215  *
2216  * NOTE: xflags is passed as a constant, optimizing this inline function!
2217  */
2218 static void
2219 buf_vlist_add(struct buf *bp, struct bufobj *bo, b_xflags_t xflags)
2220 {
2221         struct bufv *bv;
2222         struct buf *n;
2223         int error;
2224
2225         ASSERT_BO_WLOCKED(bo);
2226         KASSERT((xflags & BX_VNDIRTY) == 0 || (bo->bo_flag & BO_DEAD) == 0,
2227             ("dead bo %p", bo));
2228         KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0,
2229             ("buf_vlist_add: Buf %p has existing xflags %d", bp, bp->b_xflags));
2230         bp->b_xflags |= xflags;
2231         if (xflags & BX_VNDIRTY)
2232                 bv = &bo->bo_dirty;
2233         else
2234                 bv = &bo->bo_clean;
2235
2236         /*
2237          * Keep the list ordered.  Optimize empty list insertion.  Assume
2238          * we tend to grow at the tail so lookup_le should usually be cheaper
2239          * than _ge. 
2240          */
2241         if (bv->bv_cnt == 0 ||
2242             bp->b_lblkno > TAILQ_LAST(&bv->bv_hd, buflists)->b_lblkno)
2243                 TAILQ_INSERT_TAIL(&bv->bv_hd, bp, b_bobufs);
2244         else if ((n = BUF_PCTRIE_LOOKUP_LE(&bv->bv_root, bp->b_lblkno)) == NULL)
2245                 TAILQ_INSERT_HEAD(&bv->bv_hd, bp, b_bobufs);
2246         else
2247                 TAILQ_INSERT_AFTER(&bv->bv_hd, n, bp, b_bobufs);
2248         error = BUF_PCTRIE_INSERT(&bv->bv_root, bp);
2249         if (error)
2250                 panic("buf_vlist_add:  Preallocated nodes insufficient.");
2251         bv->bv_cnt++;
2252 }
2253
2254 /*
2255  * Look up a buffer using the buffer tries.
2256  */
2257 struct buf *
2258 gbincore(struct bufobj *bo, daddr_t lblkno)
2259 {
2260         struct buf *bp;
2261
2262         ASSERT_BO_LOCKED(bo);
2263         bp = BUF_PCTRIE_LOOKUP(&bo->bo_clean.bv_root, lblkno);
2264         if (bp != NULL)
2265                 return (bp);
2266         return BUF_PCTRIE_LOOKUP(&bo->bo_dirty.bv_root, lblkno);
2267 }
2268
2269 /*
2270  * Associate a buffer with a vnode.
2271  */
2272 void
2273 bgetvp(struct vnode *vp, struct buf *bp)
2274 {
2275         struct bufobj *bo;
2276
2277         bo = &vp->v_bufobj;
2278         ASSERT_BO_WLOCKED(bo);
2279         VNASSERT(bp->b_vp == NULL, bp->b_vp, ("bgetvp: not free"));
2280
2281         CTR3(KTR_BUF, "bgetvp(%p) vp %p flags %X", bp, vp, bp->b_flags);
2282         VNASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0, vp,
2283             ("bgetvp: bp already attached! %p", bp));
2284
2285         vhold(vp);
2286         bp->b_vp = vp;
2287         bp->b_bufobj = bo;
2288         /*
2289          * Insert onto list for new vnode.
2290          */
2291         buf_vlist_add(bp, bo, BX_VNCLEAN);
2292 }
2293
2294 /*
2295  * Disassociate a buffer from a vnode.
2296  */
2297 void
2298 brelvp(struct buf *bp)
2299 {
2300         struct bufobj *bo;
2301         struct vnode *vp;
2302
2303         CTR3(KTR_BUF, "brelvp(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2304         KASSERT(bp->b_vp != NULL, ("brelvp: NULL"));
2305
2306         /*
2307          * Delete from old vnode list, if on one.
2308          */
2309         vp = bp->b_vp;          /* XXX */
2310         bo = bp->b_bufobj;
2311         BO_LOCK(bo);
2312         if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
2313                 buf_vlist_remove(bp);
2314         else
2315                 panic("brelvp: Buffer %p not on queue.", bp);
2316         if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
2317                 bo->bo_flag &= ~BO_ONWORKLST;
2318                 mtx_lock(&sync_mtx);
2319                 LIST_REMOVE(bo, bo_synclist);
2320                 syncer_worklist_len--;
2321                 mtx_unlock(&sync_mtx);
2322         }
2323         bp->b_vp = NULL;
2324         bp->b_bufobj = NULL;
2325         BO_UNLOCK(bo);
2326         vdrop(vp);
2327 }
2328
2329 /*
2330  * Add an item to the syncer work queue.
2331  */
2332 static void
2333 vn_syncer_add_to_worklist(struct bufobj *bo, int delay)
2334 {
2335         int slot;
2336
2337         ASSERT_BO_WLOCKED(bo);
2338
2339         mtx_lock(&sync_mtx);
2340         if (bo->bo_flag & BO_ONWORKLST)
2341                 LIST_REMOVE(bo, bo_synclist);
2342         else {
2343                 bo->bo_flag |= BO_ONWORKLST;
2344                 syncer_worklist_len++;
2345         }
2346
2347         if (delay > syncer_maxdelay - 2)
2348                 delay = syncer_maxdelay - 2;
2349         slot = (syncer_delayno + delay) & syncer_mask;
2350
2351         LIST_INSERT_HEAD(&syncer_workitem_pending[slot], bo, bo_synclist);
2352         mtx_unlock(&sync_mtx);
2353 }
2354
2355 static int
2356 sysctl_vfs_worklist_len(SYSCTL_HANDLER_ARGS)
2357 {
2358         int error, len;
2359
2360         mtx_lock(&sync_mtx);
2361         len = syncer_worklist_len - sync_vnode_count;
2362         mtx_unlock(&sync_mtx);
2363         error = SYSCTL_OUT(req, &len, sizeof(len));
2364         return (error);
2365 }
2366
2367 SYSCTL_PROC(_vfs, OID_AUTO, worklist_len, CTLTYPE_INT | CTLFLAG_RD, NULL, 0,
2368     sysctl_vfs_worklist_len, "I", "Syncer thread worklist length");
2369
2370 static struct proc *updateproc;
2371 static void sched_sync(void);
2372 static struct kproc_desc up_kp = {
2373         "syncer",
2374         sched_sync,
2375         &updateproc
2376 };
2377 SYSINIT(syncer, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start, &up_kp);
2378
2379 static int
2380 sync_vnode(struct synclist *slp, struct bufobj **bo, struct thread *td)
2381 {
2382         struct vnode *vp;
2383         struct mount *mp;
2384
2385         *bo = LIST_FIRST(slp);
2386         if (*bo == NULL)
2387                 return (0);
2388         vp = bo2vnode(*bo);
2389         if (VOP_ISLOCKED(vp) != 0 || VI_TRYLOCK(vp) == 0)
2390                 return (1);
2391         /*
2392          * We use vhold in case the vnode does not
2393          * successfully sync.  vhold prevents the vnode from
2394          * going away when we unlock the sync_mtx so that
2395          * we can acquire the vnode interlock.
2396          */
2397         vholdl(vp);
2398         mtx_unlock(&sync_mtx);
2399         VI_UNLOCK(vp);
2400         if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
2401                 vdrop(vp);
2402                 mtx_lock(&sync_mtx);
2403                 return (*bo == LIST_FIRST(slp));
2404         }
2405         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2406         (void) VOP_FSYNC(vp, MNT_LAZY, td);
2407         VOP_UNLOCK(vp, 0);
2408         vn_finished_write(mp);
2409         BO_LOCK(*bo);
2410         if (((*bo)->bo_flag & BO_ONWORKLST) != 0) {
2411                 /*
2412                  * Put us back on the worklist.  The worklist
2413                  * routine will remove us from our current
2414                  * position and then add us back in at a later
2415                  * position.
2416                  */
2417                 vn_syncer_add_to_worklist(*bo, syncdelay);
2418         }
2419         BO_UNLOCK(*bo);
2420         vdrop(vp);
2421         mtx_lock(&sync_mtx);
2422         return (0);
2423 }
2424
2425 static int first_printf = 1;
2426
2427 /*
2428  * System filesystem synchronizer daemon.
2429  */
2430 static void
2431 sched_sync(void)
2432 {
2433         struct synclist *next, *slp;
2434         struct bufobj *bo;
2435         long starttime;
2436         struct thread *td = curthread;
2437         int last_work_seen;
2438         int net_worklist_len;
2439         int syncer_final_iter;
2440         int error;
2441
2442         last_work_seen = 0;
2443         syncer_final_iter = 0;
2444         syncer_state = SYNCER_RUNNING;
2445         starttime = time_uptime;
2446         td->td_pflags |= TDP_NORUNNINGBUF;
2447
2448         EVENTHANDLER_REGISTER(shutdown_pre_sync, syncer_shutdown, td->td_proc,
2449             SHUTDOWN_PRI_LAST);
2450
2451         mtx_lock(&sync_mtx);
2452         for (;;) {
2453                 if (syncer_state == SYNCER_FINAL_DELAY &&
2454                     syncer_final_iter == 0) {
2455                         mtx_unlock(&sync_mtx);
2456                         kproc_suspend_check(td->td_proc);
2457                         mtx_lock(&sync_mtx);
2458                 }
2459                 net_worklist_len = syncer_worklist_len - sync_vnode_count;
2460                 if (syncer_state != SYNCER_RUNNING &&
2461                     starttime != time_uptime) {
2462                         if (first_printf) {
2463                                 printf("\nSyncing disks, vnodes remaining... ");
2464                                 first_printf = 0;
2465                         }
2466                         printf("%d ", net_worklist_len);
2467                 }
2468                 starttime = time_uptime;
2469
2470                 /*
2471                  * Push files whose dirty time has expired.  Be careful
2472                  * of interrupt race on slp queue.
2473                  *
2474                  * Skip over empty worklist slots when shutting down.
2475                  */
2476                 do {
2477                         slp = &syncer_workitem_pending[syncer_delayno];
2478                         syncer_delayno += 1;
2479                         if (syncer_delayno == syncer_maxdelay)
2480                                 syncer_delayno = 0;
2481                         next = &syncer_workitem_pending[syncer_delayno];
2482                         /*
2483                          * If the worklist has wrapped since the
2484                          * it was emptied of all but syncer vnodes,
2485                          * switch to the FINAL_DELAY state and run
2486                          * for one more second.
2487                          */
2488                         if (syncer_state == SYNCER_SHUTTING_DOWN &&
2489                             net_worklist_len == 0 &&
2490                             last_work_seen == syncer_delayno) {
2491                                 syncer_state = SYNCER_FINAL_DELAY;
2492                                 syncer_final_iter = SYNCER_SHUTDOWN_SPEEDUP;
2493                         }
2494                 } while (syncer_state != SYNCER_RUNNING && LIST_EMPTY(slp) &&
2495                     syncer_worklist_len > 0);
2496
2497                 /*
2498                  * Keep track of the last time there was anything
2499                  * on the worklist other than syncer vnodes.
2500                  * Return to the SHUTTING_DOWN state if any
2501                  * new work appears.
2502                  */
2503                 if (net_worklist_len > 0 || syncer_state == SYNCER_RUNNING)
2504                         last_work_seen = syncer_delayno;
2505                 if (net_worklist_len > 0 && syncer_state == SYNCER_FINAL_DELAY)
2506                         syncer_state = SYNCER_SHUTTING_DOWN;
2507                 while (!LIST_EMPTY(slp)) {
2508                         error = sync_vnode(slp, &bo, td);
2509                         if (error == 1) {
2510                                 LIST_REMOVE(bo, bo_synclist);
2511                                 LIST_INSERT_HEAD(next, bo, bo_synclist);
2512                                 continue;
2513                         }
2514
2515                         if (first_printf == 0) {
2516                                 /*
2517                                  * Drop the sync mutex, because some watchdog
2518                                  * drivers need to sleep while patting
2519                                  */
2520                                 mtx_unlock(&sync_mtx);
2521                                 wdog_kern_pat(WD_LASTVAL);
2522                                 mtx_lock(&sync_mtx);
2523                         }
2524
2525                 }
2526                 if (syncer_state == SYNCER_FINAL_DELAY && syncer_final_iter > 0)
2527                         syncer_final_iter--;
2528                 /*
2529                  * The variable rushjob allows the kernel to speed up the
2530                  * processing of the filesystem syncer process. A rushjob
2531                  * value of N tells the filesystem syncer to process the next
2532                  * N seconds worth of work on its queue ASAP. Currently rushjob
2533                  * is used by the soft update code to speed up the filesystem
2534                  * syncer process when the incore state is getting so far
2535                  * ahead of the disk that the kernel memory pool is being
2536                  * threatened with exhaustion.
2537                  */
2538                 if (rushjob > 0) {
2539                         rushjob -= 1;
2540                         continue;
2541                 }
2542                 /*
2543                  * Just sleep for a short period of time between
2544                  * iterations when shutting down to allow some I/O
2545                  * to happen.
2546                  *
2547                  * If it has taken us less than a second to process the
2548                  * current work, then wait. Otherwise start right over
2549                  * again. We can still lose time if any single round
2550                  * takes more than two seconds, but it does not really
2551                  * matter as we are just trying to generally pace the
2552                  * filesystem activity.
2553                  */
2554                 if (syncer_state != SYNCER_RUNNING ||
2555                     time_uptime == starttime) {
2556                         thread_lock(td);
2557                         sched_prio(td, PPAUSE);
2558                         thread_unlock(td);
2559                 }
2560                 if (syncer_state != SYNCER_RUNNING)
2561                         cv_timedwait(&sync_wakeup, &sync_mtx,
2562                             hz / SYNCER_SHUTDOWN_SPEEDUP);
2563                 else if (time_uptime == starttime)
2564                         cv_timedwait(&sync_wakeup, &sync_mtx, hz);
2565         }
2566 }
2567
2568 /*
2569  * Request the syncer daemon to speed up its work.
2570  * We never push it to speed up more than half of its
2571  * normal turn time, otherwise it could take over the cpu.
2572  */
2573 int
2574 speedup_syncer(void)
2575 {
2576         int ret = 0;
2577
2578         mtx_lock(&sync_mtx);
2579         if (rushjob < syncdelay / 2) {
2580                 rushjob += 1;
2581                 stat_rush_requests += 1;
2582                 ret = 1;
2583         }
2584         mtx_unlock(&sync_mtx);
2585         cv_broadcast(&sync_wakeup);
2586         return (ret);
2587 }
2588
2589 /*
2590  * Tell the syncer to speed up its work and run though its work
2591  * list several times, then tell it to shut down.
2592  */
2593 static void
2594 syncer_shutdown(void *arg, int howto)
2595 {
2596
2597         if (howto & RB_NOSYNC)
2598                 return;
2599         mtx_lock(&sync_mtx);
2600         syncer_state = SYNCER_SHUTTING_DOWN;
2601         rushjob = 0;
2602         mtx_unlock(&sync_mtx);
2603         cv_broadcast(&sync_wakeup);
2604         kproc_shutdown(arg, howto);
2605 }
2606
2607 void
2608 syncer_suspend(void)
2609 {
2610
2611         syncer_shutdown(updateproc, 0);
2612 }
2613
2614 void
2615 syncer_resume(void)
2616 {
2617
2618         mtx_lock(&sync_mtx);
2619         first_printf = 1;
2620         syncer_state = SYNCER_RUNNING;
2621         mtx_unlock(&sync_mtx);
2622         cv_broadcast(&sync_wakeup);
2623         kproc_resume(updateproc);
2624 }
2625
2626 /*
2627  * Reassign a buffer from one vnode to another.
2628  * Used to assign file specific control information
2629  * (indirect blocks) to the vnode to which they belong.
2630  */
2631 void
2632 reassignbuf(struct buf *bp)
2633 {
2634         struct vnode *vp;
2635         struct bufobj *bo;
2636         int delay;
2637 #ifdef INVARIANTS
2638         struct bufv *bv;
2639 #endif
2640
2641         vp = bp->b_vp;
2642         bo = bp->b_bufobj;
2643         ++reassignbufcalls;
2644
2645         CTR3(KTR_BUF, "reassignbuf(%p) vp %p flags %X",
2646             bp, bp->b_vp, bp->b_flags);
2647         /*
2648          * B_PAGING flagged buffers cannot be reassigned because their vp
2649          * is not fully linked in.
2650          */
2651         if (bp->b_flags & B_PAGING)
2652                 panic("cannot reassign paging buffer");
2653
2654         /*
2655          * Delete from old vnode list, if on one.
2656          */
2657         BO_LOCK(bo);
2658         if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
2659                 buf_vlist_remove(bp);
2660         else
2661                 panic("reassignbuf: Buffer %p not on queue.", bp);
2662         /*
2663          * If dirty, put on list of dirty buffers; otherwise insert onto list
2664          * of clean buffers.
2665          */
2666         if (bp->b_flags & B_DELWRI) {
2667                 if ((bo->bo_flag & BO_ONWORKLST) == 0) {
2668                         switch (vp->v_type) {
2669                         case VDIR:
2670                                 delay = dirdelay;
2671                                 break;
2672                         case VCHR:
2673                                 delay = metadelay;
2674                                 break;
2675                         default:
2676                                 delay = filedelay;
2677                         }
2678                         vn_syncer_add_to_worklist(bo, delay);
2679                 }
2680                 buf_vlist_add(bp, bo, BX_VNDIRTY);
2681         } else {
2682                 buf_vlist_add(bp, bo, BX_VNCLEAN);
2683
2684                 if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
2685                         mtx_lock(&sync_mtx);
2686                         LIST_REMOVE(bo, bo_synclist);
2687                         syncer_worklist_len--;
2688                         mtx_unlock(&sync_mtx);
2689                         bo->bo_flag &= ~BO_ONWORKLST;
2690                 }
2691         }
2692 #ifdef INVARIANTS
2693         bv = &bo->bo_clean;
2694         bp = TAILQ_FIRST(&bv->bv_hd);
2695         KASSERT(bp == NULL || bp->b_bufobj == bo,
2696             ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2697         bp = TAILQ_LAST(&bv->bv_hd, buflists);
2698         KASSERT(bp == NULL || bp->b_bufobj == bo,
2699             ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2700         bv = &bo->bo_dirty;
2701         bp = TAILQ_FIRST(&bv->bv_hd);
2702         KASSERT(bp == NULL || bp->b_bufobj == bo,
2703             ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2704         bp = TAILQ_LAST(&bv->bv_hd, buflists);
2705         KASSERT(bp == NULL || bp->b_bufobj == bo,
2706             ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2707 #endif
2708         BO_UNLOCK(bo);
2709 }
2710
2711 static void
2712 v_init_counters(struct vnode *vp)
2713 {
2714
2715         VNASSERT(vp->v_type == VNON && vp->v_data == NULL && vp->v_iflag == 0,
2716             vp, ("%s called for an initialized vnode", __FUNCTION__));
2717         ASSERT_VI_UNLOCKED(vp, __FUNCTION__);
2718
2719         refcount_init(&vp->v_holdcnt, 1);
2720         refcount_init(&vp->v_usecount, 1);
2721 }
2722
2723 /*
2724  * Increment si_usecount of the associated device, if any.
2725  */
2726 static void
2727 v_incr_devcount(struct vnode *vp)
2728 {
2729
2730         ASSERT_VI_LOCKED(vp, __FUNCTION__);
2731         if (vp->v_type == VCHR && vp->v_rdev != NULL) {
2732                 dev_lock();
2733                 vp->v_rdev->si_usecount++;
2734                 dev_unlock();
2735         }
2736 }
2737
2738 /*
2739  * Decrement si_usecount of the associated device, if any.
2740  */
2741 static void
2742 v_decr_devcount(struct vnode *vp)
2743 {
2744
2745         ASSERT_VI_LOCKED(vp, __FUNCTION__);
2746         if (vp->v_type == VCHR && vp->v_rdev != NULL) {
2747                 dev_lock();
2748                 vp->v_rdev->si_usecount--;
2749                 dev_unlock();
2750         }
2751 }
2752
2753 /*
2754  * Grab a particular vnode from the free list, increment its
2755  * reference count and lock it.  VI_DOOMED is set if the vnode
2756  * is being destroyed.  Only callers who specify LK_RETRY will
2757  * see doomed vnodes.  If inactive processing was delayed in
2758  * vput try to do it here.
2759  *
2760  * Both holdcnt and usecount can be manipulated using atomics without holding
2761  * any locks except in these cases which require the vnode interlock:
2762  * holdcnt: 1->0 and 0->1
2763  * usecount: 0->1
2764  *
2765  * usecount is permitted to transition 1->0 without the interlock because
2766  * vnode is kept live by holdcnt.
2767  */
2768 static enum vgetstate
2769 _vget_prep(struct vnode *vp, bool interlock)
2770 {
2771         enum vgetstate vs;
2772
2773         if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2774                 vs = VGET_USECOUNT;
2775         } else {
2776                 _vhold(vp, interlock);
2777                 vs = VGET_HOLDCNT;
2778         }
2779         return (vs);
2780 }
2781
2782 enum vgetstate
2783 vget_prep(struct vnode *vp)
2784 {
2785
2786         return (_vget_prep(vp, false));
2787 }
2788
2789 int
2790 vget(struct vnode *vp, int flags, struct thread *td)
2791 {
2792         enum vgetstate vs;
2793
2794         MPASS(td == curthread);
2795
2796         vs = _vget_prep(vp, (flags & LK_INTERLOCK) != 0);
2797         return (vget_finish(vp, flags, vs));
2798 }
2799
2800 int
2801 vget_finish(struct vnode *vp, int flags, enum vgetstate vs)
2802 {
2803         int error, oweinact;
2804
2805         VNASSERT((flags & LK_TYPE_MASK) != 0, vp,
2806             ("%s: invalid lock operation", __func__));
2807
2808         if ((flags & LK_INTERLOCK) != 0)
2809                 ASSERT_VI_LOCKED(vp, __func__);
2810         else
2811                 ASSERT_VI_UNLOCKED(vp, __func__);
2812         VNASSERT(vp->v_holdcnt > 0, vp, ("%s: vnode not held", __func__));
2813         if (vs == VGET_USECOUNT) {
2814                 VNASSERT(vp->v_usecount > 0, vp,
2815                     ("%s: vnode without usecount when VGET_USECOUNT was passed",
2816                     __func__));
2817         }
2818
2819         if ((error = vn_lock(vp, flags)) != 0) {
2820                 if (vs == VGET_USECOUNT)
2821                         vrele(vp);
2822                 else
2823                         vdrop(vp);
2824                 CTR2(KTR_VFS, "%s: impossible to lock vnode %p", __func__,
2825                     vp);
2826                 return (error);
2827         }
2828
2829         if (vs == VGET_USECOUNT) {
2830                 VNASSERT((vp->v_iflag & VI_OWEINACT) == 0, vp,
2831                     ("%s: vnode with usecount and VI_OWEINACT set", __func__));
2832                 return (0);
2833         }
2834
2835         /*
2836          * We hold the vnode. If the usecount is 0 it will be utilized to keep
2837          * the vnode around. Otherwise someone else lended their hold count and
2838          * we have to drop ours.
2839          */
2840         if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2841 #ifdef INVARIANTS
2842                 int old = atomic_fetchadd_int(&vp->v_holdcnt, -1) - 1;
2843                 VNASSERT(old > 0, vp, ("%s: wrong hold count", __func__));
2844 #else
2845                 refcount_release(&vp->v_holdcnt);
2846 #endif
2847                 VNODE_REFCOUNT_FENCE_ACQ();
2848                 VNASSERT((vp->v_iflag & VI_OWEINACT) == 0, vp,
2849                     ("%s: vnode with usecount and VI_OWEINACT set", __func__));
2850                 return (0);
2851         }
2852
2853         /*
2854          * We don't guarantee that any particular close will
2855          * trigger inactive processing so just make a best effort
2856          * here at preventing a reference to a removed file.  If
2857          * we don't succeed no harm is done.
2858          *
2859          * Upgrade our holdcnt to a usecount.
2860          */
2861         VI_LOCK(vp);
2862         /*
2863          * See the previous section. By the time we get here we may find
2864          * ourselves in the same spot.
2865          */
2866         if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2867 #ifdef INVARIANTS
2868                 int old = atomic_fetchadd_int(&vp->v_holdcnt, -1) - 1;
2869                 VNASSERT(old > 0, vp, ("%s: wrong hold count", __func__));
2870 #else
2871                 refcount_release(&vp->v_holdcnt);
2872 #endif
2873                 VNODE_REFCOUNT_FENCE_ACQ();
2874                 VNASSERT((vp->v_iflag & VI_OWEINACT) == 0, vp,
2875                     ("%s: vnode with usecount and VI_OWEINACT set",
2876                     __func__));
2877                 VI_UNLOCK(vp);
2878                 return (0);
2879         }
2880         if ((vp->v_iflag & VI_OWEINACT) == 0) {
2881                 oweinact = 0;
2882         } else {
2883                 oweinact = 1;
2884                 vp->v_iflag &= ~VI_OWEINACT;
2885                 VNODE_REFCOUNT_FENCE_REL();
2886         }
2887         v_incr_devcount(vp);
2888         refcount_acquire(&vp->v_usecount);
2889         if (oweinact && VOP_ISLOCKED(vp) == LK_EXCLUSIVE &&
2890             (flags & LK_NOWAIT) == 0)
2891                 vinactive(vp, curthread);
2892         VI_UNLOCK(vp);
2893         return (0);
2894 }
2895
2896 /*
2897  * Increase the reference (use) and hold count of a vnode.
2898  * This will also remove the vnode from the free list if it is presently free.
2899  */
2900 void
2901 vref(struct vnode *vp)
2902 {
2903
2904         ASSERT_VI_UNLOCKED(vp, __func__);
2905         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2906         if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2907                 VNODE_REFCOUNT_FENCE_ACQ();
2908                 VNASSERT(vp->v_holdcnt > 0, vp,
2909                     ("%s: active vnode not held", __func__));
2910                 VNASSERT((vp->v_iflag & VI_OWEINACT) == 0, vp,
2911                     ("%s: vnode with usecount and VI_OWEINACT set", __func__));
2912                 return;
2913         }
2914         VI_LOCK(vp);
2915         vrefl(vp);
2916         VI_UNLOCK(vp);
2917 }
2918
2919 void
2920 vrefl(struct vnode *vp)
2921 {
2922
2923         ASSERT_VI_LOCKED(vp, __func__);
2924         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2925         if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
2926                 VNODE_REFCOUNT_FENCE_ACQ();
2927                 VNASSERT(vp->v_holdcnt > 0, vp,
2928                     ("%s: active vnode not held", __func__));
2929                 VNASSERT((vp->v_iflag & VI_OWEINACT) == 0, vp,
2930                     ("%s: vnode with usecount and VI_OWEINACT set", __func__));
2931                 return;
2932         }
2933         vholdl(vp);
2934         if ((vp->v_iflag & VI_OWEINACT) != 0) {
2935                 vp->v_iflag &= ~VI_OWEINACT;
2936                 VNODE_REFCOUNT_FENCE_REL();
2937         }
2938         v_incr_devcount(vp);
2939         refcount_acquire(&vp->v_usecount);
2940 }
2941
2942 void
2943 vrefact(struct vnode *vp)
2944 {
2945
2946         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2947 #ifdef INVARIANTS
2948         int old = atomic_fetchadd_int(&vp->v_usecount, 1);
2949         VNASSERT(old > 0, vp, ("%s: wrong use count", __func__));
2950 #else
2951         refcount_acquire(&vp->v_usecount);
2952 #endif
2953 }
2954
2955 /*
2956  * Return reference count of a vnode.
2957  *
2958  * The results of this call are only guaranteed when some mechanism is used to
2959  * stop other processes from gaining references to the vnode.  This may be the
2960  * case if the caller holds the only reference.  This is also useful when stale
2961  * data is acceptable as race conditions may be accounted for by some other
2962  * means.
2963  */
2964 int
2965 vrefcnt(struct vnode *vp)
2966 {
2967
2968         return (vp->v_usecount);
2969 }
2970
2971 enum vputx_op { VPUTX_VRELE, VPUTX_VPUT, VPUTX_VUNREF };
2972
2973 /*
2974  * Decrement the use and hold counts for a vnode.
2975  *
2976  * See an explanation near vget() as to why atomic operation is safe.
2977  */
2978 static void
2979 vputx(struct vnode *vp, enum vputx_op func)
2980 {
2981         int error;
2982
2983         KASSERT(vp != NULL, ("vputx: null vp"));
2984         if (func == VPUTX_VUNREF)
2985                 ASSERT_VOP_LOCKED(vp, "vunref");
2986         ASSERT_VI_UNLOCKED(vp, __func__);
2987         VNASSERT(vp->v_holdcnt > 0 && vp->v_usecount > 0, vp,
2988             ("%s: wrong ref counts", __func__));
2989
2990         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2991
2992         /*
2993          * We want to hold the vnode until the inactive finishes to
2994          * prevent vgone() races.  We drop the use count here and the
2995          * hold count below when we're done.
2996          *
2997          * If we release the last usecount we take ownership of the hold
2998          * count which provides liveness of the vnode, in which case we
2999          * have to vdrop.
3000          */
3001         if (!refcount_release(&vp->v_usecount))
3002                 return;
3003         VI_LOCK(vp);
3004         v_decr_devcount(vp);
3005         /*
3006          * By the time we got here someone else might have transitioned
3007          * the count back to > 0.
3008          */
3009         if (vp->v_usecount > 0) {
3010                 vdropl(vp);
3011                 return;
3012         }
3013         if (vp->v_iflag & VI_DOINGINACT) {
3014                 vdropl(vp);
3015                 return;
3016         }
3017
3018         /*
3019          * Check if the fs wants to perform inactive processing. Note we
3020          * may be only holding the interlock, in which case it is possible
3021          * someone else called vgone on the vnode and ->v_data is now NULL.
3022          * Since vgone performs inactive on its own there is nothing to do
3023          * here but to drop our hold count.
3024          */
3025         if (__predict_false(vp->v_iflag & VI_DOOMED) ||
3026             VOP_NEED_INACTIVE(vp) == 0) {
3027                 vdropl(vp);
3028                 return;
3029         }
3030
3031         /*
3032          * We must call VOP_INACTIVE with the node locked. Mark
3033          * as VI_DOINGINACT to avoid recursion.
3034          */
3035         vp->v_iflag |= VI_OWEINACT;
3036         switch (func) {
3037         case VPUTX_VRELE:
3038                 error = vn_lock(vp, LK_EXCLUSIVE | LK_INTERLOCK);
3039                 VI_LOCK(vp);
3040                 break;
3041         case VPUTX_VPUT:
3042                 error = VOP_LOCK(vp, LK_EXCLUSIVE | LK_INTERLOCK | LK_NOWAIT);
3043                 VI_LOCK(vp);
3044                 break;
3045         case VPUTX_VUNREF:
3046                 error = 0;
3047                 if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE) {
3048                         error = VOP_LOCK(vp, LK_TRYUPGRADE | LK_INTERLOCK);
3049                         VI_LOCK(vp);
3050                 }
3051                 break;
3052         }
3053         VNASSERT(vp->v_usecount == 0 || (vp->v_iflag & VI_OWEINACT) == 0, vp,
3054             ("vnode with usecount and VI_OWEINACT set"));
3055         if (error == 0) {
3056                 if (vp->v_iflag & VI_OWEINACT)
3057                         vinactive(vp, curthread);
3058                 if (func != VPUTX_VUNREF)
3059                         VOP_UNLOCK(vp, 0);
3060         }
3061         vdropl(vp);
3062 }
3063
3064 /*
3065  * Vnode put/release.
3066  * If count drops to zero, call inactive routine and return to freelist.
3067  */
3068 void
3069 vrele(struct vnode *vp)
3070 {
3071
3072         vputx(vp, VPUTX_VRELE);
3073 }
3074
3075 /*
3076  * Release an already locked vnode.  This give the same effects as
3077  * unlock+vrele(), but takes less time and avoids releasing and
3078  * re-aquiring the lock (as vrele() acquires the lock internally.)
3079  *
3080  * It is an invariant that all VOP_* calls operate on a held vnode.
3081  * We may be only having an implicit hold stemming from our usecount,
3082  * which we are about to release. If we unlock the vnode afterwards we
3083  * open a time window where someone else dropped the last usecount and
3084  * proceeded to free the vnode before our unlock finished. For this
3085  * reason we unlock the vnode early. This is a little bit wasteful as
3086  * it may be the vnode is exclusively locked and inactive processing is
3087  * needed, in which case we are adding work.
3088  */
3089 void
3090 vput(struct vnode *vp)
3091 {
3092
3093         VOP_UNLOCK(vp, 0);
3094         vputx(vp, VPUTX_VPUT);
3095 }
3096
3097 /*
3098  * Release an exclusively locked vnode. Do not unlock the vnode lock.
3099  */
3100 void
3101 vunref(struct vnode *vp)
3102 {
3103
3104         vputx(vp, VPUTX_VUNREF);
3105 }
3106
3107 /*
3108  * Increase the hold count and activate if this is the first reference.
3109  */
3110 void
3111 _vhold(struct vnode *vp, bool locked)
3112 {
3113         struct mount *mp;
3114
3115         if (locked)
3116                 ASSERT_VI_LOCKED(vp, __func__);
3117         else
3118                 ASSERT_VI_UNLOCKED(vp, __func__);
3119         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3120         if (!locked) {
3121                 if (refcount_acquire_if_not_zero(&vp->v_holdcnt)) {
3122                         VNODE_REFCOUNT_FENCE_ACQ();
3123                         VNASSERT((vp->v_iflag & VI_FREE) == 0, vp,
3124                             ("_vhold: vnode with holdcnt is free"));
3125                         return;
3126                 }
3127                 VI_LOCK(vp);
3128         }
3129         if ((vp->v_iflag & VI_FREE) == 0) {
3130                 refcount_acquire(&vp->v_holdcnt);
3131                 if (!locked)
3132                         VI_UNLOCK(vp);
3133                 return;
3134         }
3135         VNASSERT(vp->v_holdcnt == 0, vp,
3136             ("%s: wrong hold count", __func__));
3137         VNASSERT(vp->v_op != NULL, vp,
3138             ("%s: vnode already reclaimed.", __func__));
3139         /*
3140          * Remove a vnode from the free list, mark it as in use,
3141          * and put it on the active list.
3142          */
3143         VNASSERT(vp->v_mount != NULL, vp,
3144             ("_vhold: vnode not on per mount vnode list"));
3145         mp = vp->v_mount;
3146         mtx_lock(&mp->mnt_listmtx);
3147         if ((vp->v_mflag & VMP_TMPMNTFREELIST) != 0) {
3148                 TAILQ_REMOVE(&mp->mnt_tmpfreevnodelist, vp, v_actfreelist);
3149                 mp->mnt_tmpfreevnodelistsize--;
3150                 vp->v_mflag &= ~VMP_TMPMNTFREELIST;
3151         } else {
3152                 mtx_lock(&vnode_free_list_mtx);
3153                 TAILQ_REMOVE(&vnode_free_list, vp, v_actfreelist);
3154                 freevnodes--;
3155                 mtx_unlock(&vnode_free_list_mtx);
3156         }
3157         KASSERT((vp->v_iflag & VI_ACTIVE) == 0,
3158             ("Activating already active vnode"));
3159         vp->v_iflag &= ~VI_FREE;
3160         vp->v_iflag |= VI_ACTIVE;
3161         TAILQ_INSERT_HEAD(&mp->mnt_activevnodelist, vp, v_actfreelist);
3162         mp->mnt_activevnodelistsize++;
3163         mtx_unlock(&mp->mnt_listmtx);
3164         refcount_acquire(&vp->v_holdcnt);
3165         if (!locked)
3166                 VI_UNLOCK(vp);
3167 }
3168
3169 void
3170 vholdnz(struct vnode *vp)
3171 {
3172
3173         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3174 #ifdef INVARIANTS
3175         int old = atomic_fetchadd_int(&vp->v_holdcnt, 1);
3176         VNASSERT(old > 0, vp, ("%s: wrong hold count", __func__));
3177 #else
3178         atomic_add_int(&vp->v_holdcnt, 1);
3179 #endif
3180 }
3181
3182 /*
3183  * Drop the hold count of the vnode.  If this is the last reference to
3184  * the vnode we place it on the free list unless it has been vgone'd
3185  * (marked VI_DOOMED) in which case we will free it.
3186  *
3187  * Because the vnode vm object keeps a hold reference on the vnode if
3188  * there is at least one resident non-cached page, the vnode cannot
3189  * leave the active list without the page cleanup done.
3190  */
3191 void
3192 _vdrop(struct vnode *vp, bool locked)
3193 {
3194         struct mount *mp;
3195
3196         if (locked)
3197                 ASSERT_VI_LOCKED(vp, __func__);
3198         else
3199                 ASSERT_VI_UNLOCKED(vp, __func__);
3200         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3201         if (__predict_false((int)vp->v_holdcnt <= 0)) {
3202                 vn_printf(vp, "vdrop: holdcnt %d", vp->v_holdcnt);
3203                 panic("vdrop: wrong holdcnt");
3204         }
3205         if (!locked) {
3206                 if (refcount_release_if_not_last(&vp->v_holdcnt))
3207                         return;
3208                 VI_LOCK(vp);
3209         }
3210         if (refcount_release(&vp->v_holdcnt) == 0) {
3211                 VI_UNLOCK(vp);
3212                 return;
3213         }
3214         if ((vp->v_iflag & VI_DOOMED) == 0) {
3215                 /*
3216                  * Mark a vnode as free: remove it from its active list
3217                  * and put it up for recycling on the freelist.
3218                  */
3219                 VNASSERT(vp->v_op != NULL, vp,
3220                     ("vdropl: vnode already reclaimed."));
3221                 VNASSERT((vp->v_iflag & VI_FREE) == 0, vp,
3222                     ("vnode already free"));
3223                 VNASSERT(vp->v_holdcnt == 0, vp,
3224                     ("vdropl: freeing when we shouldn't"));
3225                 if ((vp->v_iflag & VI_OWEINACT) == 0) {
3226                         mp = vp->v_mount;
3227                         if (mp != NULL) {
3228                                 mtx_lock(&mp->mnt_listmtx);
3229                                 if (vp->v_iflag & VI_ACTIVE) {
3230                                         vp->v_iflag &= ~VI_ACTIVE;
3231                                         TAILQ_REMOVE(&mp->mnt_activevnodelist,
3232                                             vp, v_actfreelist);
3233                                         mp->mnt_activevnodelistsize--;
3234                                 }
3235                                 TAILQ_INSERT_TAIL(&mp->mnt_tmpfreevnodelist,
3236                                     vp, v_actfreelist);
3237                                 mp->mnt_tmpfreevnodelistsize++;
3238                                 vp->v_iflag |= VI_FREE;
3239                                 vp->v_mflag |= VMP_TMPMNTFREELIST;
3240                                 VI_UNLOCK(vp);
3241                                 if (mp->mnt_tmpfreevnodelistsize >=
3242                                     mnt_free_list_batch)
3243                                         vnlru_return_batch_locked(mp);
3244                                 mtx_unlock(&mp->mnt_listmtx);
3245                         } else {
3246                                 VNASSERT((vp->v_iflag & VI_ACTIVE) == 0, vp,
3247                                     ("vdropl: active vnode not on per mount "
3248                                     "vnode list"));
3249                                 mtx_lock(&vnode_free_list_mtx);
3250                                 TAILQ_INSERT_TAIL(&vnode_free_list, vp,
3251                                     v_actfreelist);
3252                                 freevnodes++;
3253                                 vp->v_iflag |= VI_FREE;
3254                                 VI_UNLOCK(vp);
3255                                 mtx_unlock(&vnode_free_list_mtx);
3256                         }
3257                 } else {
3258                         VI_UNLOCK(vp);
3259                         counter_u64_add(free_owe_inact, 1);
3260                 }
3261                 return;
3262         }
3263         freevnode(vp);
3264 }
3265
3266 /*
3267  * Call VOP_INACTIVE on the vnode and manage the DOINGINACT and OWEINACT
3268  * flags.  DOINGINACT prevents us from recursing in calls to vinactive.
3269  * OWEINACT tracks whether a vnode missed a call to inactive due to a
3270  * failed lock upgrade.
3271  */
3272 void
3273 vinactive(struct vnode *vp, struct thread *td)
3274 {
3275         struct vm_object *obj;
3276
3277         ASSERT_VOP_ELOCKED(vp, "vinactive");
3278         ASSERT_VI_LOCKED(vp, "vinactive");
3279         VNASSERT((vp->v_iflag & VI_DOINGINACT) == 0, vp,
3280             ("vinactive: recursed on VI_DOINGINACT"));
3281         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3282         vp->v_iflag |= VI_DOINGINACT;
3283         vp->v_iflag &= ~VI_OWEINACT;
3284         VI_UNLOCK(vp);
3285         /*
3286          * Before moving off the active list, we must be sure that any
3287          * modified pages are converted into the vnode's dirty
3288          * buffers, since these will no longer be checked once the
3289          * vnode is on the inactive list.
3290          *
3291          * The write-out of the dirty pages is asynchronous.  At the
3292          * point that VOP_INACTIVE() is called, there could still be
3293          * pending I/O and dirty pages in the object.
3294          */
3295         if ((obj = vp->v_object) != NULL && (vp->v_vflag & VV_NOSYNC) == 0 &&
3296             vm_object_mightbedirty(obj)) {
3297                 VM_OBJECT_WLOCK(obj);
3298                 vm_object_page_clean(obj, 0, 0, 0);
3299                 VM_OBJECT_WUNLOCK(obj);
3300         }
3301         VOP_INACTIVE(vp, td);
3302         VI_LOCK(vp);
3303         VNASSERT(vp->v_iflag & VI_DOINGINACT, vp,
3304             ("vinactive: lost VI_DOINGINACT"));
3305         vp->v_iflag &= ~VI_DOINGINACT;
3306 }
3307
3308 /*
3309  * Remove any vnodes in the vnode table belonging to mount point mp.
3310  *
3311  * If FORCECLOSE is not specified, there should not be any active ones,
3312  * return error if any are found (nb: this is a user error, not a
3313  * system error). If FORCECLOSE is specified, detach any active vnodes
3314  * that are found.
3315  *
3316  * If WRITECLOSE is set, only flush out regular file vnodes open for
3317  * writing.
3318  *
3319  * SKIPSYSTEM causes any vnodes marked VV_SYSTEM to be skipped.
3320  *
3321  * `rootrefs' specifies the base reference count for the root vnode
3322  * of this filesystem. The root vnode is considered busy if its
3323  * v_usecount exceeds this value. On a successful return, vflush(, td)
3324  * will call vrele() on the root vnode exactly rootrefs times.
3325  * If the SKIPSYSTEM or WRITECLOSE flags are specified, rootrefs must
3326  * be zero.
3327  */
3328 #ifdef DIAGNOSTIC
3329 static int busyprt = 0;         /* print out busy vnodes */
3330 SYSCTL_INT(_debug, OID_AUTO, busyprt, CTLFLAG_RW, &busyprt, 0, "Print out busy vnodes");
3331 #endif
3332
3333 int
3334 vflush(struct mount *mp, int rootrefs, int flags, struct thread *td)
3335 {
3336         struct vnode *vp, *mvp, *rootvp = NULL;
3337         struct vattr vattr;
3338         int busy = 0, error;
3339
3340         CTR4(KTR_VFS, "%s: mp %p with rootrefs %d and flags %d", __func__, mp,
3341             rootrefs, flags);
3342         if (rootrefs > 0) {
3343                 KASSERT((flags & (SKIPSYSTEM | WRITECLOSE)) == 0,
3344                     ("vflush: bad args"));
3345                 /*
3346                  * Get the filesystem root vnode. We can vput() it
3347                  * immediately, since with rootrefs > 0, it won't go away.
3348                  */
3349                 if ((error = VFS_ROOT(mp, LK_EXCLUSIVE, &rootvp)) != 0) {
3350                         CTR2(KTR_VFS, "%s: vfs_root lookup failed with %d",
3351                             __func__, error);
3352                         return (error);
3353                 }
3354                 vput(rootvp);
3355         }
3356 loop:
3357         MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
3358                 vholdl(vp);
3359                 error = vn_lock(vp, LK_INTERLOCK | LK_EXCLUSIVE);
3360                 if (error) {
3361                         vdrop(vp);
3362                         MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
3363                         goto loop;
3364                 }
3365                 /*
3366                  * Skip over a vnodes marked VV_SYSTEM.
3367                  */
3368                 if ((flags & SKIPSYSTEM) && (vp->v_vflag & VV_SYSTEM)) {
3369                         VOP_UNLOCK(vp, 0);
3370                         vdrop(vp);
3371                         continue;
3372                 }
3373                 /*
3374                  * If WRITECLOSE is set, flush out unlinked but still open
3375                  * files (even if open only for reading) and regular file
3376                  * vnodes open for writing.
3377                  */
3378                 if (flags & WRITECLOSE) {
3379                         if (vp->v_object != NULL) {
3380                                 VM_OBJECT_WLOCK(vp->v_object);
3381                                 vm_object_page_clean(vp->v_object, 0, 0, 0);
3382                                 VM_OBJECT_WUNLOCK(vp->v_object);
3383                         }
3384                         error = VOP_FSYNC(vp, MNT_WAIT, td);
3385                         if (error != 0) {
3386                                 VOP_UNLOCK(vp, 0);
3387                                 vdrop(vp);
3388                                 MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
3389                                 return (error);
3390                         }
3391                         error = VOP_GETATTR(vp, &vattr, td->td_ucred);
3392                         VI_LOCK(vp);
3393
3394                         if ((vp->v_type == VNON ||
3395                             (error == 0 && vattr.va_nlink > 0)) &&
3396                             (vp->v_writecount <= 0 || vp->v_type != VREG)) {
3397                                 VOP_UNLOCK(vp, 0);
3398                                 vdropl(vp);
3399                                 continue;
3400                         }
3401                 } else
3402                         VI_LOCK(vp);
3403                 /*
3404                  * With v_usecount == 0, all we need to do is clear out the
3405                  * vnode data structures and we are done.
3406                  *
3407                  * If FORCECLOSE is set, forcibly close the vnode.
3408                  */
3409                 if (vp->v_usecount == 0 || (flags & FORCECLOSE)) {
3410                         vgonel(vp);
3411                 } else {
3412                         busy++;
3413 #ifdef DIAGNOSTIC
3414                         if (busyprt)
3415                                 vn_printf(vp, "vflush: busy vnode ");
3416 #endif
3417                 }
3418                 VOP_UNLOCK(vp, 0);
3419                 vdropl(vp);
3420         }
3421         if (rootrefs > 0 && (flags & FORCECLOSE) == 0) {
3422                 /*
3423                  * If just the root vnode is busy, and if its refcount
3424                  * is equal to `rootrefs', then go ahead and kill it.
3425                  */
3426                 VI_LOCK(rootvp);
3427                 KASSERT(busy > 0, ("vflush: not busy"));
3428                 VNASSERT(rootvp->v_usecount >= rootrefs, rootvp,
3429                     ("vflush: usecount %d < rootrefs %d",
3430                      rootvp->v_usecount, rootrefs));
3431                 if (busy == 1 && rootvp->v_usecount == rootrefs) {
3432                         VOP_LOCK(rootvp, LK_EXCLUSIVE|LK_INTERLOCK);
3433                         vgone(rootvp);
3434                         VOP_UNLOCK(rootvp, 0);
3435                         busy = 0;
3436                 } else
3437                         VI_UNLOCK(rootvp);
3438         }
3439         if (busy) {
3440                 CTR2(KTR_VFS, "%s: failing as %d vnodes are busy", __func__,
3441                     busy);
3442                 return (EBUSY);
3443         }
3444         for (; rootrefs > 0; rootrefs--)
3445                 vrele(rootvp);
3446         return (0);
3447 }
3448
3449 /*
3450  * Recycle an unused vnode to the front of the free list.
3451  */
3452 int
3453 vrecycle(struct vnode *vp)
3454 {
3455         int recycled;
3456
3457         VI_LOCK(vp);
3458         recycled = vrecyclel(vp);
3459         VI_UNLOCK(vp);
3460         return (recycled);
3461 }
3462
3463 /*
3464  * vrecycle, with the vp interlock held.
3465  */
3466 int
3467 vrecyclel(struct vnode *vp)
3468 {
3469         int recycled;
3470
3471         ASSERT_VOP_ELOCKED(vp, __func__);
3472         ASSERT_VI_LOCKED(vp, __func__);
3473         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3474         recycled = 0;
3475         if (vp->v_usecount == 0) {
3476                 recycled = 1;
3477                 vgonel(vp);
3478         }
3479         return (recycled);
3480 }
3481
3482 /*
3483  * Eliminate all activity associated with a vnode
3484  * in preparation for reuse.
3485  */
3486 void
3487 vgone(struct vnode *vp)
3488 {
3489         VI_LOCK(vp);
3490         vgonel(vp);
3491         VI_UNLOCK(vp);
3492 }
3493
3494 static void
3495 notify_lowervp_vfs_dummy(struct mount *mp __unused,
3496     struct vnode *lowervp __unused)
3497 {
3498 }
3499
3500 /*
3501  * Notify upper mounts about reclaimed or unlinked vnode.
3502  */
3503 void
3504 vfs_notify_upper(struct vnode *vp, int event)
3505 {
3506         static struct vfsops vgonel_vfsops = {
3507                 .vfs_reclaim_lowervp = notify_lowervp_vfs_dummy,
3508                 .vfs_unlink_lowervp = notify_lowervp_vfs_dummy,
3509         };
3510         struct mount *mp, *ump, *mmp;
3511
3512         mp = vp->v_mount;
3513         if (mp == NULL)
3514                 return;
3515         if (TAILQ_EMPTY(&mp->mnt_uppers))
3516                 return;
3517
3518         mmp = malloc(sizeof(struct mount), M_TEMP, M_WAITOK | M_ZERO);
3519         mmp->mnt_op = &vgonel_vfsops;
3520         mmp->mnt_kern_flag |= MNTK_MARKER;
3521         MNT_ILOCK(mp);
3522         mp->mnt_kern_flag |= MNTK_VGONE_UPPER;
3523         for (ump = TAILQ_FIRST(&mp->mnt_uppers); ump != NULL;) {
3524                 if ((ump->mnt_kern_flag & MNTK_MARKER) != 0) {
3525                         ump = TAILQ_NEXT(ump, mnt_upper_link);
3526                         continue;
3527                 }
3528                 TAILQ_INSERT_AFTER(&mp->mnt_uppers, ump, mmp, mnt_upper_link);
3529                 MNT_IUNLOCK(mp);
3530                 switch (event) {
3531                 case VFS_NOTIFY_UPPER_RECLAIM:
3532                         VFS_RECLAIM_LOWERVP(ump, vp);
3533                         break;
3534                 case VFS_NOTIFY_UPPER_UNLINK:
3535                         VFS_UNLINK_LOWERVP(ump, vp);
3536                         break;
3537                 default:
3538                         KASSERT(0, ("invalid event %d", event));
3539                         break;
3540                 }
3541                 MNT_ILOCK(mp);
3542                 ump = TAILQ_NEXT(mmp, mnt_upper_link);
3543                 TAILQ_REMOVE(&mp->mnt_uppers, mmp, mnt_upper_link);
3544         }
3545         free(mmp, M_TEMP);
3546         mp->mnt_kern_flag &= ~MNTK_VGONE_UPPER;
3547         if ((mp->mnt_kern_flag & MNTK_VGONE_WAITER) != 0) {
3548                 mp->mnt_kern_flag &= ~MNTK_VGONE_WAITER;
3549                 wakeup(&mp->mnt_uppers);
3550         }
3551         MNT_IUNLOCK(mp);
3552 }
3553
3554 /*
3555  * vgone, with the vp interlock held.
3556  */
3557 static void
3558 vgonel(struct vnode *vp)
3559 {
3560         struct thread *td;
3561         struct mount *mp;
3562         vm_object_t object;
3563         bool active, oweinact;
3564
3565         ASSERT_VOP_ELOCKED(vp, "vgonel");
3566         ASSERT_VI_LOCKED(vp, "vgonel");
3567         VNASSERT(vp->v_holdcnt, vp,
3568             ("vgonel: vp %p has no reference.", vp));
3569         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3570         td = curthread;
3571
3572         /*
3573          * Don't vgonel if we're already doomed.
3574          */
3575         if (vp->v_iflag & VI_DOOMED)
3576                 return;
3577         vp->v_iflag |= VI_DOOMED;
3578
3579         /*
3580          * Check to see if the vnode is in use.  If so, we have to call
3581          * VOP_CLOSE() and VOP_INACTIVE().
3582          */
3583         active = vp->v_usecount > 0;
3584         oweinact = (vp->v_iflag & VI_OWEINACT) != 0;
3585         VI_UNLOCK(vp);
3586         vfs_notify_upper(vp, VFS_NOTIFY_UPPER_RECLAIM);
3587
3588         /*
3589          * If purging an active vnode, it must be closed and
3590          * deactivated before being reclaimed.
3591          */
3592         if (active)
3593                 VOP_CLOSE(vp, FNONBLOCK, NOCRED, td);
3594         if (oweinact || active) {
3595                 VI_LOCK(vp);
3596                 if ((vp->v_iflag & VI_DOINGINACT) == 0)
3597                         vinactive(vp, td);
3598                 VI_UNLOCK(vp);
3599         }
3600         if (vp->v_type == VSOCK)
3601                 vfs_unp_reclaim(vp);
3602
3603         /*
3604          * Clean out any buffers associated with the vnode.
3605          * If the flush fails, just toss the buffers.
3606          */
3607         mp = NULL;
3608         if (!TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd))
3609                 (void) vn_start_secondary_write(vp, &mp, V_WAIT);
3610         if (vinvalbuf(vp, V_SAVE, 0, 0) != 0) {
3611                 while (vinvalbuf(vp, 0, 0, 0) != 0)
3612                         ;
3613         }
3614
3615         BO_LOCK(&vp->v_bufobj);
3616         KASSERT(TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd) &&
3617             vp->v_bufobj.bo_dirty.bv_cnt == 0 &&
3618             TAILQ_EMPTY(&vp->v_bufobj.bo_clean.bv_hd) &&
3619             vp->v_bufobj.bo_clean.bv_cnt == 0,
3620             ("vp %p bufobj not invalidated", vp));
3621
3622         /*
3623          * For VMIO bufobj, BO_DEAD is set later, or in
3624          * vm_object_terminate() after the object's page queue is
3625          * flushed.
3626          */
3627         object = vp->v_bufobj.bo_object;
3628         if (object == NULL)
3629                 vp->v_bufobj.bo_flag |= BO_DEAD;
3630         BO_UNLOCK(&vp->v_bufobj);
3631
3632         /*
3633          * Handle the VM part.  Tmpfs handles v_object on its own (the
3634          * OBJT_VNODE check).  Nullfs or other bypassing filesystems
3635          * should not touch the object borrowed from the lower vnode
3636          * (the handle check).
3637          */
3638         if (object != NULL && object->type == OBJT_VNODE &&
3639             object->handle == vp)
3640                 vnode_destroy_vobject(vp);
3641
3642         /*
3643          * Reclaim the vnode.
3644          */
3645         if (VOP_RECLAIM(vp, td))
3646                 panic("vgone: cannot reclaim");
3647         if (mp != NULL)
3648                 vn_finished_secondary_write(mp);
3649         VNASSERT(vp->v_object == NULL, vp,
3650             ("vop_reclaim left v_object vp=%p, tag=%s", vp, vp->v_tag));
3651         /*
3652          * Clear the advisory locks and wake up waiting threads.
3653          */
3654         (void)VOP_ADVLOCKPURGE(vp);
3655         vp->v_lockf = NULL;
3656         /*
3657          * Delete from old mount point vnode list.
3658          */
3659         delmntque(vp);
3660         cache_purge(vp);
3661         /*
3662          * Done with purge, reset to the standard lock and invalidate
3663          * the vnode.
3664          */
3665         VI_LOCK(vp);
3666         vp->v_vnlock = &vp->v_lock;
3667         vp->v_op = &dead_vnodeops;
3668         vp->v_tag = "none";
3669         vp->v_type = VBAD;
3670 }
3671
3672 /*
3673  * Calculate the total number of references to a special device.
3674  */
3675 int
3676 vcount(struct vnode *vp)
3677 {
3678         int count;
3679
3680         dev_lock();
3681         count = vp->v_rdev->si_usecount;
3682         dev_unlock();
3683         return (count);
3684 }
3685
3686 /*
3687  * Print out a description of a vnode.
3688  */
3689 static char *typename[] =
3690 {"VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD",
3691  "VMARKER"};
3692
3693 void
3694 vn_printf(struct vnode *vp, const char *fmt, ...)
3695 {
3696         va_list ap;
3697         char buf[256], buf2[16];
3698         u_long flags;
3699
3700         va_start(ap, fmt);
3701         vprintf(fmt, ap);
3702         va_end(ap);
3703         printf("%p: ", (void *)vp);
3704         printf("tag %s, type %s\n", vp->v_tag, typename[vp->v_type]);
3705         printf("    usecount %d, writecount %d, refcount %d",
3706             vp->v_usecount, vp->v_writecount, vp->v_holdcnt);
3707         switch (vp->v_type) {
3708         case VDIR:
3709                 printf(" mountedhere %p\n", vp->v_mountedhere);
3710                 break;
3711         case VCHR:
3712                 printf(" rdev %p\n", vp->v_rdev);
3713                 break;
3714         case VSOCK:
3715                 printf(" socket %p\n", vp->v_unpcb);
3716                 break;
3717         case VFIFO:
3718                 printf(" fifoinfo %p\n", vp->v_fifoinfo);
3719                 break;
3720         default:
3721                 printf("\n");
3722                 break;
3723         }
3724         buf[0] = '\0';
3725         buf[1] = '\0';
3726         if (vp->v_vflag & VV_ROOT)
3727                 strlcat(buf, "|VV_ROOT", sizeof(buf));
3728         if (vp->v_vflag & VV_ISTTY)
3729                 strlcat(buf, "|VV_ISTTY", sizeof(buf));
3730         if (vp->v_vflag & VV_NOSYNC)
3731                 strlcat(buf, "|VV_NOSYNC", sizeof(buf));
3732         if (vp->v_vflag & VV_ETERNALDEV)
3733                 strlcat(buf, "|VV_ETERNALDEV", sizeof(buf));
3734         if (vp->v_vflag & VV_CACHEDLABEL)
3735                 strlcat(buf, "|VV_CACHEDLABEL", sizeof(buf));
3736         if (vp->v_vflag & VV_VMSIZEVNLOCK)
3737                 strlcat(buf, "|VV_VMSIZEVNLOCK", sizeof(buf));
3738         if (vp->v_vflag & VV_COPYONWRITE)
3739                 strlcat(buf, "|VV_COPYONWRITE", sizeof(buf));
3740         if (vp->v_vflag & VV_SYSTEM)
3741                 strlcat(buf, "|VV_SYSTEM", sizeof(buf));
3742         if (vp->v_vflag & VV_PROCDEP)
3743                 strlcat(buf, "|VV_PROCDEP", sizeof(buf));
3744         if (vp->v_vflag & VV_NOKNOTE)
3745                 strlcat(buf, "|VV_NOKNOTE", sizeof(buf));
3746         if (vp->v_vflag & VV_DELETED)
3747                 strlcat(buf, "|VV_DELETED", sizeof(buf));
3748         if (vp->v_vflag & VV_MD)
3749                 strlcat(buf, "|VV_MD", sizeof(buf));
3750         if (vp->v_vflag & VV_FORCEINSMQ)
3751                 strlcat(buf, "|VV_FORCEINSMQ", sizeof(buf));
3752         if (vp->v_vflag & VV_READLINK)
3753                 strlcat(buf, "|VV_READLINK", sizeof(buf));
3754         flags = vp->v_vflag & ~(VV_ROOT | VV_ISTTY | VV_NOSYNC | VV_ETERNALDEV |
3755             VV_CACHEDLABEL | VV_COPYONWRITE | VV_SYSTEM | VV_PROCDEP |
3756             VV_NOKNOTE | VV_DELETED | VV_MD | VV_FORCEINSMQ);
3757         if (flags != 0) {
3758                 snprintf(buf2, sizeof(buf2), "|VV(0x%lx)", flags);
3759                 strlcat(buf, buf2, sizeof(buf));
3760         }
3761         if (vp->v_iflag & VI_TEXT_REF)
3762                 strlcat(buf, "|VI_TEXT_REF", sizeof(buf));
3763         if (vp->v_iflag & VI_MOUNT)
3764                 strlcat(buf, "|VI_MOUNT", sizeof(buf));
3765         if (vp->v_iflag & VI_DOOMED)
3766                 strlcat(buf, "|VI_DOOMED", sizeof(buf));
3767         if (vp->v_iflag & VI_FREE)
3768                 strlcat(buf, "|VI_FREE", sizeof(buf));
3769         if (vp->v_iflag & VI_ACTIVE)
3770                 strlcat(buf, "|VI_ACTIVE", sizeof(buf));
3771         if (vp->v_iflag & VI_DOINGINACT)
3772                 strlcat(buf, "|VI_DOINGINACT", sizeof(buf));
3773         if (vp->v_iflag & VI_OWEINACT)
3774                 strlcat(buf, "|VI_OWEINACT", sizeof(buf));
3775         flags = vp->v_iflag & ~(VI_TEXT_REF | VI_MOUNT | VI_DOOMED | VI_FREE |
3776             VI_ACTIVE | VI_DOINGINACT | VI_OWEINACT);
3777         if (flags != 0) {
3778                 snprintf(buf2, sizeof(buf2), "|VI(0x%lx)", flags);
3779                 strlcat(buf, buf2, sizeof(buf));
3780         }
3781         if (vp->v_mflag & VMP_TMPMNTFREELIST)
3782                 strlcat(buf, "|VMP_TMPMNTFREELIST", sizeof(buf));
3783         flags = vp->v_mflag & ~(VMP_TMPMNTFREELIST);
3784         if (flags != 0) {
3785                 snprintf(buf2, sizeof(buf2), "|VMP(0x%lx)", flags);
3786                 strlcat(buf, buf2, sizeof(buf));
3787         }
3788         printf("    flags (%s)\n", buf + 1);
3789         if (mtx_owned(VI_MTX(vp)))
3790                 printf(" VI_LOCKed");
3791         if (vp->v_object != NULL)
3792                 printf("    v_object %p ref %d pages %d "
3793                     "cleanbuf %d dirtybuf %d\n",
3794                     vp->v_object, vp->v_object->ref_count,
3795                     vp->v_object->resident_page_count,
3796                     vp->v_bufobj.bo_clean.bv_cnt,
3797                     vp->v_bufobj.bo_dirty.bv_cnt);
3798         printf("    ");
3799         lockmgr_printinfo(vp->v_vnlock);
3800         if (vp->v_data != NULL)
3801                 VOP_PRINT(vp);
3802 }
3803
3804 #ifdef DDB
3805 /*
3806  * List all of the locked vnodes in the system.
3807  * Called when debugging the kernel.
3808  */
3809 DB_SHOW_COMMAND(lockedvnods, lockedvnodes)
3810 {
3811         struct mount *mp;
3812         struct vnode *vp;
3813
3814         /*
3815          * Note: because this is DDB, we can't obey the locking semantics
3816          * for these structures, which means we could catch an inconsistent
3817          * state and dereference a nasty pointer.  Not much to be done
3818          * about that.
3819          */
3820         db_printf("Locked vnodes\n");
3821         TAILQ_FOREACH(mp, &mountlist, mnt_list) {
3822                 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
3823                         if (vp->v_type != VMARKER && VOP_ISLOCKED(vp))
3824                                 vn_printf(vp, "vnode ");
3825                 }
3826         }
3827 }
3828
3829 /*
3830  * Show details about the given vnode.
3831  */
3832 DB_SHOW_COMMAND(vnode, db_show_vnode)
3833 {
3834         struct vnode *vp;
3835
3836         if (!have_addr)
3837                 return;
3838         vp = (struct vnode *)addr;
3839         vn_printf(vp, "vnode ");
3840 }
3841
3842 /*
3843  * Show details about the given mount point.
3844  */
3845 DB_SHOW_COMMAND(mount, db_show_mount)
3846 {
3847         struct mount *mp;
3848         struct vfsopt *opt;
3849         struct statfs *sp;
3850         struct vnode *vp;
3851         char buf[512];
3852         uint64_t mflags;
3853         u_int flags;
3854
3855         if (!have_addr) {
3856                 /* No address given, print short info about all mount points. */
3857                 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
3858                         db_printf("%p %s on %s (%s)\n", mp,
3859                             mp->mnt_stat.f_mntfromname,
3860                             mp->mnt_stat.f_mntonname,
3861                             mp->mnt_stat.f_fstypename);
3862                         if (db_pager_quit)
3863                                 break;
3864                 }
3865                 db_printf("\nMore info: show mount <addr>\n");
3866                 return;
3867         }
3868
3869         mp = (struct mount *)addr;
3870         db_printf("%p %s on %s (%s)\n", mp, mp->mnt_stat.f_mntfromname,
3871             mp->mnt_stat.f_mntonname, mp->mnt_stat.f_fstypename);
3872
3873         buf[0] = '\0';
3874         mflags = mp->mnt_flag;
3875 #define MNT_FLAG(flag)  do {                                            \
3876         if (mflags & (flag)) {                                          \
3877                 if (buf[0] != '\0')                                     \
3878                         strlcat(buf, ", ", sizeof(buf));                \
3879                 strlcat(buf, (#flag) + 4, sizeof(buf));                 \
3880                 mflags &= ~(flag);                                      \
3881         }                                                               \
3882 } while (0)
3883         MNT_FLAG(MNT_RDONLY);
3884         MNT_FLAG(MNT_SYNCHRONOUS);
3885         MNT_FLAG(MNT_NOEXEC);
3886         MNT_FLAG(MNT_NOSUID);
3887         MNT_FLAG(MNT_NFS4ACLS);
3888         MNT_FLAG(MNT_UNION);
3889         MNT_FLAG(MNT_ASYNC);
3890         MNT_FLAG(MNT_SUIDDIR);
3891         MNT_FLAG(MNT_SOFTDEP);
3892         MNT_FLAG(MNT_NOSYMFOLLOW);
3893         MNT_FLAG(MNT_GJOURNAL);
3894         MNT_FLAG(MNT_MULTILABEL);
3895         MNT_FLAG(MNT_ACLS);
3896         MNT_FLAG(MNT_NOATIME);
3897         MNT_FLAG(MNT_NOCLUSTERR);
3898         MNT_FLAG(MNT_NOCLUSTERW);
3899         MNT_FLAG(MNT_SUJ);
3900         MNT_FLAG(MNT_EXRDONLY);
3901         MNT_FLAG(MNT_EXPORTED);
3902         MNT_FLAG(MNT_DEFEXPORTED);
3903         MNT_FLAG(MNT_EXPORTANON);
3904         MNT_FLAG(MNT_EXKERB);
3905         MNT_FLAG(MNT_EXPUBLIC);
3906         MNT_FLAG(MNT_LOCAL);
3907         MNT_FLAG(MNT_QUOTA);
3908         MNT_FLAG(MNT_ROOTFS);
3909         MNT_FLAG(MNT_USER);
3910         MNT_FLAG(MNT_IGNORE);
3911         MNT_FLAG(MNT_UPDATE);
3912         MNT_FLAG(MNT_DELEXPORT);
3913         MNT_FLAG(MNT_RELOAD);
3914         MNT_FLAG(MNT_FORCE);
3915         MNT_FLAG(MNT_SNAPSHOT);
3916         MNT_FLAG(MNT_BYFSID);
3917 #undef MNT_FLAG
3918         if (mflags != 0) {
3919                 if (buf[0] != '\0')
3920                         strlcat(buf, ", ", sizeof(buf));
3921                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
3922                     "0x%016jx", mflags);
3923         }
3924         db_printf("    mnt_flag = %s\n", buf);
3925
3926         buf[0] = '\0';
3927         flags = mp->mnt_kern_flag;
3928 #define MNT_KERN_FLAG(flag)     do {                                    \
3929         if (flags & (flag)) {                                           \
3930                 if (buf[0] != '\0')                                     \
3931                         strlcat(buf, ", ", sizeof(buf));                \
3932                 strlcat(buf, (#flag) + 5, sizeof(buf));                 \
3933                 flags &= ~(flag);                                       \
3934         }                                                               \
3935 } while (0)
3936         MNT_KERN_FLAG(MNTK_UNMOUNTF);
3937         MNT_KERN_FLAG(MNTK_ASYNC);
3938         MNT_KERN_FLAG(MNTK_SOFTDEP);
3939         MNT_KERN_FLAG(MNTK_DRAINING);
3940         MNT_KERN_FLAG(MNTK_REFEXPIRE);
3941         MNT_KERN_FLAG(MNTK_EXTENDED_SHARED);
3942         MNT_KERN_FLAG(MNTK_SHARED_WRITES);
3943         MNT_KERN_FLAG(MNTK_NO_IOPF);
3944         MNT_KERN_FLAG(MNTK_VGONE_UPPER);
3945         MNT_KERN_FLAG(MNTK_VGONE_WAITER);
3946         MNT_KERN_FLAG(MNTK_LOOKUP_EXCL_DOTDOT);
3947         MNT_KERN_FLAG(MNTK_MARKER);
3948         MNT_KERN_FLAG(MNTK_USES_BCACHE);
3949         MNT_KERN_FLAG(MNTK_NOASYNC);
3950         MNT_KERN_FLAG(MNTK_UNMOUNT);
3951         MNT_KERN_FLAG(MNTK_MWAIT);
3952         MNT_KERN_FLAG(MNTK_SUSPEND);
3953         MNT_KERN_FLAG(MNTK_SUSPEND2);
3954         MNT_KERN_FLAG(MNTK_SUSPENDED);
3955         MNT_KERN_FLAG(MNTK_LOOKUP_SHARED);
3956         MNT_KERN_FLAG(MNTK_NOKNOTE);
3957 #undef MNT_KERN_FLAG
3958         if (flags != 0) {
3959                 if (buf[0] != '\0')
3960                         strlcat(buf, ", ", sizeof(buf));
3961                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
3962                     "0x%08x", flags);
3963         }
3964         db_printf("    mnt_kern_flag = %s\n", buf);
3965
3966         db_printf("    mnt_opt = ");
3967         opt = TAILQ_FIRST(mp->mnt_opt);
3968         if (opt != NULL) {
3969                 db_printf("%s", opt->name);
3970                 opt = TAILQ_NEXT(opt, link);
3971                 while (opt != NULL) {
3972                         db_printf(", %s", opt->name);
3973                         opt = TAILQ_NEXT(opt, link);
3974                 }
3975         }
3976         db_printf("\n");
3977
3978         sp = &mp->mnt_stat;
3979         db_printf("    mnt_stat = { version=%u type=%u flags=0x%016jx "
3980             "bsize=%ju iosize=%ju blocks=%ju bfree=%ju bavail=%jd files=%ju "
3981             "ffree=%jd syncwrites=%ju asyncwrites=%ju syncreads=%ju "
3982             "asyncreads=%ju namemax=%u owner=%u fsid=[%d, %d] }\n",
3983             (u_int)sp->f_version, (u_int)sp->f_type, (uintmax_t)sp->f_flags,
3984             (uintmax_t)sp->f_bsize, (uintmax_t)sp->f_iosize,
3985             (uintmax_t)sp->f_blocks, (uintmax_t)sp->f_bfree,
3986             (intmax_t)sp->f_bavail, (uintmax_t)sp->f_files,
3987             (intmax_t)sp->f_ffree, (uintmax_t)sp->f_syncwrites,
3988             (uintmax_t)sp->f_asyncwrites, (uintmax_t)sp->f_syncreads,
3989             (uintmax_t)sp->f_asyncreads, (u_int)sp->f_namemax,
3990             (u_int)sp->f_owner, (int)sp->f_fsid.val[0], (int)sp->f_fsid.val[1]);
3991
3992         db_printf("    mnt_cred = { uid=%u ruid=%u",
3993             (u_int)mp->mnt_cred->cr_uid, (u_int)mp->mnt_cred->cr_ruid);
3994         if (jailed(mp->mnt_cred))
3995                 db_printf(", jail=%d", mp->mnt_cred->cr_prison->pr_id);
3996         db_printf(" }\n");
3997         db_printf("    mnt_ref = %d (with %d in the struct)\n",
3998             vfs_mount_fetch_counter(mp, MNT_COUNT_REF), mp->mnt_ref);
3999         db_printf("    mnt_gen = %d\n", mp->mnt_gen);
4000         db_printf("    mnt_nvnodelistsize = %d\n", mp->mnt_nvnodelistsize);
4001         db_printf("    mnt_activevnodelistsize = %d\n",
4002             mp->mnt_activevnodelistsize);
4003         db_printf("    mnt_writeopcount = %d (with %d in the struct)\n",
4004             vfs_mount_fetch_counter(mp, MNT_COUNT_WRITEOPCOUNT), mp->mnt_writeopcount);
4005         db_printf("    mnt_maxsymlinklen = %d\n", mp->mnt_maxsymlinklen);
4006         db_printf("    mnt_iosize_max = %d\n", mp->mnt_iosize_max);
4007         db_printf("    mnt_hashseed = %u\n", mp->mnt_hashseed);
4008         db_printf("    mnt_lockref = %d (with %d in the struct)\n",
4009             vfs_mount_fetch_counter(mp, MNT_COUNT_LOCKREF), mp->mnt_lockref);
4010         db_printf("    mnt_secondary_writes = %d\n", mp->mnt_secondary_writes);
4011         db_printf("    mnt_secondary_accwrites = %d\n",
4012             mp->mnt_secondary_accwrites);
4013         db_printf("    mnt_gjprovider = %s\n",
4014             mp->mnt_gjprovider != NULL ? mp->mnt_gjprovider : "NULL");
4015         db_printf("    mnt_vfs_ops = %d\n", mp->mnt_vfs_ops);
4016
4017         db_printf("\n\nList of active vnodes\n");
4018         TAILQ_FOREACH(vp, &mp->mnt_activevnodelist, v_actfreelist) {
4019                 if (vp->v_type != VMARKER) {
4020                         vn_printf(vp, "vnode ");
4021                         if (db_pager_quit)
4022                                 break;
4023                 }
4024         }
4025         db_printf("\n\nList of inactive vnodes\n");
4026         TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4027                 if (vp->v_type != VMARKER && (vp->v_iflag & VI_ACTIVE) == 0) {
4028                         vn_printf(vp, "vnode ");
4029                         if (db_pager_quit)
4030                                 break;
4031                 }
4032         }
4033 }
4034 #endif  /* DDB */
4035
4036 /*
4037  * Fill in a struct xvfsconf based on a struct vfsconf.
4038  */
4039 static int
4040 vfsconf2x(struct sysctl_req *req, struct vfsconf *vfsp)
4041 {
4042         struct xvfsconf xvfsp;
4043
4044         bzero(&xvfsp, sizeof(xvfsp));
4045         strcpy(xvfsp.vfc_name, vfsp->vfc_name);
4046         xvfsp.vfc_typenum = vfsp->vfc_typenum;
4047         xvfsp.vfc_refcount = vfsp->vfc_refcount;
4048         xvfsp.vfc_flags = vfsp->vfc_flags;
4049         /*
4050          * These are unused in userland, we keep them
4051          * to not break binary compatibility.
4052          */
4053         xvfsp.vfc_vfsops = NULL;
4054         xvfsp.vfc_next = NULL;
4055         return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
4056 }
4057
4058 #ifdef COMPAT_FREEBSD32
4059 struct xvfsconf32 {
4060         uint32_t        vfc_vfsops;
4061         char            vfc_name[MFSNAMELEN];
4062         int32_t         vfc_typenum;
4063         int32_t         vfc_refcount;
4064         int32_t         vfc_flags;
4065         uint32_t        vfc_next;
4066 };
4067
4068 static int
4069 vfsconf2x32(struct sysctl_req *req, struct vfsconf *vfsp)
4070 {
4071         struct xvfsconf32 xvfsp;
4072
4073         bzero(&xvfsp, sizeof(xvfsp));
4074         strcpy(xvfsp.vfc_name, vfsp->vfc_name);
4075         xvfsp.vfc_typenum = vfsp->vfc_typenum;
4076         xvfsp.vfc_refcount = vfsp->vfc_refcount;
4077         xvfsp.vfc_flags = vfsp->vfc_flags;
4078         return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
4079 }
4080 #endif
4081
4082 /*
4083  * Top level filesystem related information gathering.
4084  */
4085 static int
4086 sysctl_vfs_conflist(SYSCTL_HANDLER_ARGS)
4087 {
4088         struct vfsconf *vfsp;
4089         int error;
4090
4091         error = 0;
4092         vfsconf_slock();
4093         TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4094 #ifdef COMPAT_FREEBSD32
4095                 if (req->flags & SCTL_MASK32)
4096                         error = vfsconf2x32(req, vfsp);
4097                 else
4098 #endif
4099                         error = vfsconf2x(req, vfsp);
4100                 if (error)
4101                         break;
4102         }
4103         vfsconf_sunlock();
4104         return (error);
4105 }
4106
4107 SYSCTL_PROC(_vfs, OID_AUTO, conflist, CTLTYPE_OPAQUE | CTLFLAG_RD |
4108     CTLFLAG_MPSAFE, NULL, 0, sysctl_vfs_conflist,
4109     "S,xvfsconf", "List of all configured filesystems");
4110
4111 #ifndef BURN_BRIDGES
4112 static int      sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS);
4113
4114 static int
4115 vfs_sysctl(SYSCTL_HANDLER_ARGS)
4116 {
4117         int *name = (int *)arg1 - 1;    /* XXX */
4118         u_int namelen = arg2 + 1;       /* XXX */
4119         struct vfsconf *vfsp;
4120
4121         log(LOG_WARNING, "userland calling deprecated sysctl, "
4122             "please rebuild world\n");
4123
4124 #if 1 || defined(COMPAT_PRELITE2)
4125         /* Resolve ambiguity between VFS_VFSCONF and VFS_GENERIC. */
4126         if (namelen == 1)
4127                 return (sysctl_ovfs_conf(oidp, arg1, arg2, req));
4128 #endif
4129
4130         switch (name[1]) {
4131         case VFS_MAXTYPENUM:
4132                 if (namelen != 2)
4133                         return (ENOTDIR);
4134                 return (SYSCTL_OUT(req, &maxvfsconf, sizeof(int)));
4135         case VFS_CONF:
4136                 if (namelen != 3)
4137                         return (ENOTDIR);       /* overloaded */
4138                 vfsconf_slock();
4139                 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4140                         if (vfsp->vfc_typenum == name[2])
4141                                 break;
4142                 }
4143                 vfsconf_sunlock();
4144                 if (vfsp == NULL)
4145                         return (EOPNOTSUPP);
4146 #ifdef COMPAT_FREEBSD32
4147                 if (req->flags & SCTL_MASK32)
4148                         return (vfsconf2x32(req, vfsp));
4149                 else
4150 #endif
4151                         return (vfsconf2x(req, vfsp));
4152         }
4153         return (EOPNOTSUPP);
4154 }
4155
4156 static SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RD | CTLFLAG_SKIP |
4157     CTLFLAG_MPSAFE, vfs_sysctl,
4158     "Generic filesystem");
4159
4160 #if 1 || defined(COMPAT_PRELITE2)
4161
4162 static int
4163 sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS)
4164 {
4165         int error;
4166         struct vfsconf *vfsp;
4167         struct ovfsconf ovfs;
4168
4169         vfsconf_slock();
4170         TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4171                 bzero(&ovfs, sizeof(ovfs));
4172                 ovfs.vfc_vfsops = vfsp->vfc_vfsops;     /* XXX used as flag */
4173                 strcpy(ovfs.vfc_name, vfsp->vfc_name);
4174                 ovfs.vfc_index = vfsp->vfc_typenum;
4175                 ovfs.vfc_refcount = vfsp->vfc_refcount;
4176                 ovfs.vfc_flags = vfsp->vfc_flags;
4177                 error = SYSCTL_OUT(req, &ovfs, sizeof ovfs);
4178                 if (error != 0) {
4179                         vfsconf_sunlock();
4180                         return (error);
4181                 }
4182         }
4183         vfsconf_sunlock();
4184         return (0);
4185 }
4186
4187 #endif /* 1 || COMPAT_PRELITE2 */
4188 #endif /* !BURN_BRIDGES */
4189
4190 #define KINFO_VNODESLOP         10
4191 #ifdef notyet
4192 /*
4193  * Dump vnode list (via sysctl).
4194  */
4195 /* ARGSUSED */
4196 static int
4197 sysctl_vnode(SYSCTL_HANDLER_ARGS)
4198 {
4199         struct xvnode *xvn;
4200         struct mount *mp;
4201         struct vnode *vp;
4202         int error, len, n;
4203
4204         /*
4205          * Stale numvnodes access is not fatal here.
4206          */
4207         req->lock = 0;
4208         len = (numvnodes + KINFO_VNODESLOP) * sizeof *xvn;
4209         if (!req->oldptr)
4210                 /* Make an estimate */
4211                 return (SYSCTL_OUT(req, 0, len));
4212
4213         error = sysctl_wire_old_buffer(req, 0);
4214         if (error != 0)
4215                 return (error);
4216         xvn = malloc(len, M_TEMP, M_ZERO | M_WAITOK);
4217         n = 0;
4218         mtx_lock(&mountlist_mtx);
4219         TAILQ_FOREACH(mp, &mountlist, mnt_list) {
4220                 if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK))
4221                         continue;
4222                 MNT_ILOCK(mp);
4223                 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4224                         if (n == len)
4225                                 break;
4226                         vref(vp);
4227                         xvn[n].xv_size = sizeof *xvn;
4228                         xvn[n].xv_vnode = vp;
4229                         xvn[n].xv_id = 0;       /* XXX compat */
4230 #define XV_COPY(field) xvn[n].xv_##field = vp->v_##field
4231                         XV_COPY(usecount);
4232                         XV_COPY(writecount);
4233                         XV_COPY(holdcnt);
4234                         XV_COPY(mount);
4235                         XV_COPY(numoutput);
4236                         XV_COPY(type);
4237 #undef XV_COPY
4238                         xvn[n].xv_flag = vp->v_vflag;
4239
4240                         switch (vp->v_type) {
4241                         case VREG:
4242                         case VDIR:
4243                         case VLNK:
4244                                 break;
4245                         case VBLK:
4246                         case VCHR:
4247                                 if (vp->v_rdev == NULL) {
4248                                         vrele(vp);
4249                                         continue;
4250                                 }
4251                                 xvn[n].xv_dev = dev2udev(vp->v_rdev);
4252                                 break;
4253                         case VSOCK:
4254                                 xvn[n].xv_socket = vp->v_socket;
4255                                 break;
4256                         case VFIFO:
4257                                 xvn[n].xv_fifo = vp->v_fifoinfo;
4258                                 break;
4259                         case VNON:
4260                         case VBAD:
4261                         default:
4262                                 /* shouldn't happen? */
4263                                 vrele(vp);
4264                                 continue;
4265                         }
4266                         vrele(vp);
4267                         ++n;
4268                 }
4269                 MNT_IUNLOCK(mp);
4270                 mtx_lock(&mountlist_mtx);
4271                 vfs_unbusy(mp);
4272                 if (n == len)
4273                         break;
4274         }
4275         mtx_unlock(&mountlist_mtx);
4276
4277         error = SYSCTL_OUT(req, xvn, n * sizeof *xvn);
4278         free(xvn, M_TEMP);
4279         return (error);
4280 }
4281
4282 SYSCTL_PROC(_kern, KERN_VNODE, vnode, CTLTYPE_OPAQUE | CTLFLAG_RD |
4283     CTLFLAG_MPSAFE, 0, 0, sysctl_vnode, "S,xvnode",
4284     "");
4285 #endif
4286
4287 static void
4288 unmount_or_warn(struct mount *mp)
4289 {
4290         int error;
4291
4292         error = dounmount(mp, MNT_FORCE, curthread);
4293         if (error != 0) {
4294                 printf("unmount of %s failed (", mp->mnt_stat.f_mntonname);
4295                 if (error == EBUSY)
4296                         printf("BUSY)\n");
4297                 else
4298                         printf("%d)\n", error);
4299         }
4300 }
4301
4302 /*
4303  * Unmount all filesystems. The list is traversed in reverse order
4304  * of mounting to avoid dependencies.
4305  */
4306 void
4307 vfs_unmountall(void)
4308 {
4309         struct mount *mp, *tmp;
4310
4311         CTR1(KTR_VFS, "%s: unmounting all filesystems", __func__);
4312
4313         /*
4314          * Since this only runs when rebooting, it is not interlocked.
4315          */
4316         TAILQ_FOREACH_REVERSE_SAFE(mp, &mountlist, mntlist, mnt_list, tmp) {
4317                 vfs_ref(mp);
4318
4319                 /*
4320                  * Forcibly unmounting "/dev" before "/" would prevent clean
4321                  * unmount of the latter.
4322                  */
4323                 if (mp == rootdevmp)
4324                         continue;
4325
4326                 unmount_or_warn(mp);
4327         }
4328
4329         if (rootdevmp != NULL)
4330                 unmount_or_warn(rootdevmp);
4331 }
4332
4333 /*
4334  * perform msync on all vnodes under a mount point
4335  * the mount point must be locked.
4336  */
4337 void
4338 vfs_msync(struct mount *mp, int flags)
4339 {
4340         struct vnode *vp, *mvp;
4341         struct vm_object *obj;
4342
4343         CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
4344
4345         if ((mp->mnt_kern_flag & MNTK_NOMSYNC) != 0)
4346                 return;
4347
4348         MNT_VNODE_FOREACH_ACTIVE(vp, mp, mvp) {
4349                 obj = vp->v_object;
4350                 if (obj != NULL && vm_object_mightbedirty(obj) &&
4351                     (flags == MNT_WAIT || VOP_ISLOCKED(vp) == 0)) {
4352                         if (!vget(vp,
4353                             LK_EXCLUSIVE | LK_RETRY | LK_INTERLOCK,
4354                             curthread)) {
4355                                 if (vp->v_vflag & VV_NOSYNC) {  /* unlinked */
4356                                         vput(vp);
4357                                         continue;
4358                                 }
4359
4360                                 obj = vp->v_object;
4361                                 if (obj != NULL) {
4362                                         VM_OBJECT_WLOCK(obj);
4363                                         vm_object_page_clean(obj, 0, 0,
4364                                             flags == MNT_WAIT ?
4365                                             OBJPC_SYNC : OBJPC_NOSYNC);
4366                                         VM_OBJECT_WUNLOCK(obj);
4367                                 }
4368                                 vput(vp);
4369                         }
4370                 } else
4371                         VI_UNLOCK(vp);
4372         }
4373 }
4374
4375 static void
4376 destroy_vpollinfo_free(struct vpollinfo *vi)
4377 {
4378
4379         knlist_destroy(&vi->vpi_selinfo.si_note);
4380         mtx_destroy(&vi->vpi_lock);
4381         uma_zfree(vnodepoll_zone, vi);
4382 }
4383
4384 static void
4385 destroy_vpollinfo(struct vpollinfo *vi)
4386 {
4387
4388         knlist_clear(&vi->vpi_selinfo.si_note, 1);
4389         seldrain(&vi->vpi_selinfo);
4390         destroy_vpollinfo_free(vi);
4391 }
4392
4393 /*
4394  * Initialize per-vnode helper structure to hold poll-related state.
4395  */
4396 void
4397 v_addpollinfo(struct vnode *vp)
4398 {
4399         struct vpollinfo *vi;
4400
4401         if (vp->v_pollinfo != NULL)
4402                 return;
4403         vi = uma_zalloc(vnodepoll_zone, M_WAITOK | M_ZERO);
4404         mtx_init(&vi->vpi_lock, "vnode pollinfo", NULL, MTX_DEF);
4405         knlist_init(&vi->vpi_selinfo.si_note, vp, vfs_knllock,
4406             vfs_knlunlock, vfs_knl_assert_locked, vfs_knl_assert_unlocked);
4407         VI_LOCK(vp);
4408         if (vp->v_pollinfo != NULL) {
4409                 VI_UNLOCK(vp);
4410                 destroy_vpollinfo_free(vi);
4411                 return;
4412         }
4413         vp->v_pollinfo = vi;
4414         VI_UNLOCK(vp);
4415 }
4416
4417 /*
4418  * Record a process's interest in events which might happen to
4419  * a vnode.  Because poll uses the historic select-style interface
4420  * internally, this routine serves as both the ``check for any
4421  * pending events'' and the ``record my interest in future events''
4422  * functions.  (These are done together, while the lock is held,
4423  * to avoid race conditions.)
4424  */
4425 int
4426 vn_pollrecord(struct vnode *vp, struct thread *td, int events)
4427 {
4428
4429         v_addpollinfo(vp);
4430         mtx_lock(&vp->v_pollinfo->vpi_lock);
4431         if (vp->v_pollinfo->vpi_revents & events) {
4432                 /*
4433                  * This leaves events we are not interested
4434                  * in available for the other process which
4435                  * which presumably had requested them
4436                  * (otherwise they would never have been
4437                  * recorded).
4438                  */
4439                 events &= vp->v_pollinfo->vpi_revents;
4440                 vp->v_pollinfo->vpi_revents &= ~events;
4441
4442                 mtx_unlock(&vp->v_pollinfo->vpi_lock);
4443                 return (events);
4444         }
4445         vp->v_pollinfo->vpi_events |= events;
4446         selrecord(td, &vp->v_pollinfo->vpi_selinfo);
4447         mtx_unlock(&vp->v_pollinfo->vpi_lock);
4448         return (0);
4449 }
4450
4451 /*
4452  * Routine to create and manage a filesystem syncer vnode.
4453  */
4454 #define sync_close ((int (*)(struct  vop_close_args *))nullop)
4455 static int      sync_fsync(struct  vop_fsync_args *);
4456 static int      sync_inactive(struct  vop_inactive_args *);
4457 static int      sync_reclaim(struct  vop_reclaim_args *);
4458
4459 static struct vop_vector sync_vnodeops = {
4460         .vop_bypass =   VOP_EOPNOTSUPP,
4461         .vop_close =    sync_close,             /* close */
4462         .vop_fsync =    sync_fsync,             /* fsync */
4463         .vop_inactive = sync_inactive,  /* inactive */
4464         .vop_need_inactive = vop_stdneed_inactive, /* need_inactive */
4465         .vop_reclaim =  sync_reclaim,   /* reclaim */
4466         .vop_lock1 =    vop_stdlock,    /* lock */
4467         .vop_unlock =   vop_stdunlock,  /* unlock */
4468         .vop_islocked = vop_stdislocked,        /* islocked */
4469 };
4470
4471 /*
4472  * Create a new filesystem syncer vnode for the specified mount point.
4473  */
4474 void
4475 vfs_allocate_syncvnode(struct mount *mp)
4476 {
4477         struct vnode *vp;
4478         struct bufobj *bo;
4479         static long start, incr, next;
4480         int error;
4481
4482         /* Allocate a new vnode */
4483         error = getnewvnode("syncer", mp, &sync_vnodeops, &vp);
4484         if (error != 0)
4485                 panic("vfs_allocate_syncvnode: getnewvnode() failed");
4486         vp->v_type = VNON;
4487         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
4488         vp->v_vflag |= VV_FORCEINSMQ;
4489         error = insmntque(vp, mp);
4490         if (error != 0)
4491                 panic("vfs_allocate_syncvnode: insmntque() failed");
4492         vp->v_vflag &= ~VV_FORCEINSMQ;
4493         VOP_UNLOCK(vp, 0);
4494         /*
4495          * Place the vnode onto the syncer worklist. We attempt to
4496          * scatter them about on the list so that they will go off
4497          * at evenly distributed times even if all the filesystems
4498          * are mounted at once.
4499          */
4500         next += incr;
4501         if (next == 0 || next > syncer_maxdelay) {
4502                 start /= 2;
4503                 incr /= 2;
4504                 if (start == 0) {
4505                         start = syncer_maxdelay / 2;
4506                         incr = syncer_maxdelay;
4507                 }
4508                 next = start;
4509         }
4510         bo = &vp->v_bufobj;
4511         BO_LOCK(bo);
4512         vn_syncer_add_to_worklist(bo, syncdelay > 0 ? next % syncdelay : 0);
4513         /* XXX - vn_syncer_add_to_worklist() also grabs and drops sync_mtx. */
4514         mtx_lock(&sync_mtx);
4515         sync_vnode_count++;
4516         if (mp->mnt_syncer == NULL) {
4517                 mp->mnt_syncer = vp;
4518                 vp = NULL;
4519         }
4520         mtx_unlock(&sync_mtx);
4521         BO_UNLOCK(bo);
4522         if (vp != NULL) {
4523                 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
4524                 vgone(vp);
4525                 vput(vp);
4526         }
4527 }
4528
4529 void
4530 vfs_deallocate_syncvnode(struct mount *mp)
4531 {
4532         struct vnode *vp;
4533
4534         mtx_lock(&sync_mtx);
4535         vp = mp->mnt_syncer;
4536         if (vp != NULL)
4537                 mp->mnt_syncer = NULL;
4538         mtx_unlock(&sync_mtx);
4539         if (vp != NULL)
4540                 vrele(vp);
4541 }
4542
4543 /*
4544  * Do a lazy sync of the filesystem.
4545  */
4546 static int
4547 sync_fsync(struct vop_fsync_args *ap)
4548 {
4549         struct vnode *syncvp = ap->a_vp;
4550         struct mount *mp = syncvp->v_mount;
4551         int error, save;
4552         struct bufobj *bo;
4553
4554         /*
4555          * We only need to do something if this is a lazy evaluation.
4556          */
4557         if (ap->a_waitfor != MNT_LAZY)
4558                 return (0);
4559
4560         /*
4561          * Move ourselves to the back of the sync list.
4562          */
4563         bo = &syncvp->v_bufobj;
4564         BO_LOCK(bo);
4565         vn_syncer_add_to_worklist(bo, syncdelay);
4566         BO_UNLOCK(bo);
4567
4568         /*
4569          * Walk the list of vnodes pushing all that are dirty and
4570          * not already on the sync list.
4571          */
4572         if (vfs_busy(mp, MBF_NOWAIT) != 0)
4573                 return (0);
4574         if (vn_start_write(NULL, &mp, V_NOWAIT) != 0) {
4575                 vfs_unbusy(mp);
4576                 return (0);
4577         }
4578         save = curthread_pflags_set(TDP_SYNCIO);
4579         /*
4580          * The filesystem at hand may be idle with free vnodes stored in the
4581          * batch.  Return them instead of letting them stay there indefinitely.
4582          */
4583         vnlru_return_batch(mp);
4584         vfs_msync(mp, MNT_NOWAIT);
4585         error = VFS_SYNC(mp, MNT_LAZY);
4586         curthread_pflags_restore(save);
4587         vn_finished_write(mp);
4588         vfs_unbusy(mp);
4589         return (error);
4590 }
4591
4592 /*
4593  * The syncer vnode is no referenced.
4594  */
4595 static int
4596 sync_inactive(struct vop_inactive_args *ap)
4597 {
4598
4599         vgone(ap->a_vp);
4600         return (0);
4601 }
4602
4603 /*
4604  * The syncer vnode is no longer needed and is being decommissioned.
4605  *
4606  * Modifications to the worklist must be protected by sync_mtx.
4607  */
4608 static int
4609 sync_reclaim(struct vop_reclaim_args *ap)
4610 {
4611         struct vnode *vp = ap->a_vp;
4612         struct bufobj *bo;
4613
4614         bo = &vp->v_bufobj;
4615         BO_LOCK(bo);
4616         mtx_lock(&sync_mtx);
4617         if (vp->v_mount->mnt_syncer == vp)
4618                 vp->v_mount->mnt_syncer = NULL;
4619         if (bo->bo_flag & BO_ONWORKLST) {
4620                 LIST_REMOVE(bo, bo_synclist);
4621                 syncer_worklist_len--;
4622                 sync_vnode_count--;
4623                 bo->bo_flag &= ~BO_ONWORKLST;
4624         }
4625         mtx_unlock(&sync_mtx);
4626         BO_UNLOCK(bo);
4627
4628         return (0);
4629 }
4630
4631 int
4632 vn_need_pageq_flush(struct vnode *vp)
4633 {
4634         struct vm_object *obj;
4635         int need;
4636
4637         MPASS(mtx_owned(VI_MTX(vp)));
4638         need = 0;
4639         if ((obj = vp->v_object) != NULL && (vp->v_vflag & VV_NOSYNC) == 0 &&
4640             vm_object_mightbedirty(obj))
4641                 need = 1;
4642         return (need);
4643 }
4644
4645 /*
4646  * Check if vnode represents a disk device
4647  */
4648 int
4649 vn_isdisk(struct vnode *vp, int *errp)
4650 {
4651         int error;
4652
4653         if (vp->v_type != VCHR) {
4654                 error = ENOTBLK;
4655                 goto out;
4656         }
4657         error = 0;
4658         dev_lock();
4659         if (vp->v_rdev == NULL)
4660                 error = ENXIO;
4661         else if (vp->v_rdev->si_devsw == NULL)
4662                 error = ENXIO;
4663         else if (!(vp->v_rdev->si_devsw->d_flags & D_DISK))
4664                 error = ENOTBLK;
4665         dev_unlock();
4666 out:
4667         if (errp != NULL)
4668                 *errp = error;
4669         return (error == 0);
4670 }
4671
4672 /*
4673  * Common filesystem object access control check routine.  Accepts a
4674  * vnode's type, "mode", uid and gid, requested access mode, credentials,
4675  * and optional call-by-reference privused argument allowing vaccess()
4676  * to indicate to the caller whether privilege was used to satisfy the
4677  * request (obsoleted).  Returns 0 on success, or an errno on failure.
4678  */
4679 int
4680 vaccess(enum vtype type, mode_t file_mode, uid_t file_uid, gid_t file_gid,
4681     accmode_t accmode, struct ucred *cred, int *privused)
4682 {
4683         accmode_t dac_granted;
4684         accmode_t priv_granted;
4685
4686         KASSERT((accmode & ~(VEXEC | VWRITE | VREAD | VADMIN | VAPPEND)) == 0,
4687             ("invalid bit in accmode"));
4688         KASSERT((accmode & VAPPEND) == 0 || (accmode & VWRITE),
4689             ("VAPPEND without VWRITE"));
4690
4691         /*
4692          * Look for a normal, non-privileged way to access the file/directory
4693          * as requested.  If it exists, go with that.
4694          */
4695
4696         if (privused != NULL)
4697                 *privused = 0;
4698
4699         dac_granted = 0;
4700
4701         /* Check the owner. */
4702         if (cred->cr_uid == file_uid) {
4703                 dac_granted |= VADMIN;
4704                 if (file_mode & S_IXUSR)
4705                         dac_granted |= VEXEC;
4706                 if (file_mode & S_IRUSR)
4707                         dac_granted |= VREAD;
4708                 if (file_mode & S_IWUSR)
4709                         dac_granted |= (VWRITE | VAPPEND);
4710
4711                 if ((accmode & dac_granted) == accmode)
4712                         return (0);
4713
4714                 goto privcheck;
4715         }
4716
4717         /* Otherwise, check the groups (first match) */
4718         if (groupmember(file_gid, cred)) {
4719                 if (file_mode & S_IXGRP)
4720                         dac_granted |= VEXEC;
4721                 if (file_mode & S_IRGRP)
4722                         dac_granted |= VREAD;
4723                 if (file_mode & S_IWGRP)
4724                         dac_granted |= (VWRITE | VAPPEND);
4725
4726                 if ((accmode & dac_granted) == accmode)
4727                         return (0);
4728
4729                 goto privcheck;
4730         }
4731
4732         /* Otherwise, check everyone else. */
4733         if (file_mode & S_IXOTH)
4734                 dac_granted |= VEXEC;
4735         if (file_mode & S_IROTH)
4736                 dac_granted |= VREAD;
4737         if (file_mode & S_IWOTH)
4738                 dac_granted |= (VWRITE | VAPPEND);
4739         if ((accmode & dac_granted) == accmode)
4740                 return (0);
4741
4742 privcheck:
4743         /*
4744          * Build a privilege mask to determine if the set of privileges
4745          * satisfies the requirements when combined with the granted mask
4746          * from above.  For each privilege, if the privilege is required,
4747          * bitwise or the request type onto the priv_granted mask.
4748          */
4749         priv_granted = 0;
4750
4751         if (type == VDIR) {
4752                 /*
4753                  * For directories, use PRIV_VFS_LOOKUP to satisfy VEXEC
4754                  * requests, instead of PRIV_VFS_EXEC.
4755                  */
4756                 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
4757                     !priv_check_cred(cred, PRIV_VFS_LOOKUP))
4758                         priv_granted |= VEXEC;
4759         } else {
4760                 /*
4761                  * Ensure that at least one execute bit is on. Otherwise,
4762                  * a privileged user will always succeed, and we don't want
4763                  * this to happen unless the file really is executable.
4764                  */
4765                 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
4766                     (file_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0 &&
4767                     !priv_check_cred(cred, PRIV_VFS_EXEC))
4768                         priv_granted |= VEXEC;
4769         }
4770
4771         if ((accmode & VREAD) && ((dac_granted & VREAD) == 0) &&
4772             !priv_check_cred(cred, PRIV_VFS_READ))
4773                 priv_granted |= VREAD;
4774
4775         if ((accmode & VWRITE) && ((dac_granted & VWRITE) == 0) &&
4776             !priv_check_cred(cred, PRIV_VFS_WRITE))
4777                 priv_granted |= (VWRITE | VAPPEND);
4778
4779         if ((accmode & VADMIN) && ((dac_granted & VADMIN) == 0) &&
4780             !priv_check_cred(cred, PRIV_VFS_ADMIN))
4781                 priv_granted |= VADMIN;
4782
4783         if ((accmode & (priv_granted | dac_granted)) == accmode) {
4784                 /* XXX audit: privilege used */
4785                 if (privused != NULL)
4786                         *privused = 1;
4787                 return (0);
4788         }
4789
4790         return ((accmode & VADMIN) ? EPERM : EACCES);
4791 }
4792
4793 /*
4794  * Credential check based on process requesting service, and per-attribute
4795  * permissions.
4796  */
4797 int
4798 extattr_check_cred(struct vnode *vp, int attrnamespace, struct ucred *cred,
4799     struct thread *td, accmode_t accmode)
4800 {
4801
4802         /*
4803          * Kernel-invoked always succeeds.
4804          */
4805         if (cred == NOCRED)
4806                 return (0);
4807
4808         /*
4809          * Do not allow privileged processes in jail to directly manipulate
4810          * system attributes.
4811          */
4812         switch (attrnamespace) {
4813         case EXTATTR_NAMESPACE_SYSTEM:
4814                 /* Potentially should be: return (EPERM); */
4815                 return (priv_check_cred(cred, PRIV_VFS_EXTATTR_SYSTEM));
4816         case EXTATTR_NAMESPACE_USER:
4817                 return (VOP_ACCESS(vp, accmode, cred, td));
4818         default:
4819                 return (EPERM);
4820         }
4821 }
4822
4823 #ifdef DEBUG_VFS_LOCKS
4824 /*
4825  * This only exists to suppress warnings from unlocked specfs accesses.  It is
4826  * no longer ok to have an unlocked VFS.
4827  */
4828 #define IGNORE_LOCK(vp) (panicstr != NULL || (vp) == NULL ||            \
4829         (vp)->v_type == VCHR || (vp)->v_type == VBAD)
4830
4831 int vfs_badlock_ddb = 1;        /* Drop into debugger on violation. */
4832 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_ddb, CTLFLAG_RW, &vfs_badlock_ddb, 0,
4833     "Drop into debugger on lock violation");
4834
4835 int vfs_badlock_mutex = 1;      /* Check for interlock across VOPs. */
4836 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_mutex, CTLFLAG_RW, &vfs_badlock_mutex,
4837     0, "Check for interlock across VOPs");
4838
4839 int vfs_badlock_print = 1;      /* Print lock violations. */
4840 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_print, CTLFLAG_RW, &vfs_badlock_print,
4841     0, "Print lock violations");
4842
4843 int vfs_badlock_vnode = 1;      /* Print vnode details on lock violations. */
4844 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_vnode, CTLFLAG_RW, &vfs_badlock_vnode,
4845     0, "Print vnode details on lock violations");
4846
4847 #ifdef KDB
4848 int vfs_badlock_backtrace = 1;  /* Print backtrace at lock violations. */
4849 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_backtrace, CTLFLAG_RW,
4850     &vfs_badlock_backtrace, 0, "Print backtrace at lock violations");
4851 #endif
4852
4853 static void
4854 vfs_badlock(const char *msg, const char *str, struct vnode *vp)
4855 {
4856
4857 #ifdef KDB
4858         if (vfs_badlock_backtrace)
4859                 kdb_backtrace();
4860 #endif
4861         if (vfs_badlock_vnode)
4862                 vn_printf(vp, "vnode ");
4863         if (vfs_badlock_print)
4864                 printf("%s: %p %s\n", str, (void *)vp, msg);
4865         if (vfs_badlock_ddb)
4866                 kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
4867 }
4868
4869 void
4870 assert_vi_locked(struct vnode *vp, const char *str)
4871 {
4872
4873         if (vfs_badlock_mutex && !mtx_owned(VI_MTX(vp)))
4874                 vfs_badlock("interlock is not locked but should be", str, vp);
4875 }
4876
4877 void
4878 assert_vi_unlocked(struct vnode *vp, const char *str)
4879 {
4880
4881         if (vfs_badlock_mutex && mtx_owned(VI_MTX(vp)))
4882                 vfs_badlock("interlock is locked but should not be", str, vp);
4883 }
4884
4885 void
4886 assert_vop_locked(struct vnode *vp, const char *str)
4887 {
4888         int locked;
4889
4890         if (!IGNORE_LOCK(vp)) {
4891                 locked = VOP_ISLOCKED(vp);
4892                 if (locked == 0 || locked == LK_EXCLOTHER)
4893                         vfs_badlock("is not locked but should be", str, vp);
4894         }
4895 }
4896
4897 void
4898 assert_vop_unlocked(struct vnode *vp, const char *str)
4899 {
4900
4901         if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) == LK_EXCLUSIVE)
4902                 vfs_badlock("is locked but should not be", str, vp);
4903 }
4904
4905 void
4906 assert_vop_elocked(struct vnode *vp, const char *str)
4907 {
4908
4909         if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) != LK_EXCLUSIVE)
4910                 vfs_badlock("is not exclusive locked but should be", str, vp);
4911 }
4912 #endif /* DEBUG_VFS_LOCKS */
4913
4914 void
4915 vop_rename_fail(struct vop_rename_args *ap)
4916 {
4917
4918         if (ap->a_tvp != NULL)
4919                 vput(ap->a_tvp);
4920         if (ap->a_tdvp == ap->a_tvp)
4921                 vrele(ap->a_tdvp);
4922         else
4923                 vput(ap->a_tdvp);
4924         vrele(ap->a_fdvp);
4925         vrele(ap->a_fvp);
4926 }
4927
4928 void
4929 vop_rename_pre(void *ap)
4930 {
4931         struct vop_rename_args *a = ap;
4932
4933 #ifdef DEBUG_VFS_LOCKS
4934         if (a->a_tvp)
4935                 ASSERT_VI_UNLOCKED(a->a_tvp, "VOP_RENAME");
4936         ASSERT_VI_UNLOCKED(a->a_tdvp, "VOP_RENAME");
4937         ASSERT_VI_UNLOCKED(a->a_fvp, "VOP_RENAME");
4938         ASSERT_VI_UNLOCKED(a->a_fdvp, "VOP_RENAME");
4939
4940         /* Check the source (from). */
4941         if (a->a_tdvp->v_vnlock != a->a_fdvp->v_vnlock &&
4942             (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fdvp->v_vnlock))
4943                 ASSERT_VOP_UNLOCKED(a->a_fdvp, "vop_rename: fdvp locked");
4944         if (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fvp->v_vnlock)
4945                 ASSERT_VOP_UNLOCKED(a->a_fvp, "vop_rename: fvp locked");
4946
4947         /* Check the target. */
4948         if (a->a_tvp)
4949                 ASSERT_VOP_LOCKED(a->a_tvp, "vop_rename: tvp not locked");
4950         ASSERT_VOP_LOCKED(a->a_tdvp, "vop_rename: tdvp not locked");
4951 #endif
4952         if (a->a_tdvp != a->a_fdvp)
4953                 vhold(a->a_fdvp);
4954         if (a->a_tvp != a->a_fvp)
4955                 vhold(a->a_fvp);
4956         vhold(a->a_tdvp);
4957         if (a->a_tvp)
4958                 vhold(a->a_tvp);
4959 }
4960
4961 #ifdef DEBUG_VFS_LOCKS
4962 void
4963 vop_strategy_pre(void *ap)
4964 {
4965         struct vop_strategy_args *a;
4966         struct buf *bp;
4967
4968         a = ap;
4969         bp = a->a_bp;
4970
4971         /*
4972          * Cluster ops lock their component buffers but not the IO container.
4973          */
4974         if ((bp->b_flags & B_CLUSTER) != 0)
4975                 return;
4976
4977         if (panicstr == NULL && !BUF_ISLOCKED(bp)) {
4978                 if (vfs_badlock_print)
4979                         printf(
4980                             "VOP_STRATEGY: bp is not locked but should be\n");
4981                 if (vfs_badlock_ddb)
4982                         kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
4983         }
4984 }
4985
4986 void
4987 vop_lock_pre(void *ap)
4988 {
4989         struct vop_lock1_args *a = ap;
4990
4991         if ((a->a_flags & LK_INTERLOCK) == 0)
4992                 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
4993         else
4994                 ASSERT_VI_LOCKED(a->a_vp, "VOP_LOCK");
4995 }
4996
4997 void
4998 vop_lock_post(void *ap, int rc)
4999 {
5000         struct vop_lock1_args *a = ap;
5001
5002         ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
5003         if (rc == 0 && (a->a_flags & LK_EXCLOTHER) == 0)
5004                 ASSERT_VOP_LOCKED(a->a_vp, "VOP_LOCK");
5005 }
5006
5007 void
5008 vop_unlock_pre(void *ap)
5009 {
5010         struct vop_unlock_args *a = ap;
5011
5012         if (a->a_flags & LK_INTERLOCK)
5013                 ASSERT_VI_LOCKED(a->a_vp, "VOP_UNLOCK");
5014         ASSERT_VOP_LOCKED(a->a_vp, "VOP_UNLOCK");
5015 }
5016
5017 void
5018 vop_unlock_post(void *ap, int rc)
5019 {
5020         struct vop_unlock_args *a = ap;
5021
5022         if (a->a_flags & LK_INTERLOCK)
5023                 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_UNLOCK");
5024 }
5025
5026 void
5027 vop_need_inactive_pre(void *ap)
5028 {
5029         struct vop_need_inactive_args *a = ap;
5030
5031         ASSERT_VI_LOCKED(a->a_vp, "VOP_NEED_INACTIVE");
5032 }
5033
5034 void
5035 vop_need_inactive_post(void *ap, int rc)
5036 {
5037         struct vop_need_inactive_args *a = ap;
5038
5039         ASSERT_VI_LOCKED(a->a_vp, "VOP_NEED_INACTIVE");
5040 }
5041 #endif
5042
5043 void
5044 vop_create_post(void *ap, int rc)
5045 {
5046         struct vop_create_args *a = ap;
5047
5048         if (!rc)
5049                 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
5050 }
5051
5052 void
5053 vop_deleteextattr_post(void *ap, int rc)
5054 {
5055         struct vop_deleteextattr_args *a = ap;
5056
5057         if (!rc)
5058                 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
5059 }
5060
5061 void
5062 vop_link_post(void *ap, int rc)
5063 {
5064         struct vop_link_args *a = ap;
5065
5066         if (!rc) {
5067                 VFS_KNOTE_LOCKED(a->a_vp, NOTE_LINK);
5068                 VFS_KNOTE_LOCKED(a->a_tdvp, NOTE_WRITE);
5069         }
5070 }
5071
5072 void
5073 vop_mkdir_post(void *ap, int rc)
5074 {
5075         struct vop_mkdir_args *a = ap;
5076
5077         if (!rc)
5078                 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE | NOTE_LINK);
5079 }
5080
5081 void
5082 vop_mknod_post(void *ap, int rc)
5083 {
5084         struct vop_mknod_args *a = ap;
5085
5086         if (!rc)
5087                 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
5088 }
5089
5090 void
5091 vop_reclaim_post(void *ap, int rc)
5092 {
5093         struct vop_reclaim_args *a = ap;
5094
5095         if (!rc)
5096                 VFS_KNOTE_LOCKED(a->a_vp, NOTE_REVOKE);
5097 }
5098
5099 void
5100 vop_remove_post(void *ap, int rc)
5101 {
5102         struct vop_remove_args *a = ap;
5103
5104         if (!rc) {
5105                 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
5106                 VFS_KNOTE_LOCKED(a->a_vp, NOTE_DELETE);
5107         }
5108 }
5109
5110 void
5111 vop_rename_post(void *ap, int rc)
5112 {
5113         struct vop_rename_args *a = ap;
5114         long hint;
5115
5116         if (!rc) {
5117                 hint = NOTE_WRITE;
5118                 if (a->a_fdvp == a->a_tdvp) {
5119                         if (a->a_tvp != NULL && a->a_tvp->v_type == VDIR)
5120                                 hint |= NOTE_LINK;
5121                         VFS_KNOTE_UNLOCKED(a->a_fdvp, hint);
5122                         VFS_KNOTE_UNLOCKED(a->a_tdvp, hint);
5123                 } else {
5124                         hint |= NOTE_EXTEND;
5125                         if (a->a_fvp->v_type == VDIR)
5126                                 hint |= NOTE_LINK;
5127                         VFS_KNOTE_UNLOCKED(a->a_fdvp, hint);
5128
5129                         if (a->a_fvp->v_type == VDIR && a->a_tvp != NULL &&
5130                             a->a_tvp->v_type == VDIR)
5131                                 hint &= ~NOTE_LINK;
5132                         VFS_KNOTE_UNLOCKED(a->a_tdvp, hint);
5133                 }
5134
5135                 VFS_KNOTE_UNLOCKED(a->a_fvp, NOTE_RENAME);
5136                 if (a->a_tvp)
5137                         VFS_KNOTE_UNLOCKED(a->a_tvp, NOTE_DELETE);
5138         }
5139         if (a->a_tdvp != a->a_fdvp)
5140                 vdrop(a->a_fdvp);
5141         if (a->a_tvp != a->a_fvp)
5142                 vdrop(a->a_fvp);
5143         vdrop(a->a_tdvp);
5144         if (a->a_tvp)
5145                 vdrop(a->a_tvp);
5146 }
5147
5148 void
5149 vop_rmdir_post(void *ap, int rc)
5150 {
5151         struct vop_rmdir_args *a = ap;
5152
5153         if (!rc) {
5154                 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE | NOTE_LINK);
5155                 VFS_KNOTE_LOCKED(a->a_vp, NOTE_DELETE);
5156         }
5157 }
5158
5159 void
5160 vop_setattr_post(void *ap, int rc)
5161 {
5162         struct vop_setattr_args *a = ap;
5163
5164         if (!rc)
5165                 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
5166 }
5167
5168 void
5169 vop_setextattr_post(void *ap, int rc)
5170 {
5171         struct vop_setextattr_args *a = ap;
5172
5173         if (!rc)
5174                 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
5175 }
5176
5177 void
5178 vop_symlink_post(void *ap, int rc)
5179 {
5180         struct vop_symlink_args *a = ap;
5181
5182         if (!rc)
5183                 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
5184 }
5185
5186 void
5187 vop_open_post(void *ap, int rc)
5188 {
5189         struct vop_open_args *a = ap;
5190
5191         if (!rc)
5192                 VFS_KNOTE_LOCKED(a->a_vp, NOTE_OPEN);
5193 }
5194
5195 void
5196 vop_close_post(void *ap, int rc)
5197 {
5198         struct vop_close_args *a = ap;
5199
5200         if (!rc && (a->a_cred != NOCRED || /* filter out revokes */
5201             (a->a_vp->v_iflag & VI_DOOMED) == 0)) {
5202                 VFS_KNOTE_LOCKED(a->a_vp, (a->a_fflag & FWRITE) != 0 ?
5203                     NOTE_CLOSE_WRITE : NOTE_CLOSE);
5204         }
5205 }
5206
5207 void
5208 vop_read_post(void *ap, int rc)
5209 {
5210         struct vop_read_args *a = ap;
5211
5212         if (!rc)
5213                 VFS_KNOTE_LOCKED(a->a_vp, NOTE_READ);
5214 }
5215
5216 void
5217 vop_readdir_post(void *ap, int rc)
5218 {
5219         struct vop_readdir_args *a = ap;
5220
5221         if (!rc)
5222                 VFS_KNOTE_LOCKED(a->a_vp, NOTE_READ);
5223 }
5224
5225 static struct knlist fs_knlist;
5226
5227 static void
5228 vfs_event_init(void *arg)
5229 {
5230         knlist_init_mtx(&fs_knlist, NULL);
5231 }
5232 /* XXX - correct order? */
5233 SYSINIT(vfs_knlist, SI_SUB_VFS, SI_ORDER_ANY, vfs_event_init, NULL);
5234
5235 void
5236 vfs_event_signal(fsid_t *fsid, uint32_t event, intptr_t data __unused)
5237 {
5238
5239         KNOTE_UNLOCKED(&fs_knlist, event);
5240 }
5241
5242 static int      filt_fsattach(struct knote *kn);
5243 static void     filt_fsdetach(struct knote *kn);
5244 static int      filt_fsevent(struct knote *kn, long hint);
5245
5246 struct filterops fs_filtops = {
5247         .f_isfd = 0,
5248         .f_attach = filt_fsattach,
5249         .f_detach = filt_fsdetach,
5250         .f_event = filt_fsevent
5251 };
5252
5253 static int
5254 filt_fsattach(struct knote *kn)
5255 {
5256
5257         kn->kn_flags |= EV_CLEAR;
5258         knlist_add(&fs_knlist, kn, 0);
5259         return (0);
5260 }
5261
5262 static void
5263 filt_fsdetach(struct knote *kn)
5264 {
5265
5266         knlist_remove(&fs_knlist, kn, 0);
5267 }
5268
5269 static int
5270 filt_fsevent(struct knote *kn, long hint)
5271 {
5272
5273         kn->kn_fflags |= hint;
5274         return (kn->kn_fflags != 0);
5275 }
5276
5277 static int
5278 sysctl_vfs_ctl(SYSCTL_HANDLER_ARGS)
5279 {
5280         struct vfsidctl vc;
5281         int error;
5282         struct mount *mp;
5283
5284         error = SYSCTL_IN(req, &vc, sizeof(vc));
5285         if (error)
5286                 return (error);
5287         if (vc.vc_vers != VFS_CTL_VERS1)
5288                 return (EINVAL);
5289         mp = vfs_getvfs(&vc.vc_fsid);
5290         if (mp == NULL)
5291                 return (ENOENT);
5292         /* ensure that a specific sysctl goes to the right filesystem. */
5293         if (strcmp(vc.vc_fstypename, "*") != 0 &&
5294             strcmp(vc.vc_fstypename, mp->mnt_vfc->vfc_name) != 0) {
5295                 vfs_rel(mp);
5296                 return (EINVAL);
5297         }
5298         VCTLTOREQ(&vc, req);
5299         error = VFS_SYSCTL(mp, vc.vc_op, req);
5300         vfs_rel(mp);
5301         return (error);
5302 }
5303
5304 SYSCTL_PROC(_vfs, OID_AUTO, ctl, CTLTYPE_OPAQUE | CTLFLAG_WR,
5305     NULL, 0, sysctl_vfs_ctl, "",
5306     "Sysctl by fsid");
5307
5308 /*
5309  * Function to initialize a va_filerev field sensibly.
5310  * XXX: Wouldn't a random number make a lot more sense ??
5311  */
5312 u_quad_t
5313 init_va_filerev(void)
5314 {
5315         struct bintime bt;
5316
5317         getbinuptime(&bt);
5318         return (((u_quad_t)bt.sec << 32LL) | (bt.frac >> 32LL));
5319 }
5320
5321 static int      filt_vfsread(struct knote *kn, long hint);
5322 static int      filt_vfswrite(struct knote *kn, long hint);
5323 static int      filt_vfsvnode(struct knote *kn, long hint);
5324 static void     filt_vfsdetach(struct knote *kn);
5325 static struct filterops vfsread_filtops = {
5326         .f_isfd = 1,
5327         .f_detach = filt_vfsdetach,
5328         .f_event = filt_vfsread
5329 };
5330 static struct filterops vfswrite_filtops = {
5331         .f_isfd = 1,
5332         .f_detach = filt_vfsdetach,
5333         .f_event = filt_vfswrite
5334 };
5335 static struct filterops vfsvnode_filtops = {
5336         .f_isfd = 1,
5337         .f_detach = filt_vfsdetach,
5338         .f_event = filt_vfsvnode
5339 };
5340
5341 static void
5342 vfs_knllock(void *arg)
5343 {
5344         struct vnode *vp = arg;
5345
5346         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
5347 }
5348
5349 static void
5350 vfs_knlunlock(void *arg)
5351 {
5352         struct vnode *vp = arg;
5353
5354         VOP_UNLOCK(vp, 0);
5355 }
5356
5357 static void
5358 vfs_knl_assert_locked(void *arg)
5359 {
5360 #ifdef DEBUG_VFS_LOCKS
5361         struct vnode *vp = arg;
5362
5363         ASSERT_VOP_LOCKED(vp, "vfs_knl_assert_locked");
5364 #endif
5365 }
5366
5367 static void
5368 vfs_knl_assert_unlocked(void *arg)
5369 {
5370 #ifdef DEBUG_VFS_LOCKS
5371         struct vnode *vp = arg;
5372
5373         ASSERT_VOP_UNLOCKED(vp, "vfs_knl_assert_unlocked");
5374 #endif
5375 }
5376
5377 int
5378 vfs_kqfilter(struct vop_kqfilter_args *ap)
5379 {
5380         struct vnode *vp = ap->a_vp;
5381         struct knote *kn = ap->a_kn;
5382         struct knlist *knl;
5383
5384         switch (kn->kn_filter) {
5385         case EVFILT_READ:
5386                 kn->kn_fop = &vfsread_filtops;
5387                 break;
5388         case EVFILT_WRITE:
5389                 kn->kn_fop = &vfswrite_filtops;
5390                 break;
5391         case EVFILT_VNODE:
5392                 kn->kn_fop = &vfsvnode_filtops;
5393                 break;
5394         default:
5395                 return (EINVAL);
5396         }
5397
5398         kn->kn_hook = (caddr_t)vp;
5399
5400         v_addpollinfo(vp);
5401         if (vp->v_pollinfo == NULL)
5402                 return (ENOMEM);
5403         knl = &vp->v_pollinfo->vpi_selinfo.si_note;
5404         vhold(vp);
5405         knlist_add(knl, kn, 0);
5406
5407         return (0);
5408 }
5409
5410 /*
5411  * Detach knote from vnode
5412  */
5413 static void
5414 filt_vfsdetach(struct knote *kn)
5415 {
5416         struct vnode *vp = (struct vnode *)kn->kn_hook;
5417
5418         KASSERT(vp->v_pollinfo != NULL, ("Missing v_pollinfo"));
5419         knlist_remove(&vp->v_pollinfo->vpi_selinfo.si_note, kn, 0);
5420         vdrop(vp);
5421 }
5422
5423 /*ARGSUSED*/
5424 static int
5425 filt_vfsread(struct knote *kn, long hint)
5426 {
5427         struct vnode *vp = (struct vnode *)kn->kn_hook;
5428         struct vattr va;
5429         int res;
5430
5431         /*
5432          * filesystem is gone, so set the EOF flag and schedule
5433          * the knote for deletion.
5434          */
5435         if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD)) {
5436                 VI_LOCK(vp);
5437                 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
5438                 VI_UNLOCK(vp);
5439                 return (1);
5440         }
5441
5442         if (VOP_GETATTR(vp, &va, curthread->td_ucred))
5443                 return (0);
5444
5445         VI_LOCK(vp);
5446         kn->kn_data = va.va_size - kn->kn_fp->f_offset;
5447         res = (kn->kn_sfflags & NOTE_FILE_POLL) != 0 || kn->kn_data != 0;
5448         VI_UNLOCK(vp);
5449         return (res);
5450 }
5451
5452 /*ARGSUSED*/
5453 static int
5454 filt_vfswrite(struct knote *kn, long hint)
5455 {
5456         struct vnode *vp = (struct vnode *)kn->kn_hook;
5457
5458         VI_LOCK(vp);
5459
5460         /*
5461          * filesystem is gone, so set the EOF flag and schedule
5462          * the knote for deletion.
5463          */
5464         if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD))
5465                 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
5466
5467         kn->kn_data = 0;
5468         VI_UNLOCK(vp);
5469         return (1);
5470 }
5471
5472 static int
5473 filt_vfsvnode(struct knote *kn, long hint)
5474 {
5475         struct vnode *vp = (struct vnode *)kn->kn_hook;
5476         int res;
5477
5478         VI_LOCK(vp);
5479         if (kn->kn_sfflags & hint)
5480                 kn->kn_fflags |= hint;
5481         if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD)) {
5482                 kn->kn_flags |= EV_EOF;
5483                 VI_UNLOCK(vp);
5484                 return (1);
5485         }
5486         res = (kn->kn_fflags != 0);
5487         VI_UNLOCK(vp);
5488         return (res);
5489 }
5490
5491 /*
5492  * Returns whether the directory is empty or not.
5493  * If it is empty, the return value is 0; otherwise
5494  * the return value is an error value (which may
5495  * be ENOTEMPTY).
5496  */
5497 int
5498 vfs_emptydir(struct vnode *vp)
5499 {
5500         struct uio uio;
5501         struct iovec iov;
5502         struct dirent *dirent, *dp, *endp;
5503         int error, eof;
5504
5505         error = 0;
5506         eof = 0;
5507
5508         ASSERT_VOP_LOCKED(vp, "vfs_emptydir");
5509
5510         dirent = malloc(sizeof(struct dirent), M_TEMP, M_WAITOK);
5511         iov.iov_base = dirent;
5512         iov.iov_len = sizeof(struct dirent);
5513
5514         uio.uio_iov = &iov;
5515         uio.uio_iovcnt = 1;
5516         uio.uio_offset = 0;
5517         uio.uio_resid = sizeof(struct dirent);
5518         uio.uio_segflg = UIO_SYSSPACE;
5519         uio.uio_rw = UIO_READ;
5520         uio.uio_td = curthread;
5521
5522         while (eof == 0 && error == 0) {
5523                 error = VOP_READDIR(vp, &uio, curthread->td_ucred, &eof,
5524                     NULL, NULL);
5525                 if (error != 0)
5526                         break;
5527                 endp = (void *)((uint8_t *)dirent +
5528                     sizeof(struct dirent) - uio.uio_resid);
5529                 for (dp = dirent; dp < endp;
5530                      dp = (void *)((uint8_t *)dp + GENERIC_DIRSIZ(dp))) {
5531                         if (dp->d_type == DT_WHT)
5532                                 continue;
5533                         if (dp->d_namlen == 0)
5534                                 continue;
5535                         if (dp->d_type != DT_DIR &&
5536                             dp->d_type != DT_UNKNOWN) {
5537                                 error = ENOTEMPTY;
5538                                 break;
5539                         }
5540                         if (dp->d_namlen > 2) {
5541                                 error = ENOTEMPTY;
5542                                 break;
5543                         }
5544                         if (dp->d_namlen == 1 &&
5545                             dp->d_name[0] != '.') {
5546                                 error = ENOTEMPTY;
5547                                 break;
5548                         }
5549                         if (dp->d_namlen == 2 &&
5550                             dp->d_name[1] != '.') {
5551                                 error = ENOTEMPTY;
5552                                 break;
5553                         }
5554                         uio.uio_resid = sizeof(struct dirent);
5555                 }
5556         }
5557         free(dirent, M_TEMP);
5558         return (error);
5559 }
5560
5561 int
5562 vfs_read_dirent(struct vop_readdir_args *ap, struct dirent *dp, off_t off)
5563 {
5564         int error;
5565
5566         if (dp->d_reclen > ap->a_uio->uio_resid)
5567                 return (ENAMETOOLONG);
5568         error = uiomove(dp, dp->d_reclen, ap->a_uio);
5569         if (error) {
5570                 if (ap->a_ncookies != NULL) {
5571                         if (ap->a_cookies != NULL)
5572                                 free(ap->a_cookies, M_TEMP);
5573                         ap->a_cookies = NULL;
5574                         *ap->a_ncookies = 0;
5575                 }
5576                 return (error);
5577         }
5578         if (ap->a_ncookies == NULL)
5579                 return (0);
5580
5581         KASSERT(ap->a_cookies,
5582             ("NULL ap->a_cookies value with non-NULL ap->a_ncookies!"));
5583
5584         *ap->a_cookies = realloc(*ap->a_cookies,
5585             (*ap->a_ncookies + 1) * sizeof(u_long), M_TEMP, M_WAITOK | M_ZERO);
5586         (*ap->a_cookies)[*ap->a_ncookies] = off;
5587         *ap->a_ncookies += 1;
5588         return (0);
5589 }
5590
5591 /*
5592  * Mark for update the access time of the file if the filesystem
5593  * supports VOP_MARKATIME.  This functionality is used by execve and
5594  * mmap, so we want to avoid the I/O implied by directly setting
5595  * va_atime for the sake of efficiency.
5596  */
5597 void
5598 vfs_mark_atime(struct vnode *vp, struct ucred *cred)
5599 {
5600         struct mount *mp;
5601
5602         mp = vp->v_mount;
5603         ASSERT_VOP_LOCKED(vp, "vfs_mark_atime");
5604         if (mp != NULL && (mp->mnt_flag & (MNT_NOATIME | MNT_RDONLY)) == 0)
5605                 (void)VOP_MARKATIME(vp);
5606 }
5607
5608 /*
5609  * The purpose of this routine is to remove granularity from accmode_t,
5610  * reducing it into standard unix access bits - VEXEC, VREAD, VWRITE,
5611  * VADMIN and VAPPEND.
5612  *
5613  * If it returns 0, the caller is supposed to continue with the usual
5614  * access checks using 'accmode' as modified by this routine.  If it
5615  * returns nonzero value, the caller is supposed to return that value
5616  * as errno.
5617  *
5618  * Note that after this routine runs, accmode may be zero.
5619  */
5620 int
5621 vfs_unixify_accmode(accmode_t *accmode)
5622 {
5623         /*
5624          * There is no way to specify explicit "deny" rule using
5625          * file mode or POSIX.1e ACLs.
5626          */
5627         if (*accmode & VEXPLICIT_DENY) {
5628                 *accmode = 0;
5629                 return (0);
5630         }
5631
5632         /*
5633          * None of these can be translated into usual access bits.
5634          * Also, the common case for NFSv4 ACLs is to not contain
5635          * either of these bits. Caller should check for VWRITE
5636          * on the containing directory instead.
5637          */
5638         if (*accmode & (VDELETE_CHILD | VDELETE))
5639                 return (EPERM);
5640
5641         if (*accmode & VADMIN_PERMS) {
5642                 *accmode &= ~VADMIN_PERMS;
5643                 *accmode |= VADMIN;
5644         }
5645
5646         /*
5647          * There is no way to deny VREAD_ATTRIBUTES, VREAD_ACL
5648          * or VSYNCHRONIZE using file mode or POSIX.1e ACL.
5649          */
5650         *accmode &= ~(VSTAT_PERMS | VSYNCHRONIZE);
5651
5652         return (0);
5653 }
5654
5655 /*
5656  * Clear out a doomed vnode (if any) and replace it with a new one as long
5657  * as the fs is not being unmounted. Return the root vnode to the caller.
5658  */
5659 static int __noinline
5660 vfs_cache_root_fallback(struct mount *mp, int flags, struct vnode **vpp)
5661 {
5662         struct vnode *vp;
5663         int error;
5664
5665 restart:
5666         if (mp->mnt_rootvnode != NULL) {
5667                 MNT_ILOCK(mp);
5668                 vp = mp->mnt_rootvnode;
5669                 if (vp != NULL) {
5670                         if ((vp->v_iflag & VI_DOOMED) == 0) {
5671                                 vrefact(vp);
5672                                 MNT_IUNLOCK(mp);
5673                                 error = vn_lock(vp, flags);
5674                                 if (error == 0) {
5675                                         *vpp = vp;
5676                                         return (0);
5677                                 }
5678                                 vrele(vp);
5679                                 goto restart;
5680                         }
5681                         /*
5682                          * Clear the old one.
5683                          */
5684                         mp->mnt_rootvnode = NULL;
5685                 }
5686                 MNT_IUNLOCK(mp);
5687                 if (vp != NULL) {
5688                         /*
5689                          * Paired with a fence in vfs_op_thread_exit().
5690                          */
5691                         atomic_thread_fence_acq();
5692                         vfs_op_barrier_wait(mp);
5693                         vrele(vp);
5694                 }
5695         }
5696         error = VFS_CACHEDROOT(mp, flags, vpp);
5697         if (error != 0)
5698                 return (error);
5699         if (mp->mnt_vfs_ops == 0) {
5700                 MNT_ILOCK(mp);
5701                 if (mp->mnt_vfs_ops != 0) {
5702                         MNT_IUNLOCK(mp);
5703                         return (0);
5704                 }
5705                 if (mp->mnt_rootvnode == NULL) {
5706                         vrefact(*vpp);
5707                         mp->mnt_rootvnode = *vpp;
5708                 } else {
5709                         if (mp->mnt_rootvnode != *vpp) {
5710                                 if ((mp->mnt_rootvnode->v_iflag & VI_DOOMED) == 0) {
5711                                         panic("%s: mismatch between vnode returned "
5712                                             " by VFS_CACHEDROOT and the one cached "
5713                                             " (%p != %p)",
5714                                             __func__, *vpp, mp->mnt_rootvnode);
5715                                 }
5716                         }
5717                 }
5718                 MNT_IUNLOCK(mp);
5719         }
5720         return (0);
5721 }
5722
5723 int
5724 vfs_cache_root(struct mount *mp, int flags, struct vnode **vpp)
5725 {
5726         struct vnode *vp;
5727         int error;
5728
5729         if (!vfs_op_thread_enter(mp))
5730                 return (vfs_cache_root_fallback(mp, flags, vpp));
5731         vp = (struct vnode *)atomic_load_ptr(&mp->mnt_rootvnode);
5732         if (vp == NULL || (vp->v_iflag & VI_DOOMED)) {
5733                 vfs_op_thread_exit(mp);
5734                 return (vfs_cache_root_fallback(mp, flags, vpp));
5735         }
5736         vrefact(vp);
5737         vfs_op_thread_exit(mp);
5738         error = vn_lock(vp, flags);
5739         if (error != 0) {
5740                 vrele(vp);
5741                 return (vfs_cache_root_fallback(mp, flags, vpp));
5742         }
5743         *vpp = vp;
5744         return (0);
5745 }
5746
5747 struct vnode *
5748 vfs_cache_root_clear(struct mount *mp)
5749 {
5750         struct vnode *vp;
5751
5752         /*
5753          * ops > 0 guarantees there is nobody who can see this vnode
5754          */
5755         MPASS(mp->mnt_vfs_ops > 0);
5756         vp = mp->mnt_rootvnode;
5757         mp->mnt_rootvnode = NULL;
5758         return (vp);
5759 }
5760
5761 void
5762 vfs_cache_root_set(struct mount *mp, struct vnode *vp)
5763 {
5764
5765         MPASS(mp->mnt_vfs_ops > 0);
5766         vrefact(vp);
5767         mp->mnt_rootvnode = vp;
5768 }
5769
5770 /*
5771  * These are helper functions for filesystems to traverse all
5772  * their vnodes.  See MNT_VNODE_FOREACH_ALL() in sys/mount.h.
5773  *
5774  * This interface replaces MNT_VNODE_FOREACH.
5775  */
5776
5777 MALLOC_DEFINE(M_VNODE_MARKER, "vnodemarker", "vnode marker");
5778
5779 struct vnode *
5780 __mnt_vnode_next_all(struct vnode **mvp, struct mount *mp)
5781 {
5782         struct vnode *vp;
5783
5784         if (should_yield())
5785                 kern_yield(PRI_USER);
5786         MNT_ILOCK(mp);
5787         KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
5788         for (vp = TAILQ_NEXT(*mvp, v_nmntvnodes); vp != NULL;
5789             vp = TAILQ_NEXT(vp, v_nmntvnodes)) {
5790                 /* Allow a racy peek at VI_DOOMED to save a lock acquisition. */
5791                 if (vp->v_type == VMARKER || (vp->v_iflag & VI_DOOMED) != 0)
5792                         continue;
5793                 VI_LOCK(vp);
5794                 if ((vp->v_iflag & VI_DOOMED) != 0) {
5795                         VI_UNLOCK(vp);
5796                         continue;
5797                 }
5798                 break;
5799         }
5800         if (vp == NULL) {
5801                 __mnt_vnode_markerfree_all(mvp, mp);
5802                 /* MNT_IUNLOCK(mp); -- done in above function */
5803                 mtx_assert(MNT_MTX(mp), MA_NOTOWNED);
5804                 return (NULL);
5805         }
5806         TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
5807         TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
5808         MNT_IUNLOCK(mp);
5809         return (vp);
5810 }
5811
5812 struct vnode *
5813 __mnt_vnode_first_all(struct vnode **mvp, struct mount *mp)
5814 {
5815         struct vnode *vp;
5816
5817         *mvp = malloc(sizeof(struct vnode), M_VNODE_MARKER, M_WAITOK | M_ZERO);
5818         MNT_ILOCK(mp);
5819         MNT_REF(mp);
5820         (*mvp)->v_mount = mp;
5821         (*mvp)->v_type = VMARKER;
5822
5823         TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
5824                 /* Allow a racy peek at VI_DOOMED to save a lock acquisition. */
5825                 if (vp->v_type == VMARKER || (vp->v_iflag & VI_DOOMED) != 0)
5826                         continue;
5827                 VI_LOCK(vp);
5828                 if ((vp->v_iflag & VI_DOOMED) != 0) {
5829                         VI_UNLOCK(vp);
5830                         continue;
5831                 }
5832                 break;
5833         }
5834         if (vp == NULL) {
5835                 MNT_REL(mp);
5836                 MNT_IUNLOCK(mp);
5837                 free(*mvp, M_VNODE_MARKER);
5838                 *mvp = NULL;
5839                 return (NULL);
5840         }
5841         TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
5842         MNT_IUNLOCK(mp);
5843         return (vp);
5844 }
5845
5846 void
5847 __mnt_vnode_markerfree_all(struct vnode **mvp, struct mount *mp)
5848 {
5849
5850         if (*mvp == NULL) {
5851                 MNT_IUNLOCK(mp);
5852                 return;
5853         }
5854
5855         mtx_assert(MNT_MTX(mp), MA_OWNED);
5856
5857         KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
5858         TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
5859         MNT_REL(mp);
5860         MNT_IUNLOCK(mp);
5861         free(*mvp, M_VNODE_MARKER);
5862         *mvp = NULL;
5863 }
5864
5865 /*
5866  * These are helper functions for filesystems to traverse their
5867  * active vnodes.  See MNT_VNODE_FOREACH_ACTIVE() in sys/mount.h
5868  */
5869 static void
5870 mnt_vnode_markerfree_active(struct vnode **mvp, struct mount *mp)
5871 {
5872
5873         KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
5874
5875         MNT_ILOCK(mp);
5876         MNT_REL(mp);
5877         MNT_IUNLOCK(mp);
5878         free(*mvp, M_VNODE_MARKER);
5879         *mvp = NULL;
5880 }
5881
5882 /*
5883  * Relock the mp mount vnode list lock with the vp vnode interlock in the
5884  * conventional lock order during mnt_vnode_next_active iteration.
5885  *
5886  * On entry, the mount vnode list lock is held and the vnode interlock is not.
5887  * The list lock is dropped and reacquired.  On success, both locks are held.
5888  * On failure, the mount vnode list lock is held but the vnode interlock is
5889  * not, and the procedure may have yielded.
5890  */
5891 static bool
5892 mnt_vnode_next_active_relock(struct vnode *mvp, struct mount *mp,
5893     struct vnode *vp)
5894 {
5895         const struct vnode *tmp;
5896         bool held, ret;
5897
5898         VNASSERT(mvp->v_mount == mp && mvp->v_type == VMARKER &&
5899             TAILQ_NEXT(mvp, v_actfreelist) != NULL, mvp,
5900             ("%s: bad marker", __func__));
5901         VNASSERT(vp->v_mount == mp && vp->v_type != VMARKER, vp,
5902             ("%s: inappropriate vnode", __func__));
5903         ASSERT_VI_UNLOCKED(vp, __func__);
5904         mtx_assert(&mp->mnt_listmtx, MA_OWNED);
5905
5906         ret = false;
5907
5908         TAILQ_REMOVE(&mp->mnt_activevnodelist, mvp, v_actfreelist);
5909         TAILQ_INSERT_BEFORE(vp, mvp, v_actfreelist);
5910
5911         /*
5912          * Use a hold to prevent vp from disappearing while the mount vnode
5913          * list lock is dropped and reacquired.  Normally a hold would be
5914          * acquired with vhold(), but that might try to acquire the vnode
5915          * interlock, which would be a LOR with the mount vnode list lock.
5916          */
5917         held = refcount_acquire_if_not_zero(&vp->v_holdcnt);
5918         mtx_unlock(&mp->mnt_listmtx);
5919         if (!held)
5920                 goto abort;
5921         VI_LOCK(vp);
5922         if (!refcount_release_if_not_last(&vp->v_holdcnt)) {
5923                 vdropl(vp);
5924                 goto abort;
5925         }
5926         mtx_lock(&mp->mnt_listmtx);
5927
5928         /*
5929          * Determine whether the vnode is still the next one after the marker,
5930          * excepting any other markers.  If the vnode has not been doomed by
5931          * vgone() then the hold should have ensured that it remained on the
5932          * active list.  If it has been doomed but is still on the active list,
5933          * don't abort, but rather skip over it (avoid spinning on doomed
5934          * vnodes).
5935          */
5936         tmp = mvp;
5937         do {
5938                 tmp = TAILQ_NEXT(tmp, v_actfreelist);
5939         } while (tmp != NULL && tmp->v_type == VMARKER);
5940         if (tmp != vp) {
5941                 mtx_unlock(&mp->mnt_listmtx);
5942                 VI_UNLOCK(vp);
5943                 goto abort;
5944         }
5945
5946         ret = true;
5947         goto out;
5948 abort:
5949         maybe_yield();
5950         mtx_lock(&mp->mnt_listmtx);
5951 out:
5952         if (ret)
5953                 ASSERT_VI_LOCKED(vp, __func__);
5954         else
5955                 ASSERT_VI_UNLOCKED(vp, __func__);
5956         mtx_assert(&mp->mnt_listmtx, MA_OWNED);
5957         return (ret);
5958 }
5959
5960 static struct vnode *
5961 mnt_vnode_next_active(struct vnode **mvp, struct mount *mp)
5962 {
5963         struct vnode *vp, *nvp;
5964
5965         mtx_assert(&mp->mnt_listmtx, MA_OWNED);
5966         KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
5967 restart:
5968         vp = TAILQ_NEXT(*mvp, v_actfreelist);
5969         while (vp != NULL) {
5970                 if (vp->v_type == VMARKER) {
5971                         vp = TAILQ_NEXT(vp, v_actfreelist);
5972                         continue;
5973                 }
5974                 /*
5975                  * Try-lock because this is the wrong lock order.  If that does
5976                  * not succeed, drop the mount vnode list lock and try to
5977                  * reacquire it and the vnode interlock in the right order.
5978                  */
5979                 if (!VI_TRYLOCK(vp) &&
5980                     !mnt_vnode_next_active_relock(*mvp, mp, vp))
5981                         goto restart;
5982                 KASSERT(vp->v_type != VMARKER, ("locked marker %p", vp));
5983                 KASSERT(vp->v_mount == mp || vp->v_mount == NULL,
5984                     ("alien vnode on the active list %p %p", vp, mp));
5985                 if (vp->v_mount == mp && (vp->v_iflag & VI_DOOMED) == 0)
5986                         break;
5987                 nvp = TAILQ_NEXT(vp, v_actfreelist);
5988                 VI_UNLOCK(vp);
5989                 vp = nvp;
5990         }
5991         TAILQ_REMOVE(&mp->mnt_activevnodelist, *mvp, v_actfreelist);
5992
5993         /* Check if we are done */
5994         if (vp == NULL) {
5995                 mtx_unlock(&mp->mnt_listmtx);
5996                 mnt_vnode_markerfree_active(mvp, mp);
5997                 return (NULL);
5998         }
5999         TAILQ_INSERT_AFTER(&mp->mnt_activevnodelist, vp, *mvp, v_actfreelist);
6000         mtx_unlock(&mp->mnt_listmtx);
6001         ASSERT_VI_LOCKED(vp, "active iter");
6002         KASSERT((vp->v_iflag & VI_ACTIVE) != 0, ("Non-active vp %p", vp));
6003         return (vp);
6004 }
6005
6006 struct vnode *
6007 __mnt_vnode_next_active(struct vnode **mvp, struct mount *mp)
6008 {
6009
6010         if (should_yield())
6011                 kern_yield(PRI_USER);
6012         mtx_lock(&mp->mnt_listmtx);
6013         return (mnt_vnode_next_active(mvp, mp));
6014 }
6015
6016 struct vnode *
6017 __mnt_vnode_first_active(struct vnode **mvp, struct mount *mp)
6018 {
6019         struct vnode *vp;
6020
6021         *mvp = malloc(sizeof(struct vnode), M_VNODE_MARKER, M_WAITOK | M_ZERO);
6022         MNT_ILOCK(mp);
6023         MNT_REF(mp);
6024         MNT_IUNLOCK(mp);
6025         (*mvp)->v_type = VMARKER;
6026         (*mvp)->v_mount = mp;
6027
6028         mtx_lock(&mp->mnt_listmtx);
6029         vp = TAILQ_FIRST(&mp->mnt_activevnodelist);
6030         if (vp == NULL) {
6031                 mtx_unlock(&mp->mnt_listmtx);
6032                 mnt_vnode_markerfree_active(mvp, mp);
6033                 return (NULL);
6034         }
6035         TAILQ_INSERT_BEFORE(vp, *mvp, v_actfreelist);
6036         return (mnt_vnode_next_active(mvp, mp));
6037 }
6038
6039 void
6040 __mnt_vnode_markerfree_active(struct vnode **mvp, struct mount *mp)
6041 {
6042
6043         if (*mvp == NULL)
6044                 return;
6045
6046         mtx_lock(&mp->mnt_listmtx);
6047         TAILQ_REMOVE(&mp->mnt_activevnodelist, *mvp, v_actfreelist);
6048         mtx_unlock(&mp->mnt_listmtx);
6049         mnt_vnode_markerfree_active(mvp, mp);
6050 }