xref: /freebsd/sys/kern/vfs_subr.c (revision 864c53ead899f7838cd2e1cca3b485a4a82f5cdc)
1 /*-
2  * Copyright (c) 1989, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  * (c) UNIX System Laboratories, Inc.
5  * All or some portions of this file are derived from material licensed
6  * to the University of California by American Telephone and Telegraph
7  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8  * the permission of UNIX System Laboratories, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 4. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *	@(#)vfs_subr.c	8.31 (Berkeley) 5/26/95
35  */
36 
37 /*
38  * External virtual filesystem routines
39  */
40 
41 #include <sys/cdefs.h>
42 __FBSDID("$FreeBSD$");
43 
44 #include "opt_compat.h"
45 #include "opt_ddb.h"
46 #include "opt_watchdog.h"
47 
48 #include <sys/param.h>
49 #include <sys/systm.h>
50 #include <sys/bio.h>
51 #include <sys/buf.h>
52 #include <sys/condvar.h>
53 #include <sys/conf.h>
54 #include <sys/dirent.h>
55 #include <sys/event.h>
56 #include <sys/eventhandler.h>
57 #include <sys/extattr.h>
58 #include <sys/file.h>
59 #include <sys/fcntl.h>
60 #include <sys/jail.h>
61 #include <sys/kdb.h>
62 #include <sys/kernel.h>
63 #include <sys/kthread.h>
64 #include <sys/lockf.h>
65 #include <sys/malloc.h>
66 #include <sys/mount.h>
67 #include <sys/namei.h>
68 #include <sys/pctrie.h>
69 #include <sys/priv.h>
70 #include <sys/reboot.h>
71 #include <sys/rwlock.h>
72 #include <sys/sched.h>
73 #include <sys/sleepqueue.h>
74 #include <sys/smp.h>
75 #include <sys/stat.h>
76 #include <sys/sysctl.h>
77 #include <sys/syslog.h>
78 #include <sys/vmmeter.h>
79 #include <sys/vnode.h>
80 #include <sys/watchdog.h>
81 
82 #include <machine/stdarg.h>
83 
84 #include <security/mac/mac_framework.h>
85 
86 #include <vm/vm.h>
87 #include <vm/vm_object.h>
88 #include <vm/vm_extern.h>
89 #include <vm/pmap.h>
90 #include <vm/vm_map.h>
91 #include <vm/vm_page.h>
92 #include <vm/vm_kern.h>
93 #include <vm/uma.h>
94 
95 #ifdef DDB
96 #include <ddb/ddb.h>
97 #endif
98 
99 static void	delmntque(struct vnode *vp);
100 static int	flushbuflist(struct bufv *bufv, int flags, struct bufobj *bo,
101 		    int slpflag, int slptimeo);
102 static void	syncer_shutdown(void *arg, int howto);
103 static int	vtryrecycle(struct vnode *vp);
104 static void	v_incr_usecount(struct vnode *);
105 static void	v_decr_usecount(struct vnode *);
106 static void	v_decr_useonly(struct vnode *);
107 static void	v_upgrade_usecount(struct vnode *);
108 static void	vnlru_free(int);
109 static void	vgonel(struct vnode *);
110 static void	vfs_knllock(void *arg);
111 static void	vfs_knlunlock(void *arg);
112 static void	vfs_knl_assert_locked(void *arg);
113 static void	vfs_knl_assert_unlocked(void *arg);
114 static void	destroy_vpollinfo(struct vpollinfo *vi);
115 
116 /*
117  * Number of vnodes in existence.  Increased whenever getnewvnode()
118  * allocates a new vnode, decreased in vdropl() for VI_DOOMED vnode.
119  */
120 static unsigned long	numvnodes;
121 
122 SYSCTL_ULONG(_vfs, OID_AUTO, numvnodes, CTLFLAG_RD, &numvnodes, 0,
123     "Number of vnodes in existence");
124 
125 /*
126  * Conversion tables for conversion from vnode types to inode formats
127  * and back.
128  */
129 enum vtype iftovt_tab[16] = {
130 	VNON, VFIFO, VCHR, VNON, VDIR, VNON, VBLK, VNON,
131 	VREG, VNON, VLNK, VNON, VSOCK, VNON, VNON, VBAD,
132 };
133 int vttoif_tab[10] = {
134 	0, S_IFREG, S_IFDIR, S_IFBLK, S_IFCHR, S_IFLNK,
135 	S_IFSOCK, S_IFIFO, S_IFMT, S_IFMT
136 };
137 
138 /*
139  * List of vnodes that are ready for recycling.
140  */
141 static TAILQ_HEAD(freelst, vnode) vnode_free_list;
142 
143 /*
144  * Free vnode target.  Free vnodes may simply be files which have been stat'd
145  * but not read.  This is somewhat common, and a small cache of such files
146  * should be kept to avoid recreation costs.
147  */
148 static u_long wantfreevnodes;
149 SYSCTL_ULONG(_vfs, OID_AUTO, wantfreevnodes, CTLFLAG_RW, &wantfreevnodes, 0, "");
150 /* Number of vnodes in the free list. */
151 static u_long freevnodes;
152 SYSCTL_ULONG(_vfs, OID_AUTO, freevnodes, CTLFLAG_RD, &freevnodes, 0,
153     "Number of vnodes in the free list");
154 
155 static int vlru_allow_cache_src;
156 SYSCTL_INT(_vfs, OID_AUTO, vlru_allow_cache_src, CTLFLAG_RW,
157     &vlru_allow_cache_src, 0, "Allow vlru to reclaim source vnode");
158 
159 /*
160  * Various variables used for debugging the new implementation of
161  * reassignbuf().
162  * XXX these are probably of (very) limited utility now.
163  */
164 static int reassignbufcalls;
165 SYSCTL_INT(_vfs, OID_AUTO, reassignbufcalls, CTLFLAG_RW, &reassignbufcalls, 0,
166     "Number of calls to reassignbuf");
167 
168 /*
169  * Cache for the mount type id assigned to NFS.  This is used for
170  * special checks in nfs/nfs_nqlease.c and vm/vnode_pager.c.
171  */
172 int	nfs_mount_type = -1;
173 
174 /* To keep more than one thread at a time from running vfs_getnewfsid */
175 static struct mtx mntid_mtx;
176 
177 /*
178  * Lock for any access to the following:
179  *	vnode_free_list
180  *	numvnodes
181  *	freevnodes
182  */
183 static struct mtx vnode_free_list_mtx;
184 
185 /* Publicly exported FS */
186 struct nfs_public nfs_pub;
187 
188 static uma_zone_t buf_trie_zone;
189 
190 /* Zone for allocation of new vnodes - used exclusively by getnewvnode() */
191 static uma_zone_t vnode_zone;
192 static uma_zone_t vnodepoll_zone;
193 
194 /*
195  * The workitem queue.
196  *
197  * It is useful to delay writes of file data and filesystem metadata
198  * for tens of seconds so that quickly created and deleted files need
199  * not waste disk bandwidth being created and removed. To realize this,
200  * we append vnodes to a "workitem" queue. When running with a soft
201  * updates implementation, most pending metadata dependencies should
202  * not wait for more than a few seconds. Thus, mounted on block devices
203  * are delayed only about a half the time that file data is delayed.
204  * Similarly, directory updates are more critical, so are only delayed
205  * about a third the time that file data is delayed. Thus, there are
206  * SYNCER_MAXDELAY queues that are processed round-robin at a rate of
207  * one each second (driven off the filesystem syncer process). The
208  * syncer_delayno variable indicates the next queue that is to be processed.
209  * Items that need to be processed soon are placed in this queue:
210  *
211  *	syncer_workitem_pending[syncer_delayno]
212  *
213  * A delay of fifteen seconds is done by placing the request fifteen
214  * entries later in the queue:
215  *
216  *	syncer_workitem_pending[(syncer_delayno + 15) & syncer_mask]
217  *
218  */
219 static int syncer_delayno;
220 static long syncer_mask;
221 LIST_HEAD(synclist, bufobj);
222 static struct synclist *syncer_workitem_pending;
223 /*
224  * The sync_mtx protects:
225  *	bo->bo_synclist
226  *	sync_vnode_count
227  *	syncer_delayno
228  *	syncer_state
229  *	syncer_workitem_pending
230  *	syncer_worklist_len
231  *	rushjob
232  */
233 static struct mtx sync_mtx;
234 static struct cv sync_wakeup;
235 
236 #define SYNCER_MAXDELAY		32
237 static int syncer_maxdelay = SYNCER_MAXDELAY;	/* maximum delay time */
238 static int syncdelay = 30;		/* max time to delay syncing data */
239 static int filedelay = 30;		/* time to delay syncing files */
240 SYSCTL_INT(_kern, OID_AUTO, filedelay, CTLFLAG_RW, &filedelay, 0,
241     "Time to delay syncing files (in seconds)");
242 static int dirdelay = 29;		/* time to delay syncing directories */
243 SYSCTL_INT(_kern, OID_AUTO, dirdelay, CTLFLAG_RW, &dirdelay, 0,
244     "Time to delay syncing directories (in seconds)");
245 static int metadelay = 28;		/* time to delay syncing metadata */
246 SYSCTL_INT(_kern, OID_AUTO, metadelay, CTLFLAG_RW, &metadelay, 0,
247     "Time to delay syncing metadata (in seconds)");
248 static int rushjob;		/* number of slots to run ASAP */
249 static int stat_rush_requests;	/* number of times I/O speeded up */
250 SYSCTL_INT(_debug, OID_AUTO, rush_requests, CTLFLAG_RW, &stat_rush_requests, 0,
251     "Number of times I/O speeded up (rush requests)");
252 
253 /*
254  * When shutting down the syncer, run it at four times normal speed.
255  */
256 #define SYNCER_SHUTDOWN_SPEEDUP		4
257 static int sync_vnode_count;
258 static int syncer_worklist_len;
259 static enum { SYNCER_RUNNING, SYNCER_SHUTTING_DOWN, SYNCER_FINAL_DELAY }
260     syncer_state;
261 
262 /*
263  * Number of vnodes we want to exist at any one time.  This is mostly used
264  * to size hash tables in vnode-related code.  It is normally not used in
265  * getnewvnode(), as wantfreevnodes is normally nonzero.)
266  *
267  * XXX desiredvnodes is historical cruft and should not exist.
268  */
269 int desiredvnodes;
270 SYSCTL_INT(_kern, KERN_MAXVNODES, maxvnodes, CTLFLAG_RW,
271     &desiredvnodes, 0, "Maximum number of vnodes");
272 SYSCTL_ULONG(_kern, OID_AUTO, minvnodes, CTLFLAG_RW,
273     &wantfreevnodes, 0, "Minimum number of vnodes (legacy)");
274 static int vnlru_nowhere;
275 SYSCTL_INT(_debug, OID_AUTO, vnlru_nowhere, CTLFLAG_RW,
276     &vnlru_nowhere, 0, "Number of times the vnlru process ran without success");
277 
278 /*
279  * Macros to control when a vnode is freed and recycled.  All require
280  * the vnode interlock.
281  */
282 #define VCANRECYCLE(vp) (((vp)->v_iflag & VI_FREE) && !(vp)->v_holdcnt)
283 #define VSHOULDFREE(vp) (!((vp)->v_iflag & VI_FREE) && !(vp)->v_holdcnt)
284 #define VSHOULDBUSY(vp) (((vp)->v_iflag & VI_FREE) && (vp)->v_holdcnt)
285 
286 /* Shift count for (uintptr_t)vp to initialize vp->v_hash. */
287 static int vnsz2log;
288 
289 /*
290  * Support for the bufobj clean & dirty pctrie.
291  */
292 static void *
293 buf_trie_alloc(struct pctrie *ptree)
294 {
295 
296 	return uma_zalloc(buf_trie_zone, M_NOWAIT);
297 }
298 
299 static void
300 buf_trie_free(struct pctrie *ptree, void *node)
301 {
302 
303 	uma_zfree(buf_trie_zone, node);
304 }
305 PCTRIE_DEFINE(BUF, buf, b_lblkno, buf_trie_alloc, buf_trie_free);
306 
307 /*
308  * Initialize the vnode management data structures.
309  *
310  * Reevaluate the following cap on the number of vnodes after the physical
311  * memory size exceeds 512GB.  In the limit, as the physical memory size
312  * grows, the ratio of physical pages to vnodes approaches sixteen to one.
313  */
314 #ifndef	MAXVNODES_MAX
315 #define	MAXVNODES_MAX	(512 * (1024 * 1024 * 1024 / (int)PAGE_SIZE / 16))
316 #endif
317 static void
318 vntblinit(void *dummy __unused)
319 {
320 	u_int i;
321 	int physvnodes, virtvnodes;
322 
323 	/*
324 	 * Desiredvnodes is a function of the physical memory size and the
325 	 * kernel's heap size.  Generally speaking, it scales with the
326 	 * physical memory size.  The ratio of desiredvnodes to physical pages
327 	 * is one to four until desiredvnodes exceeds 98,304.  Thereafter, the
328 	 * marginal ratio of desiredvnodes to physical pages is one to
329 	 * sixteen.  However, desiredvnodes is limited by the kernel's heap
330 	 * size.  The memory required by desiredvnodes vnodes and vm objects
331 	 * may not exceed one seventh of the kernel's heap size.
332 	 */
333 	physvnodes = maxproc + vm_cnt.v_page_count / 16 + 3 * min(98304 * 4,
334 	    vm_cnt.v_page_count) / 16;
335 	virtvnodes = vm_kmem_size / (7 * (sizeof(struct vm_object) +
336 	    sizeof(struct vnode)));
337 	desiredvnodes = min(physvnodes, virtvnodes);
338 	if (desiredvnodes > MAXVNODES_MAX) {
339 		if (bootverbose)
340 			printf("Reducing kern.maxvnodes %d -> %d\n",
341 			    desiredvnodes, MAXVNODES_MAX);
342 		desiredvnodes = MAXVNODES_MAX;
343 	}
344 	wantfreevnodes = desiredvnodes / 4;
345 	mtx_init(&mntid_mtx, "mntid", NULL, MTX_DEF);
346 	TAILQ_INIT(&vnode_free_list);
347 	mtx_init(&vnode_free_list_mtx, "vnode_free_list", NULL, MTX_DEF);
348 	vnode_zone = uma_zcreate("VNODE", sizeof (struct vnode), NULL, NULL,
349 	    NULL, NULL, UMA_ALIGN_PTR, 0);
350 	vnodepoll_zone = uma_zcreate("VNODEPOLL", sizeof (struct vpollinfo),
351 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
352 	/*
353 	 * Preallocate enough nodes to support one-per buf so that
354 	 * we can not fail an insert.  reassignbuf() callers can not
355 	 * tolerate the insertion failure.
356 	 */
357 	buf_trie_zone = uma_zcreate("BUF TRIE", pctrie_node_size(),
358 	    NULL, NULL, pctrie_zone_init, NULL, UMA_ALIGN_PTR,
359 	    UMA_ZONE_NOFREE | UMA_ZONE_VM);
360 	uma_prealloc(buf_trie_zone, nbuf);
361 	/*
362 	 * Initialize the filesystem syncer.
363 	 */
364 	syncer_workitem_pending = hashinit(syncer_maxdelay, M_VNODE,
365 	    &syncer_mask);
366 	syncer_maxdelay = syncer_mask + 1;
367 	mtx_init(&sync_mtx, "Syncer mtx", NULL, MTX_DEF);
368 	cv_init(&sync_wakeup, "syncer");
369 	for (i = 1; i <= sizeof(struct vnode); i <<= 1)
370 		vnsz2log++;
371 	vnsz2log--;
372 }
373 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_FIRST, vntblinit, NULL);
374 
375 
376 /*
377  * Mark a mount point as busy. Used to synchronize access and to delay
378  * unmounting. Eventually, mountlist_mtx is not released on failure.
379  *
380  * vfs_busy() is a custom lock, it can block the caller.
381  * vfs_busy() only sleeps if the unmount is active on the mount point.
382  * For a mountpoint mp, vfs_busy-enforced lock is before lock of any
383  * vnode belonging to mp.
384  *
385  * Lookup uses vfs_busy() to traverse mount points.
386  * root fs			var fs
387  * / vnode lock		A	/ vnode lock (/var)		D
388  * /var vnode lock	B	/log vnode lock(/var/log)	E
389  * vfs_busy lock	C	vfs_busy lock			F
390  *
391  * Within each file system, the lock order is C->A->B and F->D->E.
392  *
393  * When traversing across mounts, the system follows that lock order:
394  *
395  *        C->A->B
396  *              |
397  *              +->F->D->E
398  *
399  * The lookup() process for namei("/var") illustrates the process:
400  *  VOP_LOOKUP() obtains B while A is held
401  *  vfs_busy() obtains a shared lock on F while A and B are held
402  *  vput() releases lock on B
403  *  vput() releases lock on A
404  *  VFS_ROOT() obtains lock on D while shared lock on F is held
405  *  vfs_unbusy() releases shared lock on F
406  *  vn_lock() obtains lock on deadfs vnode vp_crossmp instead of A.
407  *    Attempt to lock A (instead of vp_crossmp) while D is held would
408  *    violate the global order, causing deadlocks.
409  *
410  * dounmount() locks B while F is drained.
411  */
412 int
413 vfs_busy(struct mount *mp, int flags)
414 {
415 
416 	MPASS((flags & ~MBF_MASK) == 0);
417 	CTR3(KTR_VFS, "%s: mp %p with flags %d", __func__, mp, flags);
418 
419 	MNT_ILOCK(mp);
420 	MNT_REF(mp);
421 	/*
422 	 * If mount point is currenly being unmounted, sleep until the
423 	 * mount point fate is decided.  If thread doing the unmounting fails,
424 	 * it will clear MNTK_UNMOUNT flag before waking us up, indicating
425 	 * that this mount point has survived the unmount attempt and vfs_busy
426 	 * should retry.  Otherwise the unmounter thread will set MNTK_REFEXPIRE
427 	 * flag in addition to MNTK_UNMOUNT, indicating that mount point is
428 	 * about to be really destroyed.  vfs_busy needs to release its
429 	 * reference on the mount point in this case and return with ENOENT,
430 	 * telling the caller that mount mount it tried to busy is no longer
431 	 * valid.
432 	 */
433 	while (mp->mnt_kern_flag & MNTK_UNMOUNT) {
434 		if (flags & MBF_NOWAIT || mp->mnt_kern_flag & MNTK_REFEXPIRE) {
435 			MNT_REL(mp);
436 			MNT_IUNLOCK(mp);
437 			CTR1(KTR_VFS, "%s: failed busying before sleeping",
438 			    __func__);
439 			return (ENOENT);
440 		}
441 		if (flags & MBF_MNTLSTLOCK)
442 			mtx_unlock(&mountlist_mtx);
443 		mp->mnt_kern_flag |= MNTK_MWAIT;
444 		msleep(mp, MNT_MTX(mp), PVFS | PDROP, "vfs_busy", 0);
445 		if (flags & MBF_MNTLSTLOCK)
446 			mtx_lock(&mountlist_mtx);
447 		MNT_ILOCK(mp);
448 	}
449 	if (flags & MBF_MNTLSTLOCK)
450 		mtx_unlock(&mountlist_mtx);
451 	mp->mnt_lockref++;
452 	MNT_IUNLOCK(mp);
453 	return (0);
454 }
455 
456 /*
457  * Free a busy filesystem.
458  */
459 void
460 vfs_unbusy(struct mount *mp)
461 {
462 
463 	CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
464 	MNT_ILOCK(mp);
465 	MNT_REL(mp);
466 	KASSERT(mp->mnt_lockref > 0, ("negative mnt_lockref"));
467 	mp->mnt_lockref--;
468 	if (mp->mnt_lockref == 0 && (mp->mnt_kern_flag & MNTK_DRAINING) != 0) {
469 		MPASS(mp->mnt_kern_flag & MNTK_UNMOUNT);
470 		CTR1(KTR_VFS, "%s: waking up waiters", __func__);
471 		mp->mnt_kern_flag &= ~MNTK_DRAINING;
472 		wakeup(&mp->mnt_lockref);
473 	}
474 	MNT_IUNLOCK(mp);
475 }
476 
477 /*
478  * Lookup a mount point by filesystem identifier.
479  */
480 struct mount *
481 vfs_getvfs(fsid_t *fsid)
482 {
483 	struct mount *mp;
484 
485 	CTR2(KTR_VFS, "%s: fsid %p", __func__, fsid);
486 	mtx_lock(&mountlist_mtx);
487 	TAILQ_FOREACH(mp, &mountlist, mnt_list) {
488 		if (mp->mnt_stat.f_fsid.val[0] == fsid->val[0] &&
489 		    mp->mnt_stat.f_fsid.val[1] == fsid->val[1]) {
490 			vfs_ref(mp);
491 			mtx_unlock(&mountlist_mtx);
492 			return (mp);
493 		}
494 	}
495 	mtx_unlock(&mountlist_mtx);
496 	CTR2(KTR_VFS, "%s: lookup failed for %p id", __func__, fsid);
497 	return ((struct mount *) 0);
498 }
499 
500 /*
501  * Lookup a mount point by filesystem identifier, busying it before
502  * returning.
503  */
504 struct mount *
505 vfs_busyfs(fsid_t *fsid)
506 {
507 	struct mount *mp;
508 	int error;
509 
510 	CTR2(KTR_VFS, "%s: fsid %p", __func__, fsid);
511 	mtx_lock(&mountlist_mtx);
512 	TAILQ_FOREACH(mp, &mountlist, mnt_list) {
513 		if (mp->mnt_stat.f_fsid.val[0] == fsid->val[0] &&
514 		    mp->mnt_stat.f_fsid.val[1] == fsid->val[1]) {
515 			error = vfs_busy(mp, MBF_MNTLSTLOCK);
516 			if (error) {
517 				mtx_unlock(&mountlist_mtx);
518 				return (NULL);
519 			}
520 			return (mp);
521 		}
522 	}
523 	CTR2(KTR_VFS, "%s: lookup failed for %p id", __func__, fsid);
524 	mtx_unlock(&mountlist_mtx);
525 	return ((struct mount *) 0);
526 }
527 
528 /*
529  * Check if a user can access privileged mount options.
530  */
531 int
532 vfs_suser(struct mount *mp, struct thread *td)
533 {
534 	int error;
535 
536 	/*
537 	 * If the thread is jailed, but this is not a jail-friendly file
538 	 * system, deny immediately.
539 	 */
540 	if (!(mp->mnt_vfc->vfc_flags & VFCF_JAIL) && jailed(td->td_ucred))
541 		return (EPERM);
542 
543 	/*
544 	 * If the file system was mounted outside the jail of the calling
545 	 * thread, deny immediately.
546 	 */
547 	if (prison_check(td->td_ucred, mp->mnt_cred) != 0)
548 		return (EPERM);
549 
550 	/*
551 	 * If file system supports delegated administration, we don't check
552 	 * for the PRIV_VFS_MOUNT_OWNER privilege - it will be better verified
553 	 * by the file system itself.
554 	 * If this is not the user that did original mount, we check for
555 	 * the PRIV_VFS_MOUNT_OWNER privilege.
556 	 */
557 	if (!(mp->mnt_vfc->vfc_flags & VFCF_DELEGADMIN) &&
558 	    mp->mnt_cred->cr_uid != td->td_ucred->cr_uid) {
559 		if ((error = priv_check(td, PRIV_VFS_MOUNT_OWNER)) != 0)
560 			return (error);
561 	}
562 	return (0);
563 }
564 
565 /*
566  * Get a new unique fsid.  Try to make its val[0] unique, since this value
567  * will be used to create fake device numbers for stat().  Also try (but
568  * not so hard) make its val[0] unique mod 2^16, since some emulators only
569  * support 16-bit device numbers.  We end up with unique val[0]'s for the
570  * first 2^16 calls and unique val[0]'s mod 2^16 for the first 2^8 calls.
571  *
572  * Keep in mind that several mounts may be running in parallel.  Starting
573  * the search one past where the previous search terminated is both a
574  * micro-optimization and a defense against returning the same fsid to
575  * different mounts.
576  */
577 void
578 vfs_getnewfsid(struct mount *mp)
579 {
580 	static uint16_t mntid_base;
581 	struct mount *nmp;
582 	fsid_t tfsid;
583 	int mtype;
584 
585 	CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
586 	mtx_lock(&mntid_mtx);
587 	mtype = mp->mnt_vfc->vfc_typenum;
588 	tfsid.val[1] = mtype;
589 	mtype = (mtype & 0xFF) << 24;
590 	for (;;) {
591 		tfsid.val[0] = makedev(255,
592 		    mtype | ((mntid_base & 0xFF00) << 8) | (mntid_base & 0xFF));
593 		mntid_base++;
594 		if ((nmp = vfs_getvfs(&tfsid)) == NULL)
595 			break;
596 		vfs_rel(nmp);
597 	}
598 	mp->mnt_stat.f_fsid.val[0] = tfsid.val[0];
599 	mp->mnt_stat.f_fsid.val[1] = tfsid.val[1];
600 	mtx_unlock(&mntid_mtx);
601 }
602 
603 /*
604  * Knob to control the precision of file timestamps:
605  *
606  *   0 = seconds only; nanoseconds zeroed.
607  *   1 = seconds and nanoseconds, accurate within 1/HZ.
608  *   2 = seconds and nanoseconds, truncated to microseconds.
609  * >=3 = seconds and nanoseconds, maximum precision.
610  */
611 enum { TSP_SEC, TSP_HZ, TSP_USEC, TSP_NSEC };
612 
613 static int timestamp_precision = TSP_SEC;
614 SYSCTL_INT(_vfs, OID_AUTO, timestamp_precision, CTLFLAG_RW,
615     &timestamp_precision, 0, "File timestamp precision (0: seconds, "
616     "1: sec + ns accurate to 1/HZ, 2: sec + ns truncated to ms, "
617     "3+: sec + ns (max. precision))");
618 
619 /*
620  * Get a current timestamp.
621  */
622 void
623 vfs_timestamp(struct timespec *tsp)
624 {
625 	struct timeval tv;
626 
627 	switch (timestamp_precision) {
628 	case TSP_SEC:
629 		tsp->tv_sec = time_second;
630 		tsp->tv_nsec = 0;
631 		break;
632 	case TSP_HZ:
633 		getnanotime(tsp);
634 		break;
635 	case TSP_USEC:
636 		microtime(&tv);
637 		TIMEVAL_TO_TIMESPEC(&tv, tsp);
638 		break;
639 	case TSP_NSEC:
640 	default:
641 		nanotime(tsp);
642 		break;
643 	}
644 }
645 
646 /*
647  * Set vnode attributes to VNOVAL
648  */
649 void
650 vattr_null(struct vattr *vap)
651 {
652 
653 	vap->va_type = VNON;
654 	vap->va_size = VNOVAL;
655 	vap->va_bytes = VNOVAL;
656 	vap->va_mode = VNOVAL;
657 	vap->va_nlink = VNOVAL;
658 	vap->va_uid = VNOVAL;
659 	vap->va_gid = VNOVAL;
660 	vap->va_fsid = VNOVAL;
661 	vap->va_fileid = VNOVAL;
662 	vap->va_blocksize = VNOVAL;
663 	vap->va_rdev = VNOVAL;
664 	vap->va_atime.tv_sec = VNOVAL;
665 	vap->va_atime.tv_nsec = VNOVAL;
666 	vap->va_mtime.tv_sec = VNOVAL;
667 	vap->va_mtime.tv_nsec = VNOVAL;
668 	vap->va_ctime.tv_sec = VNOVAL;
669 	vap->va_ctime.tv_nsec = VNOVAL;
670 	vap->va_birthtime.tv_sec = VNOVAL;
671 	vap->va_birthtime.tv_nsec = VNOVAL;
672 	vap->va_flags = VNOVAL;
673 	vap->va_gen = VNOVAL;
674 	vap->va_vaflags = 0;
675 }
676 
677 /*
678  * This routine is called when we have too many vnodes.  It attempts
679  * to free <count> vnodes and will potentially free vnodes that still
680  * have VM backing store (VM backing store is typically the cause
681  * of a vnode blowout so we want to do this).  Therefore, this operation
682  * is not considered cheap.
683  *
684  * A number of conditions may prevent a vnode from being reclaimed.
685  * the buffer cache may have references on the vnode, a directory
686  * vnode may still have references due to the namei cache representing
687  * underlying files, or the vnode may be in active use.   It is not
688  * desireable to reuse such vnodes.  These conditions may cause the
689  * number of vnodes to reach some minimum value regardless of what
690  * you set kern.maxvnodes to.  Do not set kern.maxvnodes too low.
691  */
692 static int
693 vlrureclaim(struct mount *mp)
694 {
695 	struct vnode *vp;
696 	int done;
697 	int trigger;
698 	int usevnodes;
699 	int count;
700 
701 	/*
702 	 * Calculate the trigger point, don't allow user
703 	 * screwups to blow us up.   This prevents us from
704 	 * recycling vnodes with lots of resident pages.  We
705 	 * aren't trying to free memory, we are trying to
706 	 * free vnodes.
707 	 */
708 	usevnodes = desiredvnodes;
709 	if (usevnodes <= 0)
710 		usevnodes = 1;
711 	trigger = vm_cnt.v_page_count * 2 / usevnodes;
712 	done = 0;
713 	vn_start_write(NULL, &mp, V_WAIT);
714 	MNT_ILOCK(mp);
715 	count = mp->mnt_nvnodelistsize / 10 + 1;
716 	while (count != 0) {
717 		vp = TAILQ_FIRST(&mp->mnt_nvnodelist);
718 		while (vp != NULL && vp->v_type == VMARKER)
719 			vp = TAILQ_NEXT(vp, v_nmntvnodes);
720 		if (vp == NULL)
721 			break;
722 		TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
723 		TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
724 		--count;
725 		if (!VI_TRYLOCK(vp))
726 			goto next_iter;
727 		/*
728 		 * If it's been deconstructed already, it's still
729 		 * referenced, or it exceeds the trigger, skip it.
730 		 */
731 		if (vp->v_usecount ||
732 		    (!vlru_allow_cache_src &&
733 			!LIST_EMPTY(&(vp)->v_cache_src)) ||
734 		    (vp->v_iflag & VI_DOOMED) != 0 || (vp->v_object != NULL &&
735 		    vp->v_object->resident_page_count > trigger)) {
736 			VI_UNLOCK(vp);
737 			goto next_iter;
738 		}
739 		MNT_IUNLOCK(mp);
740 		vholdl(vp);
741 		if (VOP_LOCK(vp, LK_INTERLOCK|LK_EXCLUSIVE|LK_NOWAIT)) {
742 			vdrop(vp);
743 			goto next_iter_mntunlocked;
744 		}
745 		VI_LOCK(vp);
746 		/*
747 		 * v_usecount may have been bumped after VOP_LOCK() dropped
748 		 * the vnode interlock and before it was locked again.
749 		 *
750 		 * It is not necessary to recheck VI_DOOMED because it can
751 		 * only be set by another thread that holds both the vnode
752 		 * lock and vnode interlock.  If another thread has the
753 		 * vnode lock before we get to VOP_LOCK() and obtains the
754 		 * vnode interlock after VOP_LOCK() drops the vnode
755 		 * interlock, the other thread will be unable to drop the
756 		 * vnode lock before our VOP_LOCK() call fails.
757 		 */
758 		if (vp->v_usecount ||
759 		    (!vlru_allow_cache_src &&
760 			!LIST_EMPTY(&(vp)->v_cache_src)) ||
761 		    (vp->v_object != NULL &&
762 		    vp->v_object->resident_page_count > trigger)) {
763 			VOP_UNLOCK(vp, LK_INTERLOCK);
764 			vdrop(vp);
765 			goto next_iter_mntunlocked;
766 		}
767 		KASSERT((vp->v_iflag & VI_DOOMED) == 0,
768 		    ("VI_DOOMED unexpectedly detected in vlrureclaim()"));
769 		vgonel(vp);
770 		VOP_UNLOCK(vp, 0);
771 		vdropl(vp);
772 		done++;
773 next_iter_mntunlocked:
774 		if (!should_yield())
775 			goto relock_mnt;
776 		goto yield;
777 next_iter:
778 		if (!should_yield())
779 			continue;
780 		MNT_IUNLOCK(mp);
781 yield:
782 		kern_yield(PRI_USER);
783 relock_mnt:
784 		MNT_ILOCK(mp);
785 	}
786 	MNT_IUNLOCK(mp);
787 	vn_finished_write(mp);
788 	return done;
789 }
790 
791 /*
792  * Attempt to keep the free list at wantfreevnodes length.
793  */
794 static void
795 vnlru_free(int count)
796 {
797 	struct vnode *vp;
798 
799 	mtx_assert(&vnode_free_list_mtx, MA_OWNED);
800 	for (; count > 0; count--) {
801 		vp = TAILQ_FIRST(&vnode_free_list);
802 		/*
803 		 * The list can be modified while the free_list_mtx
804 		 * has been dropped and vp could be NULL here.
805 		 */
806 		if (!vp)
807 			break;
808 		VNASSERT(vp->v_op != NULL, vp,
809 		    ("vnlru_free: vnode already reclaimed."));
810 		KASSERT((vp->v_iflag & VI_FREE) != 0,
811 		    ("Removing vnode not on freelist"));
812 		KASSERT((vp->v_iflag & VI_ACTIVE) == 0,
813 		    ("Mangling active vnode"));
814 		TAILQ_REMOVE(&vnode_free_list, vp, v_actfreelist);
815 		/*
816 		 * Don't recycle if we can't get the interlock.
817 		 */
818 		if (!VI_TRYLOCK(vp)) {
819 			TAILQ_INSERT_TAIL(&vnode_free_list, vp, v_actfreelist);
820 			continue;
821 		}
822 		VNASSERT(VCANRECYCLE(vp), vp,
823 		    ("vp inconsistent on freelist"));
824 		freevnodes--;
825 		vp->v_iflag &= ~VI_FREE;
826 		vholdl(vp);
827 		mtx_unlock(&vnode_free_list_mtx);
828 		VI_UNLOCK(vp);
829 		vtryrecycle(vp);
830 		/*
831 		 * If the recycled succeeded this vdrop will actually free
832 		 * the vnode.  If not it will simply place it back on
833 		 * the free list.
834 		 */
835 		vdrop(vp);
836 		mtx_lock(&vnode_free_list_mtx);
837 	}
838 }
839 /*
840  * Attempt to recycle vnodes in a context that is always safe to block.
841  * Calling vlrurecycle() from the bowels of filesystem code has some
842  * interesting deadlock problems.
843  */
844 static struct proc *vnlruproc;
845 static int vnlruproc_sig;
846 
847 static void
848 vnlru_proc(void)
849 {
850 	struct mount *mp, *nmp;
851 	int done;
852 	struct proc *p = vnlruproc;
853 
854 	EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, p,
855 	    SHUTDOWN_PRI_FIRST);
856 
857 	for (;;) {
858 		kproc_suspend_check(p);
859 		mtx_lock(&vnode_free_list_mtx);
860 		if (freevnodes > wantfreevnodes)
861 			vnlru_free(freevnodes - wantfreevnodes);
862 		if (numvnodes <= desiredvnodes * 9 / 10) {
863 			vnlruproc_sig = 0;
864 			wakeup(&vnlruproc_sig);
865 			msleep(vnlruproc, &vnode_free_list_mtx,
866 			    PVFS|PDROP, "vlruwt", hz);
867 			continue;
868 		}
869 		mtx_unlock(&vnode_free_list_mtx);
870 		done = 0;
871 		mtx_lock(&mountlist_mtx);
872 		for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp) {
873 			if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK)) {
874 				nmp = TAILQ_NEXT(mp, mnt_list);
875 				continue;
876 			}
877 			done += vlrureclaim(mp);
878 			mtx_lock(&mountlist_mtx);
879 			nmp = TAILQ_NEXT(mp, mnt_list);
880 			vfs_unbusy(mp);
881 		}
882 		mtx_unlock(&mountlist_mtx);
883 		if (done == 0) {
884 #if 0
885 			/* These messages are temporary debugging aids */
886 			if (vnlru_nowhere < 5)
887 				printf("vnlru process getting nowhere..\n");
888 			else if (vnlru_nowhere == 5)
889 				printf("vnlru process messages stopped.\n");
890 #endif
891 			vnlru_nowhere++;
892 			tsleep(vnlruproc, PPAUSE, "vlrup", hz * 3);
893 		} else
894 			kern_yield(PRI_USER);
895 	}
896 }
897 
898 static struct kproc_desc vnlru_kp = {
899 	"vnlru",
900 	vnlru_proc,
901 	&vnlruproc
902 };
903 SYSINIT(vnlru, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start,
904     &vnlru_kp);
905 
906 /*
907  * Routines having to do with the management of the vnode table.
908  */
909 
910 /*
911  * Try to recycle a freed vnode.  We abort if anyone picks up a reference
912  * before we actually vgone().  This function must be called with the vnode
913  * held to prevent the vnode from being returned to the free list midway
914  * through vgone().
915  */
916 static int
917 vtryrecycle(struct vnode *vp)
918 {
919 	struct mount *vnmp;
920 
921 	CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
922 	VNASSERT(vp->v_holdcnt, vp,
923 	    ("vtryrecycle: Recycling vp %p without a reference.", vp));
924 	/*
925 	 * This vnode may found and locked via some other list, if so we
926 	 * can't recycle it yet.
927 	 */
928 	if (VOP_LOCK(vp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
929 		CTR2(KTR_VFS,
930 		    "%s: impossible to recycle, vp %p lock is already held",
931 		    __func__, vp);
932 		return (EWOULDBLOCK);
933 	}
934 	/*
935 	 * Don't recycle if its filesystem is being suspended.
936 	 */
937 	if (vn_start_write(vp, &vnmp, V_NOWAIT) != 0) {
938 		VOP_UNLOCK(vp, 0);
939 		CTR2(KTR_VFS,
940 		    "%s: impossible to recycle, cannot start the write for %p",
941 		    __func__, vp);
942 		return (EBUSY);
943 	}
944 	/*
945 	 * If we got this far, we need to acquire the interlock and see if
946 	 * anyone picked up this vnode from another list.  If not, we will
947 	 * mark it with DOOMED via vgonel() so that anyone who does find it
948 	 * will skip over it.
949 	 */
950 	VI_LOCK(vp);
951 	if (vp->v_usecount) {
952 		VOP_UNLOCK(vp, LK_INTERLOCK);
953 		vn_finished_write(vnmp);
954 		CTR2(KTR_VFS,
955 		    "%s: impossible to recycle, %p is already referenced",
956 		    __func__, vp);
957 		return (EBUSY);
958 	}
959 	if ((vp->v_iflag & VI_DOOMED) == 0)
960 		vgonel(vp);
961 	VOP_UNLOCK(vp, LK_INTERLOCK);
962 	vn_finished_write(vnmp);
963 	return (0);
964 }
965 
966 /*
967  * Wait for available vnodes.
968  */
969 static int
970 getnewvnode_wait(int suspended)
971 {
972 
973 	mtx_assert(&vnode_free_list_mtx, MA_OWNED);
974 	if (numvnodes > desiredvnodes) {
975 		if (suspended) {
976 			/*
977 			 * File system is beeing suspended, we cannot risk a
978 			 * deadlock here, so allocate new vnode anyway.
979 			 */
980 			if (freevnodes > wantfreevnodes)
981 				vnlru_free(freevnodes - wantfreevnodes);
982 			return (0);
983 		}
984 		if (vnlruproc_sig == 0) {
985 			vnlruproc_sig = 1;	/* avoid unnecessary wakeups */
986 			wakeup(vnlruproc);
987 		}
988 		msleep(&vnlruproc_sig, &vnode_free_list_mtx, PVFS,
989 		    "vlruwk", hz);
990 	}
991 	return (numvnodes > desiredvnodes ? ENFILE : 0);
992 }
993 
994 void
995 getnewvnode_reserve(u_int count)
996 {
997 	struct thread *td;
998 	long num;
999 
1000 	td = curthread;
1001 	/* First try to be quick and racy. */
1002 	if (numvnodes + count <= desiredvnodes) {
1003 		num = atomic_fetchadd_long(&numvnodes, count);
1004 		if (num + count <= desiredvnodes) {
1005 			td->td_vp_reserv += count;
1006 			return;
1007 		} else
1008 			atomic_subtract_long(&numvnodes, count);
1009 	}
1010 
1011 	mtx_lock(&vnode_free_list_mtx);
1012 	while (count > 0) {
1013 		if (getnewvnode_wait(0) == 0) {
1014 			count--;
1015 			td->td_vp_reserv++;
1016 			atomic_add_long(&numvnodes, 1);
1017 		}
1018 	}
1019 	mtx_unlock(&vnode_free_list_mtx);
1020 }
1021 
1022 void
1023 getnewvnode_drop_reserve(void)
1024 {
1025 	struct thread *td;
1026 
1027 	td = curthread;
1028 	atomic_subtract_long(&numvnodes, td->td_vp_reserv);
1029 	td->td_vp_reserv = 0;
1030 }
1031 
1032 /*
1033  * Return the next vnode from the free list.
1034  */
1035 int
1036 getnewvnode(const char *tag, struct mount *mp, struct vop_vector *vops,
1037     struct vnode **vpp)
1038 {
1039 	struct vnode *vp;
1040 	struct bufobj *bo;
1041 	struct thread *td;
1042 	int error;
1043 
1044 	CTR3(KTR_VFS, "%s: mp %p with tag %s", __func__, mp, tag);
1045 	vp = NULL;
1046 	td = curthread;
1047 	if (td->td_vp_reserv > 0) {
1048 		td->td_vp_reserv -= 1;
1049 		goto alloc;
1050 	}
1051 	mtx_lock(&vnode_free_list_mtx);
1052 	/*
1053 	 * Lend our context to reclaim vnodes if they've exceeded the max.
1054 	 */
1055 	if (freevnodes > wantfreevnodes)
1056 		vnlru_free(1);
1057 	error = getnewvnode_wait(mp != NULL && (mp->mnt_kern_flag &
1058 	    MNTK_SUSPEND));
1059 #if 0	/* XXX Not all VFS_VGET/ffs_vget callers check returns. */
1060 	if (error != 0) {
1061 		mtx_unlock(&vnode_free_list_mtx);
1062 		return (error);
1063 	}
1064 #endif
1065 	atomic_add_long(&numvnodes, 1);
1066 	mtx_unlock(&vnode_free_list_mtx);
1067 alloc:
1068 	vp = (struct vnode *) uma_zalloc(vnode_zone, M_WAITOK|M_ZERO);
1069 	/*
1070 	 * Setup locks.
1071 	 */
1072 	vp->v_vnlock = &vp->v_lock;
1073 	mtx_init(&vp->v_interlock, "vnode interlock", NULL, MTX_DEF);
1074 	/*
1075 	 * By default, don't allow shared locks unless filesystems
1076 	 * opt-in.
1077 	 */
1078 	lockinit(vp->v_vnlock, PVFS, tag, VLKTIMEOUT, LK_NOSHARE | LK_IS_VNODE);
1079 	/*
1080 	 * Initialize bufobj.
1081 	 */
1082 	bo = &vp->v_bufobj;
1083 	bo->__bo_vnode = vp;
1084 	rw_init(BO_LOCKPTR(bo), "bufobj interlock");
1085 	bo->bo_ops = &buf_ops_bio;
1086 	bo->bo_private = vp;
1087 	TAILQ_INIT(&bo->bo_clean.bv_hd);
1088 	TAILQ_INIT(&bo->bo_dirty.bv_hd);
1089 	/*
1090 	 * Initialize namecache.
1091 	 */
1092 	LIST_INIT(&vp->v_cache_src);
1093 	TAILQ_INIT(&vp->v_cache_dst);
1094 	/*
1095 	 * Finalize various vnode identity bits.
1096 	 */
1097 	vp->v_type = VNON;
1098 	vp->v_tag = tag;
1099 	vp->v_op = vops;
1100 	v_incr_usecount(vp);
1101 	vp->v_data = NULL;
1102 #ifdef MAC
1103 	mac_vnode_init(vp);
1104 	if (mp != NULL && (mp->mnt_flag & MNT_MULTILABEL) == 0)
1105 		mac_vnode_associate_singlelabel(mp, vp);
1106 	else if (mp == NULL && vops != &dead_vnodeops)
1107 		printf("NULL mp in getnewvnode()\n");
1108 #endif
1109 	if (mp != NULL) {
1110 		bo->bo_bsize = mp->mnt_stat.f_iosize;
1111 		if ((mp->mnt_kern_flag & MNTK_NOKNOTE) != 0)
1112 			vp->v_vflag |= VV_NOKNOTE;
1113 	}
1114 	rangelock_init(&vp->v_rl);
1115 
1116 	/*
1117 	 * For the filesystems which do not use vfs_hash_insert(),
1118 	 * still initialize v_hash to have vfs_hash_index() useful.
1119 	 * E.g., nullfs uses vfs_hash_index() on the lower vnode for
1120 	 * its own hashing.
1121 	 */
1122 	vp->v_hash = (uintptr_t)vp >> vnsz2log;
1123 
1124 	*vpp = vp;
1125 	return (0);
1126 }
1127 
1128 /*
1129  * Delete from old mount point vnode list, if on one.
1130  */
1131 static void
1132 delmntque(struct vnode *vp)
1133 {
1134 	struct mount *mp;
1135 	int active;
1136 
1137 	mp = vp->v_mount;
1138 	if (mp == NULL)
1139 		return;
1140 	MNT_ILOCK(mp);
1141 	VI_LOCK(vp);
1142 	KASSERT(mp->mnt_activevnodelistsize <= mp->mnt_nvnodelistsize,
1143 	    ("Active vnode list size %d > Vnode list size %d",
1144 	     mp->mnt_activevnodelistsize, mp->mnt_nvnodelistsize));
1145 	active = vp->v_iflag & VI_ACTIVE;
1146 	vp->v_iflag &= ~VI_ACTIVE;
1147 	if (active) {
1148 		mtx_lock(&vnode_free_list_mtx);
1149 		TAILQ_REMOVE(&mp->mnt_activevnodelist, vp, v_actfreelist);
1150 		mp->mnt_activevnodelistsize--;
1151 		mtx_unlock(&vnode_free_list_mtx);
1152 	}
1153 	vp->v_mount = NULL;
1154 	VI_UNLOCK(vp);
1155 	VNASSERT(mp->mnt_nvnodelistsize > 0, vp,
1156 		("bad mount point vnode list size"));
1157 	TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1158 	mp->mnt_nvnodelistsize--;
1159 	MNT_REL(mp);
1160 	MNT_IUNLOCK(mp);
1161 }
1162 
1163 static void
1164 insmntque_stddtr(struct vnode *vp, void *dtr_arg)
1165 {
1166 
1167 	vp->v_data = NULL;
1168 	vp->v_op = &dead_vnodeops;
1169 	vgone(vp);
1170 	vput(vp);
1171 }
1172 
1173 /*
1174  * Insert into list of vnodes for the new mount point, if available.
1175  */
1176 int
1177 insmntque1(struct vnode *vp, struct mount *mp,
1178 	void (*dtr)(struct vnode *, void *), void *dtr_arg)
1179 {
1180 
1181 	KASSERT(vp->v_mount == NULL,
1182 		("insmntque: vnode already on per mount vnode list"));
1183 	VNASSERT(mp != NULL, vp, ("Don't call insmntque(foo, NULL)"));
1184 	ASSERT_VOP_ELOCKED(vp, "insmntque: non-locked vp");
1185 
1186 	/*
1187 	 * We acquire the vnode interlock early to ensure that the
1188 	 * vnode cannot be recycled by another process releasing a
1189 	 * holdcnt on it before we get it on both the vnode list
1190 	 * and the active vnode list. The mount mutex protects only
1191 	 * manipulation of the vnode list and the vnode freelist
1192 	 * mutex protects only manipulation of the active vnode list.
1193 	 * Hence the need to hold the vnode interlock throughout.
1194 	 */
1195 	MNT_ILOCK(mp);
1196 	VI_LOCK(vp);
1197 	if (((mp->mnt_kern_flag & MNTK_NOINSMNTQ) != 0 &&
1198 	    ((mp->mnt_kern_flag & MNTK_UNMOUNTF) != 0 ||
1199 	    mp->mnt_nvnodelistsize == 0)) &&
1200 	    (vp->v_vflag & VV_FORCEINSMQ) == 0) {
1201 		VI_UNLOCK(vp);
1202 		MNT_IUNLOCK(mp);
1203 		if (dtr != NULL)
1204 			dtr(vp, dtr_arg);
1205 		return (EBUSY);
1206 	}
1207 	vp->v_mount = mp;
1208 	MNT_REF(mp);
1209 	TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1210 	VNASSERT(mp->mnt_nvnodelistsize >= 0, vp,
1211 		("neg mount point vnode list size"));
1212 	mp->mnt_nvnodelistsize++;
1213 	KASSERT((vp->v_iflag & VI_ACTIVE) == 0,
1214 	    ("Activating already active vnode"));
1215 	vp->v_iflag |= VI_ACTIVE;
1216 	mtx_lock(&vnode_free_list_mtx);
1217 	TAILQ_INSERT_HEAD(&mp->mnt_activevnodelist, vp, v_actfreelist);
1218 	mp->mnt_activevnodelistsize++;
1219 	mtx_unlock(&vnode_free_list_mtx);
1220 	VI_UNLOCK(vp);
1221 	MNT_IUNLOCK(mp);
1222 	return (0);
1223 }
1224 
1225 int
1226 insmntque(struct vnode *vp, struct mount *mp)
1227 {
1228 
1229 	return (insmntque1(vp, mp, insmntque_stddtr, NULL));
1230 }
1231 
1232 /*
1233  * Flush out and invalidate all buffers associated with a bufobj
1234  * Called with the underlying object locked.
1235  */
1236 int
1237 bufobj_invalbuf(struct bufobj *bo, int flags, int slpflag, int slptimeo)
1238 {
1239 	int error;
1240 
1241 	BO_LOCK(bo);
1242 	if (flags & V_SAVE) {
1243 		error = bufobj_wwait(bo, slpflag, slptimeo);
1244 		if (error) {
1245 			BO_UNLOCK(bo);
1246 			return (error);
1247 		}
1248 		if (bo->bo_dirty.bv_cnt > 0) {
1249 			BO_UNLOCK(bo);
1250 			if ((error = BO_SYNC(bo, MNT_WAIT)) != 0)
1251 				return (error);
1252 			/*
1253 			 * XXX We could save a lock/unlock if this was only
1254 			 * enabled under INVARIANTS
1255 			 */
1256 			BO_LOCK(bo);
1257 			if (bo->bo_numoutput > 0 || bo->bo_dirty.bv_cnt > 0)
1258 				panic("vinvalbuf: dirty bufs");
1259 		}
1260 	}
1261 	/*
1262 	 * If you alter this loop please notice that interlock is dropped and
1263 	 * reacquired in flushbuflist.  Special care is needed to ensure that
1264 	 * no race conditions occur from this.
1265 	 */
1266 	do {
1267 		error = flushbuflist(&bo->bo_clean,
1268 		    flags, bo, slpflag, slptimeo);
1269 		if (error == 0 && !(flags & V_CLEANONLY))
1270 			error = flushbuflist(&bo->bo_dirty,
1271 			    flags, bo, slpflag, slptimeo);
1272 		if (error != 0 && error != EAGAIN) {
1273 			BO_UNLOCK(bo);
1274 			return (error);
1275 		}
1276 	} while (error != 0);
1277 
1278 	/*
1279 	 * Wait for I/O to complete.  XXX needs cleaning up.  The vnode can
1280 	 * have write I/O in-progress but if there is a VM object then the
1281 	 * VM object can also have read-I/O in-progress.
1282 	 */
1283 	do {
1284 		bufobj_wwait(bo, 0, 0);
1285 		BO_UNLOCK(bo);
1286 		if (bo->bo_object != NULL) {
1287 			VM_OBJECT_WLOCK(bo->bo_object);
1288 			vm_object_pip_wait(bo->bo_object, "bovlbx");
1289 			VM_OBJECT_WUNLOCK(bo->bo_object);
1290 		}
1291 		BO_LOCK(bo);
1292 	} while (bo->bo_numoutput > 0);
1293 	BO_UNLOCK(bo);
1294 
1295 	/*
1296 	 * Destroy the copy in the VM cache, too.
1297 	 */
1298 	if (bo->bo_object != NULL &&
1299 	    (flags & (V_ALT | V_NORMAL | V_CLEANONLY)) == 0) {
1300 		VM_OBJECT_WLOCK(bo->bo_object);
1301 		vm_object_page_remove(bo->bo_object, 0, 0, (flags & V_SAVE) ?
1302 		    OBJPR_CLEANONLY : 0);
1303 		VM_OBJECT_WUNLOCK(bo->bo_object);
1304 	}
1305 
1306 #ifdef INVARIANTS
1307 	BO_LOCK(bo);
1308 	if ((flags & (V_ALT | V_NORMAL | V_CLEANONLY)) == 0 &&
1309 	    (bo->bo_dirty.bv_cnt > 0 || bo->bo_clean.bv_cnt > 0))
1310 		panic("vinvalbuf: flush failed");
1311 	BO_UNLOCK(bo);
1312 #endif
1313 	return (0);
1314 }
1315 
1316 /*
1317  * Flush out and invalidate all buffers associated with a vnode.
1318  * Called with the underlying object locked.
1319  */
1320 int
1321 vinvalbuf(struct vnode *vp, int flags, int slpflag, int slptimeo)
1322 {
1323 
1324 	CTR3(KTR_VFS, "%s: vp %p with flags %d", __func__, vp, flags);
1325 	ASSERT_VOP_LOCKED(vp, "vinvalbuf");
1326 	if (vp->v_object != NULL && vp->v_object->handle != vp)
1327 		return (0);
1328 	return (bufobj_invalbuf(&vp->v_bufobj, flags, slpflag, slptimeo));
1329 }
1330 
1331 /*
1332  * Flush out buffers on the specified list.
1333  *
1334  */
1335 static int
1336 flushbuflist(struct bufv *bufv, int flags, struct bufobj *bo, int slpflag,
1337     int slptimeo)
1338 {
1339 	struct buf *bp, *nbp;
1340 	int retval, error;
1341 	daddr_t lblkno;
1342 	b_xflags_t xflags;
1343 
1344 	ASSERT_BO_WLOCKED(bo);
1345 
1346 	retval = 0;
1347 	TAILQ_FOREACH_SAFE(bp, &bufv->bv_hd, b_bobufs, nbp) {
1348 		if (((flags & V_NORMAL) && (bp->b_xflags & BX_ALTDATA)) ||
1349 		    ((flags & V_ALT) && (bp->b_xflags & BX_ALTDATA) == 0)) {
1350 			continue;
1351 		}
1352 		lblkno = 0;
1353 		xflags = 0;
1354 		if (nbp != NULL) {
1355 			lblkno = nbp->b_lblkno;
1356 			xflags = nbp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN);
1357 		}
1358 		retval = EAGAIN;
1359 		error = BUF_TIMELOCK(bp,
1360 		    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, BO_LOCKPTR(bo),
1361 		    "flushbuf", slpflag, slptimeo);
1362 		if (error) {
1363 			BO_LOCK(bo);
1364 			return (error != ENOLCK ? error : EAGAIN);
1365 		}
1366 		KASSERT(bp->b_bufobj == bo,
1367 		    ("bp %p wrong b_bufobj %p should be %p",
1368 		    bp, bp->b_bufobj, bo));
1369 		if (bp->b_bufobj != bo) {	/* XXX: necessary ? */
1370 			BUF_UNLOCK(bp);
1371 			BO_LOCK(bo);
1372 			return (EAGAIN);
1373 		}
1374 		/*
1375 		 * XXX Since there are no node locks for NFS, I
1376 		 * believe there is a slight chance that a delayed
1377 		 * write will occur while sleeping just above, so
1378 		 * check for it.
1379 		 */
1380 		if (((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI) &&
1381 		    (flags & V_SAVE)) {
1382 			bremfree(bp);
1383 			bp->b_flags |= B_ASYNC;
1384 			bwrite(bp);
1385 			BO_LOCK(bo);
1386 			return (EAGAIN);	/* XXX: why not loop ? */
1387 		}
1388 		bremfree(bp);
1389 		bp->b_flags |= (B_INVAL | B_RELBUF);
1390 		bp->b_flags &= ~B_ASYNC;
1391 		brelse(bp);
1392 		BO_LOCK(bo);
1393 		if (nbp != NULL &&
1394 		    (nbp->b_bufobj != bo ||
1395 		     nbp->b_lblkno != lblkno ||
1396 		     (nbp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN)) != xflags))
1397 			break;			/* nbp invalid */
1398 	}
1399 	return (retval);
1400 }
1401 
1402 /*
1403  * Truncate a file's buffer and pages to a specified length.  This
1404  * is in lieu of the old vinvalbuf mechanism, which performed unneeded
1405  * sync activity.
1406  */
1407 int
1408 vtruncbuf(struct vnode *vp, struct ucred *cred, off_t length, int blksize)
1409 {
1410 	struct buf *bp, *nbp;
1411 	int anyfreed;
1412 	int trunclbn;
1413 	struct bufobj *bo;
1414 
1415 	CTR5(KTR_VFS, "%s: vp %p with cred %p and block %d:%ju", __func__,
1416 	    vp, cred, blksize, (uintmax_t)length);
1417 
1418 	/*
1419 	 * Round up to the *next* lbn.
1420 	 */
1421 	trunclbn = (length + blksize - 1) / blksize;
1422 
1423 	ASSERT_VOP_LOCKED(vp, "vtruncbuf");
1424 restart:
1425 	bo = &vp->v_bufobj;
1426 	BO_LOCK(bo);
1427 	anyfreed = 1;
1428 	for (;anyfreed;) {
1429 		anyfreed = 0;
1430 		TAILQ_FOREACH_SAFE(bp, &bo->bo_clean.bv_hd, b_bobufs, nbp) {
1431 			if (bp->b_lblkno < trunclbn)
1432 				continue;
1433 			if (BUF_LOCK(bp,
1434 			    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
1435 			    BO_LOCKPTR(bo)) == ENOLCK)
1436 				goto restart;
1437 
1438 			bremfree(bp);
1439 			bp->b_flags |= (B_INVAL | B_RELBUF);
1440 			bp->b_flags &= ~B_ASYNC;
1441 			brelse(bp);
1442 			anyfreed = 1;
1443 
1444 			BO_LOCK(bo);
1445 			if (nbp != NULL &&
1446 			    (((nbp->b_xflags & BX_VNCLEAN) == 0) ||
1447 			    (nbp->b_vp != vp) ||
1448 			    (nbp->b_flags & B_DELWRI))) {
1449 				BO_UNLOCK(bo);
1450 				goto restart;
1451 			}
1452 		}
1453 
1454 		TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
1455 			if (bp->b_lblkno < trunclbn)
1456 				continue;
1457 			if (BUF_LOCK(bp,
1458 			    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
1459 			    BO_LOCKPTR(bo)) == ENOLCK)
1460 				goto restart;
1461 			bremfree(bp);
1462 			bp->b_flags |= (B_INVAL | B_RELBUF);
1463 			bp->b_flags &= ~B_ASYNC;
1464 			brelse(bp);
1465 			anyfreed = 1;
1466 
1467 			BO_LOCK(bo);
1468 			if (nbp != NULL &&
1469 			    (((nbp->b_xflags & BX_VNDIRTY) == 0) ||
1470 			    (nbp->b_vp != vp) ||
1471 			    (nbp->b_flags & B_DELWRI) == 0)) {
1472 				BO_UNLOCK(bo);
1473 				goto restart;
1474 			}
1475 		}
1476 	}
1477 
1478 	if (length > 0) {
1479 restartsync:
1480 		TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
1481 			if (bp->b_lblkno > 0)
1482 				continue;
1483 			/*
1484 			 * Since we hold the vnode lock this should only
1485 			 * fail if we're racing with the buf daemon.
1486 			 */
1487 			if (BUF_LOCK(bp,
1488 			    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
1489 			    BO_LOCKPTR(bo)) == ENOLCK) {
1490 				goto restart;
1491 			}
1492 			VNASSERT((bp->b_flags & B_DELWRI), vp,
1493 			    ("buf(%p) on dirty queue without DELWRI", bp));
1494 
1495 			bremfree(bp);
1496 			bawrite(bp);
1497 			BO_LOCK(bo);
1498 			goto restartsync;
1499 		}
1500 	}
1501 
1502 	bufobj_wwait(bo, 0, 0);
1503 	BO_UNLOCK(bo);
1504 	vnode_pager_setsize(vp, length);
1505 
1506 	return (0);
1507 }
1508 
1509 static void
1510 buf_vlist_remove(struct buf *bp)
1511 {
1512 	struct bufv *bv;
1513 
1514 	KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1515 	ASSERT_BO_WLOCKED(bp->b_bufobj);
1516 	KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) !=
1517 	    (BX_VNDIRTY|BX_VNCLEAN),
1518 	    ("buf_vlist_remove: Buf %p is on two lists", bp));
1519 	if (bp->b_xflags & BX_VNDIRTY)
1520 		bv = &bp->b_bufobj->bo_dirty;
1521 	else
1522 		bv = &bp->b_bufobj->bo_clean;
1523 	BUF_PCTRIE_REMOVE(&bv->bv_root, bp->b_lblkno);
1524 	TAILQ_REMOVE(&bv->bv_hd, bp, b_bobufs);
1525 	bv->bv_cnt--;
1526 	bp->b_xflags &= ~(BX_VNDIRTY | BX_VNCLEAN);
1527 }
1528 
1529 /*
1530  * Add the buffer to the sorted clean or dirty block list.
1531  *
1532  * NOTE: xflags is passed as a constant, optimizing this inline function!
1533  */
1534 static void
1535 buf_vlist_add(struct buf *bp, struct bufobj *bo, b_xflags_t xflags)
1536 {
1537 	struct bufv *bv;
1538 	struct buf *n;
1539 	int error;
1540 
1541 	ASSERT_BO_WLOCKED(bo);
1542 	KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0,
1543 	    ("buf_vlist_add: Buf %p has existing xflags %d", bp, bp->b_xflags));
1544 	bp->b_xflags |= xflags;
1545 	if (xflags & BX_VNDIRTY)
1546 		bv = &bo->bo_dirty;
1547 	else
1548 		bv = &bo->bo_clean;
1549 
1550 	/*
1551 	 * Keep the list ordered.  Optimize empty list insertion.  Assume
1552 	 * we tend to grow at the tail so lookup_le should usually be cheaper
1553 	 * than _ge.
1554 	 */
1555 	if (bv->bv_cnt == 0 ||
1556 	    bp->b_lblkno > TAILQ_LAST(&bv->bv_hd, buflists)->b_lblkno)
1557 		TAILQ_INSERT_TAIL(&bv->bv_hd, bp, b_bobufs);
1558 	else if ((n = BUF_PCTRIE_LOOKUP_LE(&bv->bv_root, bp->b_lblkno)) == NULL)
1559 		TAILQ_INSERT_HEAD(&bv->bv_hd, bp, b_bobufs);
1560 	else
1561 		TAILQ_INSERT_AFTER(&bv->bv_hd, n, bp, b_bobufs);
1562 	error = BUF_PCTRIE_INSERT(&bv->bv_root, bp);
1563 	if (error)
1564 		panic("buf_vlist_add:  Preallocated nodes insufficient.");
1565 	bv->bv_cnt++;
1566 }
1567 
1568 /*
1569  * Lookup a buffer using the splay tree.  Note that we specifically avoid
1570  * shadow buffers used in background bitmap writes.
1571  *
1572  * This code isn't quite efficient as it could be because we are maintaining
1573  * two sorted lists and do not know which list the block resides in.
1574  *
1575  * During a "make buildworld" the desired buffer is found at one of
1576  * the roots more than 60% of the time.  Thus, checking both roots
1577  * before performing either splay eliminates unnecessary splays on the
1578  * first tree splayed.
1579  */
1580 struct buf *
1581 gbincore(struct bufobj *bo, daddr_t lblkno)
1582 {
1583 	struct buf *bp;
1584 
1585 	ASSERT_BO_LOCKED(bo);
1586 	bp = BUF_PCTRIE_LOOKUP(&bo->bo_clean.bv_root, lblkno);
1587 	if (bp != NULL)
1588 		return (bp);
1589 	return BUF_PCTRIE_LOOKUP(&bo->bo_dirty.bv_root, lblkno);
1590 }
1591 
1592 /*
1593  * Associate a buffer with a vnode.
1594  */
1595 void
1596 bgetvp(struct vnode *vp, struct buf *bp)
1597 {
1598 	struct bufobj *bo;
1599 
1600 	bo = &vp->v_bufobj;
1601 	ASSERT_BO_WLOCKED(bo);
1602 	VNASSERT(bp->b_vp == NULL, bp->b_vp, ("bgetvp: not free"));
1603 
1604 	CTR3(KTR_BUF, "bgetvp(%p) vp %p flags %X", bp, vp, bp->b_flags);
1605 	VNASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0, vp,
1606 	    ("bgetvp: bp already attached! %p", bp));
1607 
1608 	vhold(vp);
1609 	bp->b_vp = vp;
1610 	bp->b_bufobj = bo;
1611 	/*
1612 	 * Insert onto list for new vnode.
1613 	 */
1614 	buf_vlist_add(bp, bo, BX_VNCLEAN);
1615 }
1616 
1617 /*
1618  * Disassociate a buffer from a vnode.
1619  */
1620 void
1621 brelvp(struct buf *bp)
1622 {
1623 	struct bufobj *bo;
1624 	struct vnode *vp;
1625 
1626 	CTR3(KTR_BUF, "brelvp(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1627 	KASSERT(bp->b_vp != NULL, ("brelvp: NULL"));
1628 
1629 	/*
1630 	 * Delete from old vnode list, if on one.
1631 	 */
1632 	vp = bp->b_vp;		/* XXX */
1633 	bo = bp->b_bufobj;
1634 	BO_LOCK(bo);
1635 	if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
1636 		buf_vlist_remove(bp);
1637 	else
1638 		panic("brelvp: Buffer %p not on queue.", bp);
1639 	if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
1640 		bo->bo_flag &= ~BO_ONWORKLST;
1641 		mtx_lock(&sync_mtx);
1642 		LIST_REMOVE(bo, bo_synclist);
1643 		syncer_worklist_len--;
1644 		mtx_unlock(&sync_mtx);
1645 	}
1646 	bp->b_vp = NULL;
1647 	bp->b_bufobj = NULL;
1648 	BO_UNLOCK(bo);
1649 	vdrop(vp);
1650 }
1651 
1652 /*
1653  * Add an item to the syncer work queue.
1654  */
1655 static void
1656 vn_syncer_add_to_worklist(struct bufobj *bo, int delay)
1657 {
1658 	int slot;
1659 
1660 	ASSERT_BO_WLOCKED(bo);
1661 
1662 	mtx_lock(&sync_mtx);
1663 	if (bo->bo_flag & BO_ONWORKLST)
1664 		LIST_REMOVE(bo, bo_synclist);
1665 	else {
1666 		bo->bo_flag |= BO_ONWORKLST;
1667 		syncer_worklist_len++;
1668 	}
1669 
1670 	if (delay > syncer_maxdelay - 2)
1671 		delay = syncer_maxdelay - 2;
1672 	slot = (syncer_delayno + delay) & syncer_mask;
1673 
1674 	LIST_INSERT_HEAD(&syncer_workitem_pending[slot], bo, bo_synclist);
1675 	mtx_unlock(&sync_mtx);
1676 }
1677 
1678 static int
1679 sysctl_vfs_worklist_len(SYSCTL_HANDLER_ARGS)
1680 {
1681 	int error, len;
1682 
1683 	mtx_lock(&sync_mtx);
1684 	len = syncer_worklist_len - sync_vnode_count;
1685 	mtx_unlock(&sync_mtx);
1686 	error = SYSCTL_OUT(req, &len, sizeof(len));
1687 	return (error);
1688 }
1689 
1690 SYSCTL_PROC(_vfs, OID_AUTO, worklist_len, CTLTYPE_INT | CTLFLAG_RD, NULL, 0,
1691     sysctl_vfs_worklist_len, "I", "Syncer thread worklist length");
1692 
1693 static struct proc *updateproc;
1694 static void sched_sync(void);
1695 static struct kproc_desc up_kp = {
1696 	"syncer",
1697 	sched_sync,
1698 	&updateproc
1699 };
1700 SYSINIT(syncer, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start, &up_kp);
1701 
1702 static int
1703 sync_vnode(struct synclist *slp, struct bufobj **bo, struct thread *td)
1704 {
1705 	struct vnode *vp;
1706 	struct mount *mp;
1707 
1708 	*bo = LIST_FIRST(slp);
1709 	if (*bo == NULL)
1710 		return (0);
1711 	vp = (*bo)->__bo_vnode;	/* XXX */
1712 	if (VOP_ISLOCKED(vp) != 0 || VI_TRYLOCK(vp) == 0)
1713 		return (1);
1714 	/*
1715 	 * We use vhold in case the vnode does not
1716 	 * successfully sync.  vhold prevents the vnode from
1717 	 * going away when we unlock the sync_mtx so that
1718 	 * we can acquire the vnode interlock.
1719 	 */
1720 	vholdl(vp);
1721 	mtx_unlock(&sync_mtx);
1722 	VI_UNLOCK(vp);
1723 	if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
1724 		vdrop(vp);
1725 		mtx_lock(&sync_mtx);
1726 		return (*bo == LIST_FIRST(slp));
1727 	}
1728 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1729 	(void) VOP_FSYNC(vp, MNT_LAZY, td);
1730 	VOP_UNLOCK(vp, 0);
1731 	vn_finished_write(mp);
1732 	BO_LOCK(*bo);
1733 	if (((*bo)->bo_flag & BO_ONWORKLST) != 0) {
1734 		/*
1735 		 * Put us back on the worklist.  The worklist
1736 		 * routine will remove us from our current
1737 		 * position and then add us back in at a later
1738 		 * position.
1739 		 */
1740 		vn_syncer_add_to_worklist(*bo, syncdelay);
1741 	}
1742 	BO_UNLOCK(*bo);
1743 	vdrop(vp);
1744 	mtx_lock(&sync_mtx);
1745 	return (0);
1746 }
1747 
1748 /*
1749  * System filesystem synchronizer daemon.
1750  */
1751 static void
1752 sched_sync(void)
1753 {
1754 	struct synclist *next, *slp;
1755 	struct bufobj *bo;
1756 	long starttime;
1757 	struct thread *td = curthread;
1758 	int last_work_seen;
1759 	int net_worklist_len;
1760 	int syncer_final_iter;
1761 	int first_printf;
1762 	int error;
1763 
1764 	last_work_seen = 0;
1765 	syncer_final_iter = 0;
1766 	first_printf = 1;
1767 	syncer_state = SYNCER_RUNNING;
1768 	starttime = time_uptime;
1769 	td->td_pflags |= TDP_NORUNNINGBUF;
1770 
1771 	EVENTHANDLER_REGISTER(shutdown_pre_sync, syncer_shutdown, td->td_proc,
1772 	    SHUTDOWN_PRI_LAST);
1773 
1774 	mtx_lock(&sync_mtx);
1775 	for (;;) {
1776 		if (syncer_state == SYNCER_FINAL_DELAY &&
1777 		    syncer_final_iter == 0) {
1778 			mtx_unlock(&sync_mtx);
1779 			kproc_suspend_check(td->td_proc);
1780 			mtx_lock(&sync_mtx);
1781 		}
1782 		net_worklist_len = syncer_worklist_len - sync_vnode_count;
1783 		if (syncer_state != SYNCER_RUNNING &&
1784 		    starttime != time_uptime) {
1785 			if (first_printf) {
1786 				printf("\nSyncing disks, vnodes remaining...");
1787 				first_printf = 0;
1788 			}
1789 			printf("%d ", net_worklist_len);
1790 		}
1791 		starttime = time_uptime;
1792 
1793 		/*
1794 		 * Push files whose dirty time has expired.  Be careful
1795 		 * of interrupt race on slp queue.
1796 		 *
1797 		 * Skip over empty worklist slots when shutting down.
1798 		 */
1799 		do {
1800 			slp = &syncer_workitem_pending[syncer_delayno];
1801 			syncer_delayno += 1;
1802 			if (syncer_delayno == syncer_maxdelay)
1803 				syncer_delayno = 0;
1804 			next = &syncer_workitem_pending[syncer_delayno];
1805 			/*
1806 			 * If the worklist has wrapped since the
1807 			 * it was emptied of all but syncer vnodes,
1808 			 * switch to the FINAL_DELAY state and run
1809 			 * for one more second.
1810 			 */
1811 			if (syncer_state == SYNCER_SHUTTING_DOWN &&
1812 			    net_worklist_len == 0 &&
1813 			    last_work_seen == syncer_delayno) {
1814 				syncer_state = SYNCER_FINAL_DELAY;
1815 				syncer_final_iter = SYNCER_SHUTDOWN_SPEEDUP;
1816 			}
1817 		} while (syncer_state != SYNCER_RUNNING && LIST_EMPTY(slp) &&
1818 		    syncer_worklist_len > 0);
1819 
1820 		/*
1821 		 * Keep track of the last time there was anything
1822 		 * on the worklist other than syncer vnodes.
1823 		 * Return to the SHUTTING_DOWN state if any
1824 		 * new work appears.
1825 		 */
1826 		if (net_worklist_len > 0 || syncer_state == SYNCER_RUNNING)
1827 			last_work_seen = syncer_delayno;
1828 		if (net_worklist_len > 0 && syncer_state == SYNCER_FINAL_DELAY)
1829 			syncer_state = SYNCER_SHUTTING_DOWN;
1830 		while (!LIST_EMPTY(slp)) {
1831 			error = sync_vnode(slp, &bo, td);
1832 			if (error == 1) {
1833 				LIST_REMOVE(bo, bo_synclist);
1834 				LIST_INSERT_HEAD(next, bo, bo_synclist);
1835 				continue;
1836 			}
1837 
1838 			if (first_printf == 0)
1839 				wdog_kern_pat(WD_LASTVAL);
1840 
1841 		}
1842 		if (syncer_state == SYNCER_FINAL_DELAY && syncer_final_iter > 0)
1843 			syncer_final_iter--;
1844 		/*
1845 		 * The variable rushjob allows the kernel to speed up the
1846 		 * processing of the filesystem syncer process. A rushjob
1847 		 * value of N tells the filesystem syncer to process the next
1848 		 * N seconds worth of work on its queue ASAP. Currently rushjob
1849 		 * is used by the soft update code to speed up the filesystem
1850 		 * syncer process when the incore state is getting so far
1851 		 * ahead of the disk that the kernel memory pool is being
1852 		 * threatened with exhaustion.
1853 		 */
1854 		if (rushjob > 0) {
1855 			rushjob -= 1;
1856 			continue;
1857 		}
1858 		/*
1859 		 * Just sleep for a short period of time between
1860 		 * iterations when shutting down to allow some I/O
1861 		 * to happen.
1862 		 *
1863 		 * If it has taken us less than a second to process the
1864 		 * current work, then wait. Otherwise start right over
1865 		 * again. We can still lose time if any single round
1866 		 * takes more than two seconds, but it does not really
1867 		 * matter as we are just trying to generally pace the
1868 		 * filesystem activity.
1869 		 */
1870 		if (syncer_state != SYNCER_RUNNING ||
1871 		    time_uptime == starttime) {
1872 			thread_lock(td);
1873 			sched_prio(td, PPAUSE);
1874 			thread_unlock(td);
1875 		}
1876 		if (syncer_state != SYNCER_RUNNING)
1877 			cv_timedwait(&sync_wakeup, &sync_mtx,
1878 			    hz / SYNCER_SHUTDOWN_SPEEDUP);
1879 		else if (time_uptime == starttime)
1880 			cv_timedwait(&sync_wakeup, &sync_mtx, hz);
1881 	}
1882 }
1883 
1884 /*
1885  * Request the syncer daemon to speed up its work.
1886  * We never push it to speed up more than half of its
1887  * normal turn time, otherwise it could take over the cpu.
1888  */
1889 int
1890 speedup_syncer(void)
1891 {
1892 	int ret = 0;
1893 
1894 	mtx_lock(&sync_mtx);
1895 	if (rushjob < syncdelay / 2) {
1896 		rushjob += 1;
1897 		stat_rush_requests += 1;
1898 		ret = 1;
1899 	}
1900 	mtx_unlock(&sync_mtx);
1901 	cv_broadcast(&sync_wakeup);
1902 	return (ret);
1903 }
1904 
1905 /*
1906  * Tell the syncer to speed up its work and run though its work
1907  * list several times, then tell it to shut down.
1908  */
1909 static void
1910 syncer_shutdown(void *arg, int howto)
1911 {
1912 
1913 	if (howto & RB_NOSYNC)
1914 		return;
1915 	mtx_lock(&sync_mtx);
1916 	syncer_state = SYNCER_SHUTTING_DOWN;
1917 	rushjob = 0;
1918 	mtx_unlock(&sync_mtx);
1919 	cv_broadcast(&sync_wakeup);
1920 	kproc_shutdown(arg, howto);
1921 }
1922 
1923 /*
1924  * Reassign a buffer from one vnode to another.
1925  * Used to assign file specific control information
1926  * (indirect blocks) to the vnode to which they belong.
1927  */
1928 void
1929 reassignbuf(struct buf *bp)
1930 {
1931 	struct vnode *vp;
1932 	struct bufobj *bo;
1933 	int delay;
1934 #ifdef INVARIANTS
1935 	struct bufv *bv;
1936 #endif
1937 
1938 	vp = bp->b_vp;
1939 	bo = bp->b_bufobj;
1940 	++reassignbufcalls;
1941 
1942 	CTR3(KTR_BUF, "reassignbuf(%p) vp %p flags %X",
1943 	    bp, bp->b_vp, bp->b_flags);
1944 	/*
1945 	 * B_PAGING flagged buffers cannot be reassigned because their vp
1946 	 * is not fully linked in.
1947 	 */
1948 	if (bp->b_flags & B_PAGING)
1949 		panic("cannot reassign paging buffer");
1950 
1951 	/*
1952 	 * Delete from old vnode list, if on one.
1953 	 */
1954 	BO_LOCK(bo);
1955 	if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
1956 		buf_vlist_remove(bp);
1957 	else
1958 		panic("reassignbuf: Buffer %p not on queue.", bp);
1959 	/*
1960 	 * If dirty, put on list of dirty buffers; otherwise insert onto list
1961 	 * of clean buffers.
1962 	 */
1963 	if (bp->b_flags & B_DELWRI) {
1964 		if ((bo->bo_flag & BO_ONWORKLST) == 0) {
1965 			switch (vp->v_type) {
1966 			case VDIR:
1967 				delay = dirdelay;
1968 				break;
1969 			case VCHR:
1970 				delay = metadelay;
1971 				break;
1972 			default:
1973 				delay = filedelay;
1974 			}
1975 			vn_syncer_add_to_worklist(bo, delay);
1976 		}
1977 		buf_vlist_add(bp, bo, BX_VNDIRTY);
1978 	} else {
1979 		buf_vlist_add(bp, bo, BX_VNCLEAN);
1980 
1981 		if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
1982 			mtx_lock(&sync_mtx);
1983 			LIST_REMOVE(bo, bo_synclist);
1984 			syncer_worklist_len--;
1985 			mtx_unlock(&sync_mtx);
1986 			bo->bo_flag &= ~BO_ONWORKLST;
1987 		}
1988 	}
1989 #ifdef INVARIANTS
1990 	bv = &bo->bo_clean;
1991 	bp = TAILQ_FIRST(&bv->bv_hd);
1992 	KASSERT(bp == NULL || bp->b_bufobj == bo,
1993 	    ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
1994 	bp = TAILQ_LAST(&bv->bv_hd, buflists);
1995 	KASSERT(bp == NULL || bp->b_bufobj == bo,
1996 	    ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
1997 	bv = &bo->bo_dirty;
1998 	bp = TAILQ_FIRST(&bv->bv_hd);
1999 	KASSERT(bp == NULL || bp->b_bufobj == bo,
2000 	    ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2001 	bp = TAILQ_LAST(&bv->bv_hd, buflists);
2002 	KASSERT(bp == NULL || bp->b_bufobj == bo,
2003 	    ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2004 #endif
2005 	BO_UNLOCK(bo);
2006 }
2007 
2008 /*
2009  * Increment the use and hold counts on the vnode, taking care to reference
2010  * the driver's usecount if this is a chardev.  The vholdl() will remove
2011  * the vnode from the free list if it is presently free.  Requires the
2012  * vnode interlock and returns with it held.
2013  */
2014 static void
2015 v_incr_usecount(struct vnode *vp)
2016 {
2017 
2018 	CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2019 	vp->v_usecount++;
2020 	if (vp->v_type == VCHR && vp->v_rdev != NULL) {
2021 		dev_lock();
2022 		vp->v_rdev->si_usecount++;
2023 		dev_unlock();
2024 	}
2025 	vholdl(vp);
2026 }
2027 
2028 /*
2029  * Turn a holdcnt into a use+holdcnt such that only one call to
2030  * v_decr_usecount is needed.
2031  */
2032 static void
2033 v_upgrade_usecount(struct vnode *vp)
2034 {
2035 
2036 	CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2037 	vp->v_usecount++;
2038 	if (vp->v_type == VCHR && vp->v_rdev != NULL) {
2039 		dev_lock();
2040 		vp->v_rdev->si_usecount++;
2041 		dev_unlock();
2042 	}
2043 }
2044 
2045 /*
2046  * Decrement the vnode use and hold count along with the driver's usecount
2047  * if this is a chardev.  The vdropl() below releases the vnode interlock
2048  * as it may free the vnode.
2049  */
2050 static void
2051 v_decr_usecount(struct vnode *vp)
2052 {
2053 
2054 	ASSERT_VI_LOCKED(vp, __FUNCTION__);
2055 	VNASSERT(vp->v_usecount > 0, vp,
2056 	    ("v_decr_usecount: negative usecount"));
2057 	CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2058 	vp->v_usecount--;
2059 	if (vp->v_type == VCHR && vp->v_rdev != NULL) {
2060 		dev_lock();
2061 		vp->v_rdev->si_usecount--;
2062 		dev_unlock();
2063 	}
2064 	vdropl(vp);
2065 }
2066 
2067 /*
2068  * Decrement only the use count and driver use count.  This is intended to
2069  * be paired with a follow on vdropl() to release the remaining hold count.
2070  * In this way we may vgone() a vnode with a 0 usecount without risk of
2071  * having it end up on a free list because the hold count is kept above 0.
2072  */
2073 static void
2074 v_decr_useonly(struct vnode *vp)
2075 {
2076 
2077 	ASSERT_VI_LOCKED(vp, __FUNCTION__);
2078 	VNASSERT(vp->v_usecount > 0, vp,
2079 	    ("v_decr_useonly: negative usecount"));
2080 	CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2081 	vp->v_usecount--;
2082 	if (vp->v_type == VCHR && vp->v_rdev != NULL) {
2083 		dev_lock();
2084 		vp->v_rdev->si_usecount--;
2085 		dev_unlock();
2086 	}
2087 }
2088 
2089 /*
2090  * Grab a particular vnode from the free list, increment its
2091  * reference count and lock it.  VI_DOOMED is set if the vnode
2092  * is being destroyed.  Only callers who specify LK_RETRY will
2093  * see doomed vnodes.  If inactive processing was delayed in
2094  * vput try to do it here.
2095  */
2096 int
2097 vget(struct vnode *vp, int flags, struct thread *td)
2098 {
2099 	int error;
2100 
2101 	error = 0;
2102 	VNASSERT((flags & LK_TYPE_MASK) != 0, vp,
2103 	    ("vget: invalid lock operation"));
2104 	CTR3(KTR_VFS, "%s: vp %p with flags %d", __func__, vp, flags);
2105 
2106 	if ((flags & LK_INTERLOCK) == 0)
2107 		VI_LOCK(vp);
2108 	vholdl(vp);
2109 	if ((error = vn_lock(vp, flags | LK_INTERLOCK)) != 0) {
2110 		vdrop(vp);
2111 		CTR2(KTR_VFS, "%s: impossible to lock vnode %p", __func__,
2112 		    vp);
2113 		return (error);
2114 	}
2115 	if (vp->v_iflag & VI_DOOMED && (flags & LK_RETRY) == 0)
2116 		panic("vget: vn_lock failed to return ENOENT\n");
2117 	VI_LOCK(vp);
2118 	/* Upgrade our holdcnt to a usecount. */
2119 	v_upgrade_usecount(vp);
2120 	/*
2121 	 * We don't guarantee that any particular close will
2122 	 * trigger inactive processing so just make a best effort
2123 	 * here at preventing a reference to a removed file.  If
2124 	 * we don't succeed no harm is done.
2125 	 */
2126 	if (vp->v_iflag & VI_OWEINACT) {
2127 		if (VOP_ISLOCKED(vp) == LK_EXCLUSIVE &&
2128 		    (flags & LK_NOWAIT) == 0)
2129 			vinactive(vp, td);
2130 		vp->v_iflag &= ~VI_OWEINACT;
2131 	}
2132 	VI_UNLOCK(vp);
2133 	return (0);
2134 }
2135 
2136 /*
2137  * Increase the reference count of a vnode.
2138  */
2139 void
2140 vref(struct vnode *vp)
2141 {
2142 
2143 	CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2144 	VI_LOCK(vp);
2145 	v_incr_usecount(vp);
2146 	VI_UNLOCK(vp);
2147 }
2148 
2149 /*
2150  * Return reference count of a vnode.
2151  *
2152  * The results of this call are only guaranteed when some mechanism other
2153  * than the VI lock is used to stop other processes from gaining references
2154  * to the vnode.  This may be the case if the caller holds the only reference.
2155  * This is also useful when stale data is acceptable as race conditions may
2156  * be accounted for by some other means.
2157  */
2158 int
2159 vrefcnt(struct vnode *vp)
2160 {
2161 	int usecnt;
2162 
2163 	VI_LOCK(vp);
2164 	usecnt = vp->v_usecount;
2165 	VI_UNLOCK(vp);
2166 
2167 	return (usecnt);
2168 }
2169 
2170 #define	VPUTX_VRELE	1
2171 #define	VPUTX_VPUT	2
2172 #define	VPUTX_VUNREF	3
2173 
2174 static void
2175 vputx(struct vnode *vp, int func)
2176 {
2177 	int error;
2178 
2179 	KASSERT(vp != NULL, ("vputx: null vp"));
2180 	if (func == VPUTX_VUNREF)
2181 		ASSERT_VOP_LOCKED(vp, "vunref");
2182 	else if (func == VPUTX_VPUT)
2183 		ASSERT_VOP_LOCKED(vp, "vput");
2184 	else
2185 		KASSERT(func == VPUTX_VRELE, ("vputx: wrong func"));
2186 	CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2187 	VI_LOCK(vp);
2188 
2189 	/* Skip this v_writecount check if we're going to panic below. */
2190 	VNASSERT(vp->v_writecount < vp->v_usecount || vp->v_usecount < 1, vp,
2191 	    ("vputx: missed vn_close"));
2192 	error = 0;
2193 
2194 	if (vp->v_usecount > 1 || ((vp->v_iflag & VI_DOINGINACT) &&
2195 	    vp->v_usecount == 1)) {
2196 		if (func == VPUTX_VPUT)
2197 			VOP_UNLOCK(vp, 0);
2198 		v_decr_usecount(vp);
2199 		return;
2200 	}
2201 
2202 	if (vp->v_usecount != 1) {
2203 		vprint("vputx: negative ref count", vp);
2204 		panic("vputx: negative ref cnt");
2205 	}
2206 	CTR2(KTR_VFS, "%s: return vnode %p to the freelist", __func__, vp);
2207 	/*
2208 	 * We want to hold the vnode until the inactive finishes to
2209 	 * prevent vgone() races.  We drop the use count here and the
2210 	 * hold count below when we're done.
2211 	 */
2212 	v_decr_useonly(vp);
2213 	/*
2214 	 * We must call VOP_INACTIVE with the node locked. Mark
2215 	 * as VI_DOINGINACT to avoid recursion.
2216 	 */
2217 	vp->v_iflag |= VI_OWEINACT;
2218 	switch (func) {
2219 	case VPUTX_VRELE:
2220 		error = vn_lock(vp, LK_EXCLUSIVE | LK_INTERLOCK);
2221 		VI_LOCK(vp);
2222 		break;
2223 	case VPUTX_VPUT:
2224 		if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE) {
2225 			error = VOP_LOCK(vp, LK_UPGRADE | LK_INTERLOCK |
2226 			    LK_NOWAIT);
2227 			VI_LOCK(vp);
2228 		}
2229 		break;
2230 	case VPUTX_VUNREF:
2231 		if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE) {
2232 			error = VOP_LOCK(vp, LK_TRYUPGRADE | LK_INTERLOCK);
2233 			VI_LOCK(vp);
2234 		}
2235 		break;
2236 	}
2237 	if (vp->v_usecount > 0)
2238 		vp->v_iflag &= ~VI_OWEINACT;
2239 	if (error == 0) {
2240 		if (vp->v_iflag & VI_OWEINACT)
2241 			vinactive(vp, curthread);
2242 		if (func != VPUTX_VUNREF)
2243 			VOP_UNLOCK(vp, 0);
2244 	}
2245 	vdropl(vp);
2246 }
2247 
2248 /*
2249  * Vnode put/release.
2250  * If count drops to zero, call inactive routine and return to freelist.
2251  */
2252 void
2253 vrele(struct vnode *vp)
2254 {
2255 
2256 	vputx(vp, VPUTX_VRELE);
2257 }
2258 
2259 /*
2260  * Release an already locked vnode.  This give the same effects as
2261  * unlock+vrele(), but takes less time and avoids releasing and
2262  * re-aquiring the lock (as vrele() acquires the lock internally.)
2263  */
2264 void
2265 vput(struct vnode *vp)
2266 {
2267 
2268 	vputx(vp, VPUTX_VPUT);
2269 }
2270 
2271 /*
2272  * Release an exclusively locked vnode. Do not unlock the vnode lock.
2273  */
2274 void
2275 vunref(struct vnode *vp)
2276 {
2277 
2278 	vputx(vp, VPUTX_VUNREF);
2279 }
2280 
2281 /*
2282  * Somebody doesn't want the vnode recycled.
2283  */
2284 void
2285 vhold(struct vnode *vp)
2286 {
2287 
2288 	VI_LOCK(vp);
2289 	vholdl(vp);
2290 	VI_UNLOCK(vp);
2291 }
2292 
2293 /*
2294  * Increase the hold count and activate if this is the first reference.
2295  */
2296 void
2297 vholdl(struct vnode *vp)
2298 {
2299 	struct mount *mp;
2300 
2301 	CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2302 	vp->v_holdcnt++;
2303 	if (!VSHOULDBUSY(vp))
2304 		return;
2305 	ASSERT_VI_LOCKED(vp, "vholdl");
2306 	VNASSERT((vp->v_iflag & VI_FREE) != 0, vp, ("vnode not free"));
2307 	VNASSERT(vp->v_op != NULL, vp, ("vholdl: vnode already reclaimed."));
2308 	/*
2309 	 * Remove a vnode from the free list, mark it as in use,
2310 	 * and put it on the active list.
2311 	 */
2312 	mtx_lock(&vnode_free_list_mtx);
2313 	TAILQ_REMOVE(&vnode_free_list, vp, v_actfreelist);
2314 	freevnodes--;
2315 	vp->v_iflag &= ~(VI_FREE|VI_AGE);
2316 	KASSERT((vp->v_iflag & VI_ACTIVE) == 0,
2317 	    ("Activating already active vnode"));
2318 	vp->v_iflag |= VI_ACTIVE;
2319 	mp = vp->v_mount;
2320 	TAILQ_INSERT_HEAD(&mp->mnt_activevnodelist, vp, v_actfreelist);
2321 	mp->mnt_activevnodelistsize++;
2322 	mtx_unlock(&vnode_free_list_mtx);
2323 }
2324 
2325 /*
2326  * Note that there is one less who cares about this vnode.
2327  * vdrop() is the opposite of vhold().
2328  */
2329 void
2330 vdrop(struct vnode *vp)
2331 {
2332 
2333 	VI_LOCK(vp);
2334 	vdropl(vp);
2335 }
2336 
2337 /*
2338  * Drop the hold count of the vnode.  If this is the last reference to
2339  * the vnode we place it on the free list unless it has been vgone'd
2340  * (marked VI_DOOMED) in which case we will free it.
2341  */
2342 void
2343 vdropl(struct vnode *vp)
2344 {
2345 	struct bufobj *bo;
2346 	struct mount *mp;
2347 	int active;
2348 
2349 	ASSERT_VI_LOCKED(vp, "vdropl");
2350 	CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2351 	if (vp->v_holdcnt <= 0)
2352 		panic("vdrop: holdcnt %d", vp->v_holdcnt);
2353 	vp->v_holdcnt--;
2354 	VNASSERT(vp->v_holdcnt >= vp->v_usecount, vp,
2355 	    ("hold count less than use count"));
2356 	if (vp->v_holdcnt > 0) {
2357 		VI_UNLOCK(vp);
2358 		return;
2359 	}
2360 	if ((vp->v_iflag & VI_DOOMED) == 0) {
2361 		/*
2362 		 * Mark a vnode as free: remove it from its active list
2363 		 * and put it up for recycling on the freelist.
2364 		 */
2365 		VNASSERT(vp->v_op != NULL, vp,
2366 		    ("vdropl: vnode already reclaimed."));
2367 		VNASSERT((vp->v_iflag & VI_FREE) == 0, vp,
2368 		    ("vnode already free"));
2369 		VNASSERT(VSHOULDFREE(vp), vp,
2370 		    ("vdropl: freeing when we shouldn't"));
2371 		active = vp->v_iflag & VI_ACTIVE;
2372 		vp->v_iflag &= ~VI_ACTIVE;
2373 		mp = vp->v_mount;
2374 		mtx_lock(&vnode_free_list_mtx);
2375 		if (active) {
2376 			TAILQ_REMOVE(&mp->mnt_activevnodelist, vp,
2377 			    v_actfreelist);
2378 			mp->mnt_activevnodelistsize--;
2379 		}
2380 		if (vp->v_iflag & VI_AGE) {
2381 			TAILQ_INSERT_HEAD(&vnode_free_list, vp, v_actfreelist);
2382 		} else {
2383 			TAILQ_INSERT_TAIL(&vnode_free_list, vp, v_actfreelist);
2384 		}
2385 		freevnodes++;
2386 		vp->v_iflag &= ~VI_AGE;
2387 		vp->v_iflag |= VI_FREE;
2388 		mtx_unlock(&vnode_free_list_mtx);
2389 		VI_UNLOCK(vp);
2390 		return;
2391 	}
2392 	/*
2393 	 * The vnode has been marked for destruction, so free it.
2394 	 */
2395 	CTR2(KTR_VFS, "%s: destroying the vnode %p", __func__, vp);
2396 	atomic_subtract_long(&numvnodes, 1);
2397 	bo = &vp->v_bufobj;
2398 	VNASSERT((vp->v_iflag & VI_FREE) == 0, vp,
2399 	    ("cleaned vnode still on the free list."));
2400 	VNASSERT(vp->v_data == NULL, vp, ("cleaned vnode isn't"));
2401 	VNASSERT(vp->v_holdcnt == 0, vp, ("Non-zero hold count"));
2402 	VNASSERT(vp->v_usecount == 0, vp, ("Non-zero use count"));
2403 	VNASSERT(vp->v_writecount == 0, vp, ("Non-zero write count"));
2404 	VNASSERT(bo->bo_numoutput == 0, vp, ("Clean vnode has pending I/O's"));
2405 	VNASSERT(bo->bo_clean.bv_cnt == 0, vp, ("cleanbufcnt not 0"));
2406 	VNASSERT(pctrie_is_empty(&bo->bo_clean.bv_root), vp,
2407 	    ("clean blk trie not empty"));
2408 	VNASSERT(bo->bo_dirty.bv_cnt == 0, vp, ("dirtybufcnt not 0"));
2409 	VNASSERT(pctrie_is_empty(&bo->bo_dirty.bv_root), vp,
2410 	    ("dirty blk trie not empty"));
2411 	VNASSERT(TAILQ_EMPTY(&vp->v_cache_dst), vp, ("vp has namecache dst"));
2412 	VNASSERT(LIST_EMPTY(&vp->v_cache_src), vp, ("vp has namecache src"));
2413 	VNASSERT(vp->v_cache_dd == NULL, vp, ("vp has namecache for .."));
2414 	VI_UNLOCK(vp);
2415 #ifdef MAC
2416 	mac_vnode_destroy(vp);
2417 #endif
2418 	if (vp->v_pollinfo != NULL)
2419 		destroy_vpollinfo(vp->v_pollinfo);
2420 #ifdef INVARIANTS
2421 	/* XXX Elsewhere we detect an already freed vnode via NULL v_op. */
2422 	vp->v_op = NULL;
2423 #endif
2424 	rangelock_destroy(&vp->v_rl);
2425 	lockdestroy(vp->v_vnlock);
2426 	mtx_destroy(&vp->v_interlock);
2427 	rw_destroy(BO_LOCKPTR(bo));
2428 	uma_zfree(vnode_zone, vp);
2429 }
2430 
2431 /*
2432  * Call VOP_INACTIVE on the vnode and manage the DOINGINACT and OWEINACT
2433  * flags.  DOINGINACT prevents us from recursing in calls to vinactive.
2434  * OWEINACT tracks whether a vnode missed a call to inactive due to a
2435  * failed lock upgrade.
2436  */
2437 void
2438 vinactive(struct vnode *vp, struct thread *td)
2439 {
2440 	struct vm_object *obj;
2441 
2442 	ASSERT_VOP_ELOCKED(vp, "vinactive");
2443 	ASSERT_VI_LOCKED(vp, "vinactive");
2444 	VNASSERT((vp->v_iflag & VI_DOINGINACT) == 0, vp,
2445 	    ("vinactive: recursed on VI_DOINGINACT"));
2446 	CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2447 	vp->v_iflag |= VI_DOINGINACT;
2448 	vp->v_iflag &= ~VI_OWEINACT;
2449 	VI_UNLOCK(vp);
2450 	/*
2451 	 * Before moving off the active list, we must be sure that any
2452 	 * modified pages are on the vnode's dirty list since these will
2453 	 * no longer be checked once the vnode is on the inactive list.
2454 	 * Because the vnode vm object keeps a hold reference on the vnode
2455 	 * if there is at least one resident non-cached page, the vnode
2456 	 * cannot leave the active list without the page cleanup done.
2457 	 */
2458 	obj = vp->v_object;
2459 	if (obj != NULL && (obj->flags & OBJ_MIGHTBEDIRTY) != 0) {
2460 		VM_OBJECT_WLOCK(obj);
2461 		vm_object_page_clean(obj, 0, 0, OBJPC_NOSYNC);
2462 		VM_OBJECT_WUNLOCK(obj);
2463 	}
2464 	VOP_INACTIVE(vp, td);
2465 	VI_LOCK(vp);
2466 	VNASSERT(vp->v_iflag & VI_DOINGINACT, vp,
2467 	    ("vinactive: lost VI_DOINGINACT"));
2468 	vp->v_iflag &= ~VI_DOINGINACT;
2469 }
2470 
2471 /*
2472  * Remove any vnodes in the vnode table belonging to mount point mp.
2473  *
2474  * If FORCECLOSE is not specified, there should not be any active ones,
2475  * return error if any are found (nb: this is a user error, not a
2476  * system error). If FORCECLOSE is specified, detach any active vnodes
2477  * that are found.
2478  *
2479  * If WRITECLOSE is set, only flush out regular file vnodes open for
2480  * writing.
2481  *
2482  * SKIPSYSTEM causes any vnodes marked VV_SYSTEM to be skipped.
2483  *
2484  * `rootrefs' specifies the base reference count for the root vnode
2485  * of this filesystem. The root vnode is considered busy if its
2486  * v_usecount exceeds this value. On a successful return, vflush(, td)
2487  * will call vrele() on the root vnode exactly rootrefs times.
2488  * If the SKIPSYSTEM or WRITECLOSE flags are specified, rootrefs must
2489  * be zero.
2490  */
2491 #ifdef DIAGNOSTIC
2492 static int busyprt = 0;		/* print out busy vnodes */
2493 SYSCTL_INT(_debug, OID_AUTO, busyprt, CTLFLAG_RW, &busyprt, 0, "Print out busy vnodes");
2494 #endif
2495 
2496 int
2497 vflush(struct mount *mp, int rootrefs, int flags, struct thread *td)
2498 {
2499 	struct vnode *vp, *mvp, *rootvp = NULL;
2500 	struct vattr vattr;
2501 	int busy = 0, error;
2502 
2503 	CTR4(KTR_VFS, "%s: mp %p with rootrefs %d and flags %d", __func__, mp,
2504 	    rootrefs, flags);
2505 	if (rootrefs > 0) {
2506 		KASSERT((flags & (SKIPSYSTEM | WRITECLOSE)) == 0,
2507 		    ("vflush: bad args"));
2508 		/*
2509 		 * Get the filesystem root vnode. We can vput() it
2510 		 * immediately, since with rootrefs > 0, it won't go away.
2511 		 */
2512 		if ((error = VFS_ROOT(mp, LK_EXCLUSIVE, &rootvp)) != 0) {
2513 			CTR2(KTR_VFS, "%s: vfs_root lookup failed with %d",
2514 			    __func__, error);
2515 			return (error);
2516 		}
2517 		vput(rootvp);
2518 	}
2519 loop:
2520 	MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
2521 		vholdl(vp);
2522 		error = vn_lock(vp, LK_INTERLOCK | LK_EXCLUSIVE);
2523 		if (error) {
2524 			vdrop(vp);
2525 			MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
2526 			goto loop;
2527 		}
2528 		/*
2529 		 * Skip over a vnodes marked VV_SYSTEM.
2530 		 */
2531 		if ((flags & SKIPSYSTEM) && (vp->v_vflag & VV_SYSTEM)) {
2532 			VOP_UNLOCK(vp, 0);
2533 			vdrop(vp);
2534 			continue;
2535 		}
2536 		/*
2537 		 * If WRITECLOSE is set, flush out unlinked but still open
2538 		 * files (even if open only for reading) and regular file
2539 		 * vnodes open for writing.
2540 		 */
2541 		if (flags & WRITECLOSE) {
2542 			if (vp->v_object != NULL) {
2543 				VM_OBJECT_WLOCK(vp->v_object);
2544 				vm_object_page_clean(vp->v_object, 0, 0, 0);
2545 				VM_OBJECT_WUNLOCK(vp->v_object);
2546 			}
2547 			error = VOP_FSYNC(vp, MNT_WAIT, td);
2548 			if (error != 0) {
2549 				VOP_UNLOCK(vp, 0);
2550 				vdrop(vp);
2551 				MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
2552 				return (error);
2553 			}
2554 			error = VOP_GETATTR(vp, &vattr, td->td_ucred);
2555 			VI_LOCK(vp);
2556 
2557 			if ((vp->v_type == VNON ||
2558 			    (error == 0 && vattr.va_nlink > 0)) &&
2559 			    (vp->v_writecount == 0 || vp->v_type != VREG)) {
2560 				VOP_UNLOCK(vp, 0);
2561 				vdropl(vp);
2562 				continue;
2563 			}
2564 		} else
2565 			VI_LOCK(vp);
2566 		/*
2567 		 * With v_usecount == 0, all we need to do is clear out the
2568 		 * vnode data structures and we are done.
2569 		 *
2570 		 * If FORCECLOSE is set, forcibly close the vnode.
2571 		 */
2572 		if (vp->v_usecount == 0 || (flags & FORCECLOSE)) {
2573 			VNASSERT(vp->v_usecount == 0 ||
2574 			    (vp->v_type != VCHR && vp->v_type != VBLK), vp,
2575 			    ("device VNODE %p is FORCECLOSED", vp));
2576 			vgonel(vp);
2577 		} else {
2578 			busy++;
2579 #ifdef DIAGNOSTIC
2580 			if (busyprt)
2581 				vprint("vflush: busy vnode", vp);
2582 #endif
2583 		}
2584 		VOP_UNLOCK(vp, 0);
2585 		vdropl(vp);
2586 	}
2587 	if (rootrefs > 0 && (flags & FORCECLOSE) == 0) {
2588 		/*
2589 		 * If just the root vnode is busy, and if its refcount
2590 		 * is equal to `rootrefs', then go ahead and kill it.
2591 		 */
2592 		VI_LOCK(rootvp);
2593 		KASSERT(busy > 0, ("vflush: not busy"));
2594 		VNASSERT(rootvp->v_usecount >= rootrefs, rootvp,
2595 		    ("vflush: usecount %d < rootrefs %d",
2596 		     rootvp->v_usecount, rootrefs));
2597 		if (busy == 1 && rootvp->v_usecount == rootrefs) {
2598 			VOP_LOCK(rootvp, LK_EXCLUSIVE|LK_INTERLOCK);
2599 			vgone(rootvp);
2600 			VOP_UNLOCK(rootvp, 0);
2601 			busy = 0;
2602 		} else
2603 			VI_UNLOCK(rootvp);
2604 	}
2605 	if (busy) {
2606 		CTR2(KTR_VFS, "%s: failing as %d vnodes are busy", __func__,
2607 		    busy);
2608 		return (EBUSY);
2609 	}
2610 	for (; rootrefs > 0; rootrefs--)
2611 		vrele(rootvp);
2612 	return (0);
2613 }
2614 
2615 /*
2616  * Recycle an unused vnode to the front of the free list.
2617  */
2618 int
2619 vrecycle(struct vnode *vp)
2620 {
2621 	int recycled;
2622 
2623 	ASSERT_VOP_ELOCKED(vp, "vrecycle");
2624 	CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2625 	recycled = 0;
2626 	VI_LOCK(vp);
2627 	if (vp->v_usecount == 0) {
2628 		recycled = 1;
2629 		vgonel(vp);
2630 	}
2631 	VI_UNLOCK(vp);
2632 	return (recycled);
2633 }
2634 
2635 /*
2636  * Eliminate all activity associated with a vnode
2637  * in preparation for reuse.
2638  */
2639 void
2640 vgone(struct vnode *vp)
2641 {
2642 	VI_LOCK(vp);
2643 	vgonel(vp);
2644 	VI_UNLOCK(vp);
2645 }
2646 
2647 static void
2648 notify_lowervp_vfs_dummy(struct mount *mp __unused,
2649     struct vnode *lowervp __unused)
2650 {
2651 }
2652 
2653 /*
2654  * Notify upper mounts about reclaimed or unlinked vnode.
2655  */
2656 void
2657 vfs_notify_upper(struct vnode *vp, int event)
2658 {
2659 	static struct vfsops vgonel_vfsops = {
2660 		.vfs_reclaim_lowervp = notify_lowervp_vfs_dummy,
2661 		.vfs_unlink_lowervp = notify_lowervp_vfs_dummy,
2662 	};
2663 	struct mount *mp, *ump, *mmp;
2664 
2665 	mp = vp->v_mount;
2666 	if (mp == NULL)
2667 		return;
2668 
2669 	MNT_ILOCK(mp);
2670 	if (TAILQ_EMPTY(&mp->mnt_uppers))
2671 		goto unlock;
2672 	MNT_IUNLOCK(mp);
2673 	mmp = malloc(sizeof(struct mount), M_TEMP, M_WAITOK | M_ZERO);
2674 	mmp->mnt_op = &vgonel_vfsops;
2675 	mmp->mnt_kern_flag |= MNTK_MARKER;
2676 	MNT_ILOCK(mp);
2677 	mp->mnt_kern_flag |= MNTK_VGONE_UPPER;
2678 	for (ump = TAILQ_FIRST(&mp->mnt_uppers); ump != NULL;) {
2679 		if ((ump->mnt_kern_flag & MNTK_MARKER) != 0) {
2680 			ump = TAILQ_NEXT(ump, mnt_upper_link);
2681 			continue;
2682 		}
2683 		TAILQ_INSERT_AFTER(&mp->mnt_uppers, ump, mmp, mnt_upper_link);
2684 		MNT_IUNLOCK(mp);
2685 		switch (event) {
2686 		case VFS_NOTIFY_UPPER_RECLAIM:
2687 			VFS_RECLAIM_LOWERVP(ump, vp);
2688 			break;
2689 		case VFS_NOTIFY_UPPER_UNLINK:
2690 			VFS_UNLINK_LOWERVP(ump, vp);
2691 			break;
2692 		default:
2693 			KASSERT(0, ("invalid event %d", event));
2694 			break;
2695 		}
2696 		MNT_ILOCK(mp);
2697 		ump = TAILQ_NEXT(mmp, mnt_upper_link);
2698 		TAILQ_REMOVE(&mp->mnt_uppers, mmp, mnt_upper_link);
2699 	}
2700 	free(mmp, M_TEMP);
2701 	mp->mnt_kern_flag &= ~MNTK_VGONE_UPPER;
2702 	if ((mp->mnt_kern_flag & MNTK_VGONE_WAITER) != 0) {
2703 		mp->mnt_kern_flag &= ~MNTK_VGONE_WAITER;
2704 		wakeup(&mp->mnt_uppers);
2705 	}
2706 unlock:
2707 	MNT_IUNLOCK(mp);
2708 }
2709 
2710 /*
2711  * vgone, with the vp interlock held.
2712  */
2713 void
2714 vgonel(struct vnode *vp)
2715 {
2716 	struct thread *td;
2717 	int oweinact;
2718 	int active;
2719 	struct mount *mp;
2720 
2721 	ASSERT_VOP_ELOCKED(vp, "vgonel");
2722 	ASSERT_VI_LOCKED(vp, "vgonel");
2723 	VNASSERT(vp->v_holdcnt, vp,
2724 	    ("vgonel: vp %p has no reference.", vp));
2725 	CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2726 	td = curthread;
2727 
2728 	/*
2729 	 * Don't vgonel if we're already doomed.
2730 	 */
2731 	if (vp->v_iflag & VI_DOOMED)
2732 		return;
2733 	vp->v_iflag |= VI_DOOMED;
2734 
2735 	/*
2736 	 * Check to see if the vnode is in use.  If so, we have to call
2737 	 * VOP_CLOSE() and VOP_INACTIVE().
2738 	 */
2739 	active = vp->v_usecount;
2740 	oweinact = (vp->v_iflag & VI_OWEINACT);
2741 	VI_UNLOCK(vp);
2742 	vfs_notify_upper(vp, VFS_NOTIFY_UPPER_RECLAIM);
2743 
2744 	/*
2745 	 * Clean out any buffers associated with the vnode.
2746 	 * If the flush fails, just toss the buffers.
2747 	 */
2748 	mp = NULL;
2749 	if (!TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd))
2750 		(void) vn_start_secondary_write(vp, &mp, V_WAIT);
2751 	if (vinvalbuf(vp, V_SAVE, 0, 0) != 0)
2752 		vinvalbuf(vp, 0, 0, 0);
2753 
2754 	/*
2755 	 * If purging an active vnode, it must be closed and
2756 	 * deactivated before being reclaimed.
2757 	 */
2758 	if (active)
2759 		VOP_CLOSE(vp, FNONBLOCK, NOCRED, td);
2760 	if (oweinact || active) {
2761 		VI_LOCK(vp);
2762 		if ((vp->v_iflag & VI_DOINGINACT) == 0)
2763 			vinactive(vp, td);
2764 		VI_UNLOCK(vp);
2765 	}
2766 	if (vp->v_type == VSOCK)
2767 		vfs_unp_reclaim(vp);
2768 	/*
2769 	 * Reclaim the vnode.
2770 	 */
2771 	if (VOP_RECLAIM(vp, td))
2772 		panic("vgone: cannot reclaim");
2773 	if (mp != NULL)
2774 		vn_finished_secondary_write(mp);
2775 	VNASSERT(vp->v_object == NULL, vp,
2776 	    ("vop_reclaim left v_object vp=%p, tag=%s", vp, vp->v_tag));
2777 	/*
2778 	 * Clear the advisory locks and wake up waiting threads.
2779 	 */
2780 	(void)VOP_ADVLOCKPURGE(vp);
2781 	/*
2782 	 * Delete from old mount point vnode list.
2783 	 */
2784 	delmntque(vp);
2785 	cache_purge(vp);
2786 	/*
2787 	 * Done with purge, reset to the standard lock and invalidate
2788 	 * the vnode.
2789 	 */
2790 	VI_LOCK(vp);
2791 	vp->v_vnlock = &vp->v_lock;
2792 	vp->v_op = &dead_vnodeops;
2793 	vp->v_tag = "none";
2794 	vp->v_type = VBAD;
2795 }
2796 
2797 /*
2798  * Calculate the total number of references to a special device.
2799  */
2800 int
2801 vcount(struct vnode *vp)
2802 {
2803 	int count;
2804 
2805 	dev_lock();
2806 	count = vp->v_rdev->si_usecount;
2807 	dev_unlock();
2808 	return (count);
2809 }
2810 
2811 /*
2812  * Same as above, but using the struct cdev *as argument
2813  */
2814 int
2815 count_dev(struct cdev *dev)
2816 {
2817 	int count;
2818 
2819 	dev_lock();
2820 	count = dev->si_usecount;
2821 	dev_unlock();
2822 	return(count);
2823 }
2824 
2825 /*
2826  * Print out a description of a vnode.
2827  */
2828 static char *typename[] =
2829 {"VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD",
2830  "VMARKER"};
2831 
2832 void
2833 vn_printf(struct vnode *vp, const char *fmt, ...)
2834 {
2835 	va_list ap;
2836 	char buf[256], buf2[16];
2837 	u_long flags;
2838 
2839 	va_start(ap, fmt);
2840 	vprintf(fmt, ap);
2841 	va_end(ap);
2842 	printf("%p: ", (void *)vp);
2843 	printf("tag %s, type %s\n", vp->v_tag, typename[vp->v_type]);
2844 	printf("    usecount %d, writecount %d, refcount %d mountedhere %p\n",
2845 	    vp->v_usecount, vp->v_writecount, vp->v_holdcnt, vp->v_mountedhere);
2846 	buf[0] = '\0';
2847 	buf[1] = '\0';
2848 	if (vp->v_vflag & VV_ROOT)
2849 		strlcat(buf, "|VV_ROOT", sizeof(buf));
2850 	if (vp->v_vflag & VV_ISTTY)
2851 		strlcat(buf, "|VV_ISTTY", sizeof(buf));
2852 	if (vp->v_vflag & VV_NOSYNC)
2853 		strlcat(buf, "|VV_NOSYNC", sizeof(buf));
2854 	if (vp->v_vflag & VV_ETERNALDEV)
2855 		strlcat(buf, "|VV_ETERNALDEV", sizeof(buf));
2856 	if (vp->v_vflag & VV_CACHEDLABEL)
2857 		strlcat(buf, "|VV_CACHEDLABEL", sizeof(buf));
2858 	if (vp->v_vflag & VV_TEXT)
2859 		strlcat(buf, "|VV_TEXT", sizeof(buf));
2860 	if (vp->v_vflag & VV_COPYONWRITE)
2861 		strlcat(buf, "|VV_COPYONWRITE", sizeof(buf));
2862 	if (vp->v_vflag & VV_SYSTEM)
2863 		strlcat(buf, "|VV_SYSTEM", sizeof(buf));
2864 	if (vp->v_vflag & VV_PROCDEP)
2865 		strlcat(buf, "|VV_PROCDEP", sizeof(buf));
2866 	if (vp->v_vflag & VV_NOKNOTE)
2867 		strlcat(buf, "|VV_NOKNOTE", sizeof(buf));
2868 	if (vp->v_vflag & VV_DELETED)
2869 		strlcat(buf, "|VV_DELETED", sizeof(buf));
2870 	if (vp->v_vflag & VV_MD)
2871 		strlcat(buf, "|VV_MD", sizeof(buf));
2872 	if (vp->v_vflag & VV_FORCEINSMQ)
2873 		strlcat(buf, "|VV_FORCEINSMQ", sizeof(buf));
2874 	flags = vp->v_vflag & ~(VV_ROOT | VV_ISTTY | VV_NOSYNC | VV_ETERNALDEV |
2875 	    VV_CACHEDLABEL | VV_TEXT | VV_COPYONWRITE | VV_SYSTEM | VV_PROCDEP |
2876 	    VV_NOKNOTE | VV_DELETED | VV_MD | VV_FORCEINSMQ);
2877 	if (flags != 0) {
2878 		snprintf(buf2, sizeof(buf2), "|VV(0x%lx)", flags);
2879 		strlcat(buf, buf2, sizeof(buf));
2880 	}
2881 	if (vp->v_iflag & VI_MOUNT)
2882 		strlcat(buf, "|VI_MOUNT", sizeof(buf));
2883 	if (vp->v_iflag & VI_AGE)
2884 		strlcat(buf, "|VI_AGE", sizeof(buf));
2885 	if (vp->v_iflag & VI_DOOMED)
2886 		strlcat(buf, "|VI_DOOMED", sizeof(buf));
2887 	if (vp->v_iflag & VI_FREE)
2888 		strlcat(buf, "|VI_FREE", sizeof(buf));
2889 	if (vp->v_iflag & VI_ACTIVE)
2890 		strlcat(buf, "|VI_ACTIVE", sizeof(buf));
2891 	if (vp->v_iflag & VI_DOINGINACT)
2892 		strlcat(buf, "|VI_DOINGINACT", sizeof(buf));
2893 	if (vp->v_iflag & VI_OWEINACT)
2894 		strlcat(buf, "|VI_OWEINACT", sizeof(buf));
2895 	flags = vp->v_iflag & ~(VI_MOUNT | VI_AGE | VI_DOOMED | VI_FREE |
2896 	    VI_ACTIVE | VI_DOINGINACT | VI_OWEINACT);
2897 	if (flags != 0) {
2898 		snprintf(buf2, sizeof(buf2), "|VI(0x%lx)", flags);
2899 		strlcat(buf, buf2, sizeof(buf));
2900 	}
2901 	printf("    flags (%s)\n", buf + 1);
2902 	if (mtx_owned(VI_MTX(vp)))
2903 		printf(" VI_LOCKed");
2904 	if (vp->v_object != NULL)
2905 		printf("    v_object %p ref %d pages %d "
2906 		    "cleanbuf %d dirtybuf %d\n",
2907 		    vp->v_object, vp->v_object->ref_count,
2908 		    vp->v_object->resident_page_count,
2909 		    vp->v_bufobj.bo_dirty.bv_cnt,
2910 		    vp->v_bufobj.bo_clean.bv_cnt);
2911 	printf("    ");
2912 	lockmgr_printinfo(vp->v_vnlock);
2913 	if (vp->v_data != NULL)
2914 		VOP_PRINT(vp);
2915 }
2916 
2917 #ifdef DDB
2918 /*
2919  * List all of the locked vnodes in the system.
2920  * Called when debugging the kernel.
2921  */
2922 DB_SHOW_COMMAND(lockedvnods, lockedvnodes)
2923 {
2924 	struct mount *mp;
2925 	struct vnode *vp;
2926 
2927 	/*
2928 	 * Note: because this is DDB, we can't obey the locking semantics
2929 	 * for these structures, which means we could catch an inconsistent
2930 	 * state and dereference a nasty pointer.  Not much to be done
2931 	 * about that.
2932 	 */
2933 	db_printf("Locked vnodes\n");
2934 	TAILQ_FOREACH(mp, &mountlist, mnt_list) {
2935 		TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
2936 			if (vp->v_type != VMARKER && VOP_ISLOCKED(vp))
2937 				vprint("", vp);
2938 		}
2939 	}
2940 }
2941 
2942 /*
2943  * Show details about the given vnode.
2944  */
2945 DB_SHOW_COMMAND(vnode, db_show_vnode)
2946 {
2947 	struct vnode *vp;
2948 
2949 	if (!have_addr)
2950 		return;
2951 	vp = (struct vnode *)addr;
2952 	vn_printf(vp, "vnode ");
2953 }
2954 
2955 /*
2956  * Show details about the given mount point.
2957  */
2958 DB_SHOW_COMMAND(mount, db_show_mount)
2959 {
2960 	struct mount *mp;
2961 	struct vfsopt *opt;
2962 	struct statfs *sp;
2963 	struct vnode *vp;
2964 	char buf[512];
2965 	uint64_t mflags;
2966 	u_int flags;
2967 
2968 	if (!have_addr) {
2969 		/* No address given, print short info about all mount points. */
2970 		TAILQ_FOREACH(mp, &mountlist, mnt_list) {
2971 			db_printf("%p %s on %s (%s)\n", mp,
2972 			    mp->mnt_stat.f_mntfromname,
2973 			    mp->mnt_stat.f_mntonname,
2974 			    mp->mnt_stat.f_fstypename);
2975 			if (db_pager_quit)
2976 				break;
2977 		}
2978 		db_printf("\nMore info: show mount <addr>\n");
2979 		return;
2980 	}
2981 
2982 	mp = (struct mount *)addr;
2983 	db_printf("%p %s on %s (%s)\n", mp, mp->mnt_stat.f_mntfromname,
2984 	    mp->mnt_stat.f_mntonname, mp->mnt_stat.f_fstypename);
2985 
2986 	buf[0] = '\0';
2987 	mflags = mp->mnt_flag;
2988 #define	MNT_FLAG(flag)	do {						\
2989 	if (mflags & (flag)) {						\
2990 		if (buf[0] != '\0')					\
2991 			strlcat(buf, ", ", sizeof(buf));		\
2992 		strlcat(buf, (#flag) + 4, sizeof(buf));			\
2993 		mflags &= ~(flag);					\
2994 	}								\
2995 } while (0)
2996 	MNT_FLAG(MNT_RDONLY);
2997 	MNT_FLAG(MNT_SYNCHRONOUS);
2998 	MNT_FLAG(MNT_NOEXEC);
2999 	MNT_FLAG(MNT_NOSUID);
3000 	MNT_FLAG(MNT_NFS4ACLS);
3001 	MNT_FLAG(MNT_UNION);
3002 	MNT_FLAG(MNT_ASYNC);
3003 	MNT_FLAG(MNT_SUIDDIR);
3004 	MNT_FLAG(MNT_SOFTDEP);
3005 	MNT_FLAG(MNT_NOSYMFOLLOW);
3006 	MNT_FLAG(MNT_GJOURNAL);
3007 	MNT_FLAG(MNT_MULTILABEL);
3008 	MNT_FLAG(MNT_ACLS);
3009 	MNT_FLAG(MNT_NOATIME);
3010 	MNT_FLAG(MNT_NOCLUSTERR);
3011 	MNT_FLAG(MNT_NOCLUSTERW);
3012 	MNT_FLAG(MNT_SUJ);
3013 	MNT_FLAG(MNT_EXRDONLY);
3014 	MNT_FLAG(MNT_EXPORTED);
3015 	MNT_FLAG(MNT_DEFEXPORTED);
3016 	MNT_FLAG(MNT_EXPORTANON);
3017 	MNT_FLAG(MNT_EXKERB);
3018 	MNT_FLAG(MNT_EXPUBLIC);
3019 	MNT_FLAG(MNT_LOCAL);
3020 	MNT_FLAG(MNT_QUOTA);
3021 	MNT_FLAG(MNT_ROOTFS);
3022 	MNT_FLAG(MNT_USER);
3023 	MNT_FLAG(MNT_IGNORE);
3024 	MNT_FLAG(MNT_UPDATE);
3025 	MNT_FLAG(MNT_DELEXPORT);
3026 	MNT_FLAG(MNT_RELOAD);
3027 	MNT_FLAG(MNT_FORCE);
3028 	MNT_FLAG(MNT_SNAPSHOT);
3029 	MNT_FLAG(MNT_BYFSID);
3030 #undef MNT_FLAG
3031 	if (mflags != 0) {
3032 		if (buf[0] != '\0')
3033 			strlcat(buf, ", ", sizeof(buf));
3034 		snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
3035 		    "0x%016jx", mflags);
3036 	}
3037 	db_printf("    mnt_flag = %s\n", buf);
3038 
3039 	buf[0] = '\0';
3040 	flags = mp->mnt_kern_flag;
3041 #define	MNT_KERN_FLAG(flag)	do {					\
3042 	if (flags & (flag)) {						\
3043 		if (buf[0] != '\0')					\
3044 			strlcat(buf, ", ", sizeof(buf));		\
3045 		strlcat(buf, (#flag) + 5, sizeof(buf));			\
3046 		flags &= ~(flag);					\
3047 	}								\
3048 } while (0)
3049 	MNT_KERN_FLAG(MNTK_UNMOUNTF);
3050 	MNT_KERN_FLAG(MNTK_ASYNC);
3051 	MNT_KERN_FLAG(MNTK_SOFTDEP);
3052 	MNT_KERN_FLAG(MNTK_NOINSMNTQ);
3053 	MNT_KERN_FLAG(MNTK_DRAINING);
3054 	MNT_KERN_FLAG(MNTK_REFEXPIRE);
3055 	MNT_KERN_FLAG(MNTK_EXTENDED_SHARED);
3056 	MNT_KERN_FLAG(MNTK_SHARED_WRITES);
3057 	MNT_KERN_FLAG(MNTK_NO_IOPF);
3058 	MNT_KERN_FLAG(MNTK_VGONE_UPPER);
3059 	MNT_KERN_FLAG(MNTK_VGONE_WAITER);
3060 	MNT_KERN_FLAG(MNTK_LOOKUP_EXCL_DOTDOT);
3061 	MNT_KERN_FLAG(MNTK_MARKER);
3062 	MNT_KERN_FLAG(MNTK_NOASYNC);
3063 	MNT_KERN_FLAG(MNTK_UNMOUNT);
3064 	MNT_KERN_FLAG(MNTK_MWAIT);
3065 	MNT_KERN_FLAG(MNTK_SUSPEND);
3066 	MNT_KERN_FLAG(MNTK_SUSPEND2);
3067 	MNT_KERN_FLAG(MNTK_SUSPENDED);
3068 	MNT_KERN_FLAG(MNTK_LOOKUP_SHARED);
3069 	MNT_KERN_FLAG(MNTK_NOKNOTE);
3070 #undef MNT_KERN_FLAG
3071 	if (flags != 0) {
3072 		if (buf[0] != '\0')
3073 			strlcat(buf, ", ", sizeof(buf));
3074 		snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
3075 		    "0x%08x", flags);
3076 	}
3077 	db_printf("    mnt_kern_flag = %s\n", buf);
3078 
3079 	db_printf("    mnt_opt = ");
3080 	opt = TAILQ_FIRST(mp->mnt_opt);
3081 	if (opt != NULL) {
3082 		db_printf("%s", opt->name);
3083 		opt = TAILQ_NEXT(opt, link);
3084 		while (opt != NULL) {
3085 			db_printf(", %s", opt->name);
3086 			opt = TAILQ_NEXT(opt, link);
3087 		}
3088 	}
3089 	db_printf("\n");
3090 
3091 	sp = &mp->mnt_stat;
3092 	db_printf("    mnt_stat = { version=%u type=%u flags=0x%016jx "
3093 	    "bsize=%ju iosize=%ju blocks=%ju bfree=%ju bavail=%jd files=%ju "
3094 	    "ffree=%jd syncwrites=%ju asyncwrites=%ju syncreads=%ju "
3095 	    "asyncreads=%ju namemax=%u owner=%u fsid=[%d, %d] }\n",
3096 	    (u_int)sp->f_version, (u_int)sp->f_type, (uintmax_t)sp->f_flags,
3097 	    (uintmax_t)sp->f_bsize, (uintmax_t)sp->f_iosize,
3098 	    (uintmax_t)sp->f_blocks, (uintmax_t)sp->f_bfree,
3099 	    (intmax_t)sp->f_bavail, (uintmax_t)sp->f_files,
3100 	    (intmax_t)sp->f_ffree, (uintmax_t)sp->f_syncwrites,
3101 	    (uintmax_t)sp->f_asyncwrites, (uintmax_t)sp->f_syncreads,
3102 	    (uintmax_t)sp->f_asyncreads, (u_int)sp->f_namemax,
3103 	    (u_int)sp->f_owner, (int)sp->f_fsid.val[0], (int)sp->f_fsid.val[1]);
3104 
3105 	db_printf("    mnt_cred = { uid=%u ruid=%u",
3106 	    (u_int)mp->mnt_cred->cr_uid, (u_int)mp->mnt_cred->cr_ruid);
3107 	if (jailed(mp->mnt_cred))
3108 		db_printf(", jail=%d", mp->mnt_cred->cr_prison->pr_id);
3109 	db_printf(" }\n");
3110 	db_printf("    mnt_ref = %d\n", mp->mnt_ref);
3111 	db_printf("    mnt_gen = %d\n", mp->mnt_gen);
3112 	db_printf("    mnt_nvnodelistsize = %d\n", mp->mnt_nvnodelistsize);
3113 	db_printf("    mnt_activevnodelistsize = %d\n",
3114 	    mp->mnt_activevnodelistsize);
3115 	db_printf("    mnt_writeopcount = %d\n", mp->mnt_writeopcount);
3116 	db_printf("    mnt_maxsymlinklen = %d\n", mp->mnt_maxsymlinklen);
3117 	db_printf("    mnt_iosize_max = %d\n", mp->mnt_iosize_max);
3118 	db_printf("    mnt_hashseed = %u\n", mp->mnt_hashseed);
3119 	db_printf("    mnt_secondary_writes = %d\n", mp->mnt_secondary_writes);
3120 	db_printf("    mnt_secondary_accwrites = %d\n",
3121 	    mp->mnt_secondary_accwrites);
3122 	db_printf("    mnt_gjprovider = %s\n",
3123 	    mp->mnt_gjprovider != NULL ? mp->mnt_gjprovider : "NULL");
3124 
3125 	db_printf("\n\nList of active vnodes\n");
3126 	TAILQ_FOREACH(vp, &mp->mnt_activevnodelist, v_actfreelist) {
3127 		if (vp->v_type != VMARKER) {
3128 			vn_printf(vp, "vnode ");
3129 			if (db_pager_quit)
3130 				break;
3131 		}
3132 	}
3133 	db_printf("\n\nList of inactive vnodes\n");
3134 	TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
3135 		if (vp->v_type != VMARKER && (vp->v_iflag & VI_ACTIVE) == 0) {
3136 			vn_printf(vp, "vnode ");
3137 			if (db_pager_quit)
3138 				break;
3139 		}
3140 	}
3141 }
3142 #endif	/* DDB */
3143 
3144 /*
3145  * Fill in a struct xvfsconf based on a struct vfsconf.
3146  */
3147 static int
3148 vfsconf2x(struct sysctl_req *req, struct vfsconf *vfsp)
3149 {
3150 	struct xvfsconf xvfsp;
3151 
3152 	bzero(&xvfsp, sizeof(xvfsp));
3153 	strcpy(xvfsp.vfc_name, vfsp->vfc_name);
3154 	xvfsp.vfc_typenum = vfsp->vfc_typenum;
3155 	xvfsp.vfc_refcount = vfsp->vfc_refcount;
3156 	xvfsp.vfc_flags = vfsp->vfc_flags;
3157 	/*
3158 	 * These are unused in userland, we keep them
3159 	 * to not break binary compatibility.
3160 	 */
3161 	xvfsp.vfc_vfsops = NULL;
3162 	xvfsp.vfc_next = NULL;
3163 	return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
3164 }
3165 
3166 #ifdef COMPAT_FREEBSD32
3167 struct xvfsconf32 {
3168 	uint32_t	vfc_vfsops;
3169 	char		vfc_name[MFSNAMELEN];
3170 	int32_t		vfc_typenum;
3171 	int32_t		vfc_refcount;
3172 	int32_t		vfc_flags;
3173 	uint32_t	vfc_next;
3174 };
3175 
3176 static int
3177 vfsconf2x32(struct sysctl_req *req, struct vfsconf *vfsp)
3178 {
3179 	struct xvfsconf32 xvfsp;
3180 
3181 	strcpy(xvfsp.vfc_name, vfsp->vfc_name);
3182 	xvfsp.vfc_typenum = vfsp->vfc_typenum;
3183 	xvfsp.vfc_refcount = vfsp->vfc_refcount;
3184 	xvfsp.vfc_flags = vfsp->vfc_flags;
3185 	xvfsp.vfc_vfsops = 0;
3186 	xvfsp.vfc_next = 0;
3187 	return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
3188 }
3189 #endif
3190 
3191 /*
3192  * Top level filesystem related information gathering.
3193  */
3194 static int
3195 sysctl_vfs_conflist(SYSCTL_HANDLER_ARGS)
3196 {
3197 	struct vfsconf *vfsp;
3198 	int error;
3199 
3200 	error = 0;
3201 	TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
3202 #ifdef COMPAT_FREEBSD32
3203 		if (req->flags & SCTL_MASK32)
3204 			error = vfsconf2x32(req, vfsp);
3205 		else
3206 #endif
3207 			error = vfsconf2x(req, vfsp);
3208 		if (error)
3209 			break;
3210 	}
3211 	return (error);
3212 }
3213 
3214 SYSCTL_PROC(_vfs, OID_AUTO, conflist, CTLTYPE_OPAQUE | CTLFLAG_RD,
3215     NULL, 0, sysctl_vfs_conflist,
3216     "S,xvfsconf", "List of all configured filesystems");
3217 
3218 #ifndef BURN_BRIDGES
3219 static int	sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS);
3220 
3221 static int
3222 vfs_sysctl(SYSCTL_HANDLER_ARGS)
3223 {
3224 	int *name = (int *)arg1 - 1;	/* XXX */
3225 	u_int namelen = arg2 + 1;	/* XXX */
3226 	struct vfsconf *vfsp;
3227 
3228 	log(LOG_WARNING, "userland calling deprecated sysctl, "
3229 	    "please rebuild world\n");
3230 
3231 #if 1 || defined(COMPAT_PRELITE2)
3232 	/* Resolve ambiguity between VFS_VFSCONF and VFS_GENERIC. */
3233 	if (namelen == 1)
3234 		return (sysctl_ovfs_conf(oidp, arg1, arg2, req));
3235 #endif
3236 
3237 	switch (name[1]) {
3238 	case VFS_MAXTYPENUM:
3239 		if (namelen != 2)
3240 			return (ENOTDIR);
3241 		return (SYSCTL_OUT(req, &maxvfsconf, sizeof(int)));
3242 	case VFS_CONF:
3243 		if (namelen != 3)
3244 			return (ENOTDIR);	/* overloaded */
3245 		TAILQ_FOREACH(vfsp, &vfsconf, vfc_list)
3246 			if (vfsp->vfc_typenum == name[2])
3247 				break;
3248 		if (vfsp == NULL)
3249 			return (EOPNOTSUPP);
3250 #ifdef COMPAT_FREEBSD32
3251 		if (req->flags & SCTL_MASK32)
3252 			return (vfsconf2x32(req, vfsp));
3253 		else
3254 #endif
3255 			return (vfsconf2x(req, vfsp));
3256 	}
3257 	return (EOPNOTSUPP);
3258 }
3259 
3260 static SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RD | CTLFLAG_SKIP,
3261     vfs_sysctl, "Generic filesystem");
3262 
3263 #if 1 || defined(COMPAT_PRELITE2)
3264 
3265 static int
3266 sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS)
3267 {
3268 	int error;
3269 	struct vfsconf *vfsp;
3270 	struct ovfsconf ovfs;
3271 
3272 	TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
3273 		bzero(&ovfs, sizeof(ovfs));
3274 		ovfs.vfc_vfsops = vfsp->vfc_vfsops;	/* XXX used as flag */
3275 		strcpy(ovfs.vfc_name, vfsp->vfc_name);
3276 		ovfs.vfc_index = vfsp->vfc_typenum;
3277 		ovfs.vfc_refcount = vfsp->vfc_refcount;
3278 		ovfs.vfc_flags = vfsp->vfc_flags;
3279 		error = SYSCTL_OUT(req, &ovfs, sizeof ovfs);
3280 		if (error)
3281 			return error;
3282 	}
3283 	return 0;
3284 }
3285 
3286 #endif /* 1 || COMPAT_PRELITE2 */
3287 #endif /* !BURN_BRIDGES */
3288 
3289 #define KINFO_VNODESLOP		10
3290 #ifdef notyet
3291 /*
3292  * Dump vnode list (via sysctl).
3293  */
3294 /* ARGSUSED */
3295 static int
3296 sysctl_vnode(SYSCTL_HANDLER_ARGS)
3297 {
3298 	struct xvnode *xvn;
3299 	struct mount *mp;
3300 	struct vnode *vp;
3301 	int error, len, n;
3302 
3303 	/*
3304 	 * Stale numvnodes access is not fatal here.
3305 	 */
3306 	req->lock = 0;
3307 	len = (numvnodes + KINFO_VNODESLOP) * sizeof *xvn;
3308 	if (!req->oldptr)
3309 		/* Make an estimate */
3310 		return (SYSCTL_OUT(req, 0, len));
3311 
3312 	error = sysctl_wire_old_buffer(req, 0);
3313 	if (error != 0)
3314 		return (error);
3315 	xvn = malloc(len, M_TEMP, M_ZERO | M_WAITOK);
3316 	n = 0;
3317 	mtx_lock(&mountlist_mtx);
3318 	TAILQ_FOREACH(mp, &mountlist, mnt_list) {
3319 		if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK))
3320 			continue;
3321 		MNT_ILOCK(mp);
3322 		TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
3323 			if (n == len)
3324 				break;
3325 			vref(vp);
3326 			xvn[n].xv_size = sizeof *xvn;
3327 			xvn[n].xv_vnode = vp;
3328 			xvn[n].xv_id = 0;	/* XXX compat */
3329 #define XV_COPY(field) xvn[n].xv_##field = vp->v_##field
3330 			XV_COPY(usecount);
3331 			XV_COPY(writecount);
3332 			XV_COPY(holdcnt);
3333 			XV_COPY(mount);
3334 			XV_COPY(numoutput);
3335 			XV_COPY(type);
3336 #undef XV_COPY
3337 			xvn[n].xv_flag = vp->v_vflag;
3338 
3339 			switch (vp->v_type) {
3340 			case VREG:
3341 			case VDIR:
3342 			case VLNK:
3343 				break;
3344 			case VBLK:
3345 			case VCHR:
3346 				if (vp->v_rdev == NULL) {
3347 					vrele(vp);
3348 					continue;
3349 				}
3350 				xvn[n].xv_dev = dev2udev(vp->v_rdev);
3351 				break;
3352 			case VSOCK:
3353 				xvn[n].xv_socket = vp->v_socket;
3354 				break;
3355 			case VFIFO:
3356 				xvn[n].xv_fifo = vp->v_fifoinfo;
3357 				break;
3358 			case VNON:
3359 			case VBAD:
3360 			default:
3361 				/* shouldn't happen? */
3362 				vrele(vp);
3363 				continue;
3364 			}
3365 			vrele(vp);
3366 			++n;
3367 		}
3368 		MNT_IUNLOCK(mp);
3369 		mtx_lock(&mountlist_mtx);
3370 		vfs_unbusy(mp);
3371 		if (n == len)
3372 			break;
3373 	}
3374 	mtx_unlock(&mountlist_mtx);
3375 
3376 	error = SYSCTL_OUT(req, xvn, n * sizeof *xvn);
3377 	free(xvn, M_TEMP);
3378 	return (error);
3379 }
3380 
3381 SYSCTL_PROC(_kern, KERN_VNODE, vnode, CTLTYPE_OPAQUE|CTLFLAG_RD,
3382     0, 0, sysctl_vnode, "S,xvnode", "");
3383 #endif
3384 
3385 /*
3386  * Unmount all filesystems. The list is traversed in reverse order
3387  * of mounting to avoid dependencies.
3388  */
3389 void
3390 vfs_unmountall(void)
3391 {
3392 	struct mount *mp;
3393 	struct thread *td;
3394 	int error;
3395 
3396 	CTR1(KTR_VFS, "%s: unmounting all filesystems", __func__);
3397 	td = curthread;
3398 
3399 	/*
3400 	 * Since this only runs when rebooting, it is not interlocked.
3401 	 */
3402 	while(!TAILQ_EMPTY(&mountlist)) {
3403 		mp = TAILQ_LAST(&mountlist, mntlist);
3404 		error = dounmount(mp, MNT_FORCE, td);
3405 		if (error) {
3406 			TAILQ_REMOVE(&mountlist, mp, mnt_list);
3407 			/*
3408 			 * XXX: Due to the way in which we mount the root
3409 			 * file system off of devfs, devfs will generate a
3410 			 * "busy" warning when we try to unmount it before
3411 			 * the root.  Don't print a warning as a result in
3412 			 * order to avoid false positive errors that may
3413 			 * cause needless upset.
3414 			 */
3415 			if (strcmp(mp->mnt_vfc->vfc_name, "devfs") != 0) {
3416 				printf("unmount of %s failed (",
3417 				    mp->mnt_stat.f_mntonname);
3418 				if (error == EBUSY)
3419 					printf("BUSY)\n");
3420 				else
3421 					printf("%d)\n", error);
3422 			}
3423 		} else {
3424 			/* The unmount has removed mp from the mountlist */
3425 		}
3426 	}
3427 }
3428 
3429 /*
3430  * perform msync on all vnodes under a mount point
3431  * the mount point must be locked.
3432  */
3433 void
3434 vfs_msync(struct mount *mp, int flags)
3435 {
3436 	struct vnode *vp, *mvp;
3437 	struct vm_object *obj;
3438 
3439 	CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
3440 	MNT_VNODE_FOREACH_ACTIVE(vp, mp, mvp) {
3441 		obj = vp->v_object;
3442 		if (obj != NULL && (obj->flags & OBJ_MIGHTBEDIRTY) != 0 &&
3443 		    (flags == MNT_WAIT || VOP_ISLOCKED(vp) == 0)) {
3444 			if (!vget(vp,
3445 			    LK_EXCLUSIVE | LK_RETRY | LK_INTERLOCK,
3446 			    curthread)) {
3447 				if (vp->v_vflag & VV_NOSYNC) {	/* unlinked */
3448 					vput(vp);
3449 					continue;
3450 				}
3451 
3452 				obj = vp->v_object;
3453 				if (obj != NULL) {
3454 					VM_OBJECT_WLOCK(obj);
3455 					vm_object_page_clean(obj, 0, 0,
3456 					    flags == MNT_WAIT ?
3457 					    OBJPC_SYNC : OBJPC_NOSYNC);
3458 					VM_OBJECT_WUNLOCK(obj);
3459 				}
3460 				vput(vp);
3461 			}
3462 		} else
3463 			VI_UNLOCK(vp);
3464 	}
3465 }
3466 
3467 static void
3468 destroy_vpollinfo_free(struct vpollinfo *vi)
3469 {
3470 
3471 	knlist_destroy(&vi->vpi_selinfo.si_note);
3472 	mtx_destroy(&vi->vpi_lock);
3473 	uma_zfree(vnodepoll_zone, vi);
3474 }
3475 
3476 static void
3477 destroy_vpollinfo(struct vpollinfo *vi)
3478 {
3479 
3480 	knlist_clear(&vi->vpi_selinfo.si_note, 1);
3481 	seldrain(&vi->vpi_selinfo);
3482 	destroy_vpollinfo_free(vi);
3483 }
3484 
3485 /*
3486  * Initalize per-vnode helper structure to hold poll-related state.
3487  */
3488 void
3489 v_addpollinfo(struct vnode *vp)
3490 {
3491 	struct vpollinfo *vi;
3492 
3493 	if (vp->v_pollinfo != NULL)
3494 		return;
3495 	vi = uma_zalloc(vnodepoll_zone, M_WAITOK);
3496 	mtx_init(&vi->vpi_lock, "vnode pollinfo", NULL, MTX_DEF);
3497 	knlist_init(&vi->vpi_selinfo.si_note, vp, vfs_knllock,
3498 	    vfs_knlunlock, vfs_knl_assert_locked, vfs_knl_assert_unlocked);
3499 	VI_LOCK(vp);
3500 	if (vp->v_pollinfo != NULL) {
3501 		VI_UNLOCK(vp);
3502 		destroy_vpollinfo_free(vi);
3503 		return;
3504 	}
3505 	vp->v_pollinfo = vi;
3506 	VI_UNLOCK(vp);
3507 }
3508 
3509 /*
3510  * Record a process's interest in events which might happen to
3511  * a vnode.  Because poll uses the historic select-style interface
3512  * internally, this routine serves as both the ``check for any
3513  * pending events'' and the ``record my interest in future events''
3514  * functions.  (These are done together, while the lock is held,
3515  * to avoid race conditions.)
3516  */
3517 int
3518 vn_pollrecord(struct vnode *vp, struct thread *td, int events)
3519 {
3520 
3521 	v_addpollinfo(vp);
3522 	mtx_lock(&vp->v_pollinfo->vpi_lock);
3523 	if (vp->v_pollinfo->vpi_revents & events) {
3524 		/*
3525 		 * This leaves events we are not interested
3526 		 * in available for the other process which
3527 		 * which presumably had requested them
3528 		 * (otherwise they would never have been
3529 		 * recorded).
3530 		 */
3531 		events &= vp->v_pollinfo->vpi_revents;
3532 		vp->v_pollinfo->vpi_revents &= ~events;
3533 
3534 		mtx_unlock(&vp->v_pollinfo->vpi_lock);
3535 		return (events);
3536 	}
3537 	vp->v_pollinfo->vpi_events |= events;
3538 	selrecord(td, &vp->v_pollinfo->vpi_selinfo);
3539 	mtx_unlock(&vp->v_pollinfo->vpi_lock);
3540 	return (0);
3541 }
3542 
3543 /*
3544  * Routine to create and manage a filesystem syncer vnode.
3545  */
3546 #define sync_close ((int (*)(struct  vop_close_args *))nullop)
3547 static int	sync_fsync(struct  vop_fsync_args *);
3548 static int	sync_inactive(struct  vop_inactive_args *);
3549 static int	sync_reclaim(struct  vop_reclaim_args *);
3550 
3551 static struct vop_vector sync_vnodeops = {
3552 	.vop_bypass =	VOP_EOPNOTSUPP,
3553 	.vop_close =	sync_close,		/* close */
3554 	.vop_fsync =	sync_fsync,		/* fsync */
3555 	.vop_inactive =	sync_inactive,	/* inactive */
3556 	.vop_reclaim =	sync_reclaim,	/* reclaim */
3557 	.vop_lock1 =	vop_stdlock,	/* lock */
3558 	.vop_unlock =	vop_stdunlock,	/* unlock */
3559 	.vop_islocked =	vop_stdislocked,	/* islocked */
3560 };
3561 
3562 /*
3563  * Create a new filesystem syncer vnode for the specified mount point.
3564  */
3565 void
3566 vfs_allocate_syncvnode(struct mount *mp)
3567 {
3568 	struct vnode *vp;
3569 	struct bufobj *bo;
3570 	static long start, incr, next;
3571 	int error;
3572 
3573 	/* Allocate a new vnode */
3574 	error = getnewvnode("syncer", mp, &sync_vnodeops, &vp);
3575 	if (error != 0)
3576 		panic("vfs_allocate_syncvnode: getnewvnode() failed");
3577 	vp->v_type = VNON;
3578 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
3579 	vp->v_vflag |= VV_FORCEINSMQ;
3580 	error = insmntque(vp, mp);
3581 	if (error != 0)
3582 		panic("vfs_allocate_syncvnode: insmntque() failed");
3583 	vp->v_vflag &= ~VV_FORCEINSMQ;
3584 	VOP_UNLOCK(vp, 0);
3585 	/*
3586 	 * Place the vnode onto the syncer worklist. We attempt to
3587 	 * scatter them about on the list so that they will go off
3588 	 * at evenly distributed times even if all the filesystems
3589 	 * are mounted at once.
3590 	 */
3591 	next += incr;
3592 	if (next == 0 || next > syncer_maxdelay) {
3593 		start /= 2;
3594 		incr /= 2;
3595 		if (start == 0) {
3596 			start = syncer_maxdelay / 2;
3597 			incr = syncer_maxdelay;
3598 		}
3599 		next = start;
3600 	}
3601 	bo = &vp->v_bufobj;
3602 	BO_LOCK(bo);
3603 	vn_syncer_add_to_worklist(bo, syncdelay > 0 ? next % syncdelay : 0);
3604 	/* XXX - vn_syncer_add_to_worklist() also grabs and drops sync_mtx. */
3605 	mtx_lock(&sync_mtx);
3606 	sync_vnode_count++;
3607 	if (mp->mnt_syncer == NULL) {
3608 		mp->mnt_syncer = vp;
3609 		vp = NULL;
3610 	}
3611 	mtx_unlock(&sync_mtx);
3612 	BO_UNLOCK(bo);
3613 	if (vp != NULL) {
3614 		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
3615 		vgone(vp);
3616 		vput(vp);
3617 	}
3618 }
3619 
3620 void
3621 vfs_deallocate_syncvnode(struct mount *mp)
3622 {
3623 	struct vnode *vp;
3624 
3625 	mtx_lock(&sync_mtx);
3626 	vp = mp->mnt_syncer;
3627 	if (vp != NULL)
3628 		mp->mnt_syncer = NULL;
3629 	mtx_unlock(&sync_mtx);
3630 	if (vp != NULL)
3631 		vrele(vp);
3632 }
3633 
3634 /*
3635  * Do a lazy sync of the filesystem.
3636  */
3637 static int
3638 sync_fsync(struct vop_fsync_args *ap)
3639 {
3640 	struct vnode *syncvp = ap->a_vp;
3641 	struct mount *mp = syncvp->v_mount;
3642 	int error, save;
3643 	struct bufobj *bo;
3644 
3645 	/*
3646 	 * We only need to do something if this is a lazy evaluation.
3647 	 */
3648 	if (ap->a_waitfor != MNT_LAZY)
3649 		return (0);
3650 
3651 	/*
3652 	 * Move ourselves to the back of the sync list.
3653 	 */
3654 	bo = &syncvp->v_bufobj;
3655 	BO_LOCK(bo);
3656 	vn_syncer_add_to_worklist(bo, syncdelay);
3657 	BO_UNLOCK(bo);
3658 
3659 	/*
3660 	 * Walk the list of vnodes pushing all that are dirty and
3661 	 * not already on the sync list.
3662 	 */
3663 	mtx_lock(&mountlist_mtx);
3664 	if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK) != 0) {
3665 		mtx_unlock(&mountlist_mtx);
3666 		return (0);
3667 	}
3668 	if (vn_start_write(NULL, &mp, V_NOWAIT) != 0) {
3669 		vfs_unbusy(mp);
3670 		return (0);
3671 	}
3672 	save = curthread_pflags_set(TDP_SYNCIO);
3673 	vfs_msync(mp, MNT_NOWAIT);
3674 	error = VFS_SYNC(mp, MNT_LAZY);
3675 	curthread_pflags_restore(save);
3676 	vn_finished_write(mp);
3677 	vfs_unbusy(mp);
3678 	return (error);
3679 }
3680 
3681 /*
3682  * The syncer vnode is no referenced.
3683  */
3684 static int
3685 sync_inactive(struct vop_inactive_args *ap)
3686 {
3687 
3688 	vgone(ap->a_vp);
3689 	return (0);
3690 }
3691 
3692 /*
3693  * The syncer vnode is no longer needed and is being decommissioned.
3694  *
3695  * Modifications to the worklist must be protected by sync_mtx.
3696  */
3697 static int
3698 sync_reclaim(struct vop_reclaim_args *ap)
3699 {
3700 	struct vnode *vp = ap->a_vp;
3701 	struct bufobj *bo;
3702 
3703 	bo = &vp->v_bufobj;
3704 	BO_LOCK(bo);
3705 	mtx_lock(&sync_mtx);
3706 	if (vp->v_mount->mnt_syncer == vp)
3707 		vp->v_mount->mnt_syncer = NULL;
3708 	if (bo->bo_flag & BO_ONWORKLST) {
3709 		LIST_REMOVE(bo, bo_synclist);
3710 		syncer_worklist_len--;
3711 		sync_vnode_count--;
3712 		bo->bo_flag &= ~BO_ONWORKLST;
3713 	}
3714 	mtx_unlock(&sync_mtx);
3715 	BO_UNLOCK(bo);
3716 
3717 	return (0);
3718 }
3719 
3720 /*
3721  * Check if vnode represents a disk device
3722  */
3723 int
3724 vn_isdisk(struct vnode *vp, int *errp)
3725 {
3726 	int error;
3727 
3728 	error = 0;
3729 	dev_lock();
3730 	if (vp->v_type != VCHR)
3731 		error = ENOTBLK;
3732 	else if (vp->v_rdev == NULL)
3733 		error = ENXIO;
3734 	else if (vp->v_rdev->si_devsw == NULL)
3735 		error = ENXIO;
3736 	else if (!(vp->v_rdev->si_devsw->d_flags & D_DISK))
3737 		error = ENOTBLK;
3738 	dev_unlock();
3739 	if (errp != NULL)
3740 		*errp = error;
3741 	return (error == 0);
3742 }
3743 
3744 /*
3745  * Common filesystem object access control check routine.  Accepts a
3746  * vnode's type, "mode", uid and gid, requested access mode, credentials,
3747  * and optional call-by-reference privused argument allowing vaccess()
3748  * to indicate to the caller whether privilege was used to satisfy the
3749  * request (obsoleted).  Returns 0 on success, or an errno on failure.
3750  */
3751 int
3752 vaccess(enum vtype type, mode_t file_mode, uid_t file_uid, gid_t file_gid,
3753     accmode_t accmode, struct ucred *cred, int *privused)
3754 {
3755 	accmode_t dac_granted;
3756 	accmode_t priv_granted;
3757 
3758 	KASSERT((accmode & ~(VEXEC | VWRITE | VREAD | VADMIN | VAPPEND)) == 0,
3759 	    ("invalid bit in accmode"));
3760 	KASSERT((accmode & VAPPEND) == 0 || (accmode & VWRITE),
3761 	    ("VAPPEND without VWRITE"));
3762 
3763 	/*
3764 	 * Look for a normal, non-privileged way to access the file/directory
3765 	 * as requested.  If it exists, go with that.
3766 	 */
3767 
3768 	if (privused != NULL)
3769 		*privused = 0;
3770 
3771 	dac_granted = 0;
3772 
3773 	/* Check the owner. */
3774 	if (cred->cr_uid == file_uid) {
3775 		dac_granted |= VADMIN;
3776 		if (file_mode & S_IXUSR)
3777 			dac_granted |= VEXEC;
3778 		if (file_mode & S_IRUSR)
3779 			dac_granted |= VREAD;
3780 		if (file_mode & S_IWUSR)
3781 			dac_granted |= (VWRITE | VAPPEND);
3782 
3783 		if ((accmode & dac_granted) == accmode)
3784 			return (0);
3785 
3786 		goto privcheck;
3787 	}
3788 
3789 	/* Otherwise, check the groups (first match) */
3790 	if (groupmember(file_gid, cred)) {
3791 		if (file_mode & S_IXGRP)
3792 			dac_granted |= VEXEC;
3793 		if (file_mode & S_IRGRP)
3794 			dac_granted |= VREAD;
3795 		if (file_mode & S_IWGRP)
3796 			dac_granted |= (VWRITE | VAPPEND);
3797 
3798 		if ((accmode & dac_granted) == accmode)
3799 			return (0);
3800 
3801 		goto privcheck;
3802 	}
3803 
3804 	/* Otherwise, check everyone else. */
3805 	if (file_mode & S_IXOTH)
3806 		dac_granted |= VEXEC;
3807 	if (file_mode & S_IROTH)
3808 		dac_granted |= VREAD;
3809 	if (file_mode & S_IWOTH)
3810 		dac_granted |= (VWRITE | VAPPEND);
3811 	if ((accmode & dac_granted) == accmode)
3812 		return (0);
3813 
3814 privcheck:
3815 	/*
3816 	 * Build a privilege mask to determine if the set of privileges
3817 	 * satisfies the requirements when combined with the granted mask
3818 	 * from above.  For each privilege, if the privilege is required,
3819 	 * bitwise or the request type onto the priv_granted mask.
3820 	 */
3821 	priv_granted = 0;
3822 
3823 	if (type == VDIR) {
3824 		/*
3825 		 * For directories, use PRIV_VFS_LOOKUP to satisfy VEXEC
3826 		 * requests, instead of PRIV_VFS_EXEC.
3827 		 */
3828 		if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
3829 		    !priv_check_cred(cred, PRIV_VFS_LOOKUP, 0))
3830 			priv_granted |= VEXEC;
3831 	} else {
3832 		/*
3833 		 * Ensure that at least one execute bit is on. Otherwise,
3834 		 * a privileged user will always succeed, and we don't want
3835 		 * this to happen unless the file really is executable.
3836 		 */
3837 		if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
3838 		    (file_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0 &&
3839 		    !priv_check_cred(cred, PRIV_VFS_EXEC, 0))
3840 			priv_granted |= VEXEC;
3841 	}
3842 
3843 	if ((accmode & VREAD) && ((dac_granted & VREAD) == 0) &&
3844 	    !priv_check_cred(cred, PRIV_VFS_READ, 0))
3845 		priv_granted |= VREAD;
3846 
3847 	if ((accmode & VWRITE) && ((dac_granted & VWRITE) == 0) &&
3848 	    !priv_check_cred(cred, PRIV_VFS_WRITE, 0))
3849 		priv_granted |= (VWRITE | VAPPEND);
3850 
3851 	if ((accmode & VADMIN) && ((dac_granted & VADMIN) == 0) &&
3852 	    !priv_check_cred(cred, PRIV_VFS_ADMIN, 0))
3853 		priv_granted |= VADMIN;
3854 
3855 	if ((accmode & (priv_granted | dac_granted)) == accmode) {
3856 		/* XXX audit: privilege used */
3857 		if (privused != NULL)
3858 			*privused = 1;
3859 		return (0);
3860 	}
3861 
3862 	return ((accmode & VADMIN) ? EPERM : EACCES);
3863 }
3864 
3865 /*
3866  * Credential check based on process requesting service, and per-attribute
3867  * permissions.
3868  */
3869 int
3870 extattr_check_cred(struct vnode *vp, int attrnamespace, struct ucred *cred,
3871     struct thread *td, accmode_t accmode)
3872 {
3873 
3874 	/*
3875 	 * Kernel-invoked always succeeds.
3876 	 */
3877 	if (cred == NOCRED)
3878 		return (0);
3879 
3880 	/*
3881 	 * Do not allow privileged processes in jail to directly manipulate
3882 	 * system attributes.
3883 	 */
3884 	switch (attrnamespace) {
3885 	case EXTATTR_NAMESPACE_SYSTEM:
3886 		/* Potentially should be: return (EPERM); */
3887 		return (priv_check_cred(cred, PRIV_VFS_EXTATTR_SYSTEM, 0));
3888 	case EXTATTR_NAMESPACE_USER:
3889 		return (VOP_ACCESS(vp, accmode, cred, td));
3890 	default:
3891 		return (EPERM);
3892 	}
3893 }
3894 
3895 #ifdef DEBUG_VFS_LOCKS
3896 /*
3897  * This only exists to supress warnings from unlocked specfs accesses.  It is
3898  * no longer ok to have an unlocked VFS.
3899  */
3900 #define	IGNORE_LOCK(vp) (panicstr != NULL || (vp) == NULL ||		\
3901 	(vp)->v_type == VCHR ||	(vp)->v_type == VBAD)
3902 
3903 int vfs_badlock_ddb = 1;	/* Drop into debugger on violation. */
3904 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_ddb, CTLFLAG_RW, &vfs_badlock_ddb, 0,
3905     "Drop into debugger on lock violation");
3906 
3907 int vfs_badlock_mutex = 1;	/* Check for interlock across VOPs. */
3908 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_mutex, CTLFLAG_RW, &vfs_badlock_mutex,
3909     0, "Check for interlock across VOPs");
3910 
3911 int vfs_badlock_print = 1;	/* Print lock violations. */
3912 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_print, CTLFLAG_RW, &vfs_badlock_print,
3913     0, "Print lock violations");
3914 
3915 #ifdef KDB
3916 int vfs_badlock_backtrace = 1;	/* Print backtrace at lock violations. */
3917 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_backtrace, CTLFLAG_RW,
3918     &vfs_badlock_backtrace, 0, "Print backtrace at lock violations");
3919 #endif
3920 
3921 static void
3922 vfs_badlock(const char *msg, const char *str, struct vnode *vp)
3923 {
3924 
3925 #ifdef KDB
3926 	if (vfs_badlock_backtrace)
3927 		kdb_backtrace();
3928 #endif
3929 	if (vfs_badlock_print)
3930 		printf("%s: %p %s\n", str, (void *)vp, msg);
3931 	if (vfs_badlock_ddb)
3932 		kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
3933 }
3934 
3935 void
3936 assert_vi_locked(struct vnode *vp, const char *str)
3937 {
3938 
3939 	if (vfs_badlock_mutex && !mtx_owned(VI_MTX(vp)))
3940 		vfs_badlock("interlock is not locked but should be", str, vp);
3941 }
3942 
3943 void
3944 assert_vi_unlocked(struct vnode *vp, const char *str)
3945 {
3946 
3947 	if (vfs_badlock_mutex && mtx_owned(VI_MTX(vp)))
3948 		vfs_badlock("interlock is locked but should not be", str, vp);
3949 }
3950 
3951 void
3952 assert_vop_locked(struct vnode *vp, const char *str)
3953 {
3954 	int locked;
3955 
3956 	if (!IGNORE_LOCK(vp)) {
3957 		locked = VOP_ISLOCKED(vp);
3958 		if (locked == 0 || locked == LK_EXCLOTHER)
3959 			vfs_badlock("is not locked but should be", str, vp);
3960 	}
3961 }
3962 
3963 void
3964 assert_vop_unlocked(struct vnode *vp, const char *str)
3965 {
3966 
3967 	if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) == LK_EXCLUSIVE)
3968 		vfs_badlock("is locked but should not be", str, vp);
3969 }
3970 
3971 void
3972 assert_vop_elocked(struct vnode *vp, const char *str)
3973 {
3974 
3975 	if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) != LK_EXCLUSIVE)
3976 		vfs_badlock("is not exclusive locked but should be", str, vp);
3977 }
3978 
3979 #if 0
3980 void
3981 assert_vop_elocked_other(struct vnode *vp, const char *str)
3982 {
3983 
3984 	if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) != LK_EXCLOTHER)
3985 		vfs_badlock("is not exclusive locked by another thread",
3986 		    str, vp);
3987 }
3988 
3989 void
3990 assert_vop_slocked(struct vnode *vp, const char *str)
3991 {
3992 
3993 	if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) != LK_SHARED)
3994 		vfs_badlock("is not locked shared but should be", str, vp);
3995 }
3996 #endif /* 0 */
3997 #endif /* DEBUG_VFS_LOCKS */
3998 
3999 void
4000 vop_rename_fail(struct vop_rename_args *ap)
4001 {
4002 
4003 	if (ap->a_tvp != NULL)
4004 		vput(ap->a_tvp);
4005 	if (ap->a_tdvp == ap->a_tvp)
4006 		vrele(ap->a_tdvp);
4007 	else
4008 		vput(ap->a_tdvp);
4009 	vrele(ap->a_fdvp);
4010 	vrele(ap->a_fvp);
4011 }
4012 
4013 void
4014 vop_rename_pre(void *ap)
4015 {
4016 	struct vop_rename_args *a = ap;
4017 
4018 #ifdef DEBUG_VFS_LOCKS
4019 	if (a->a_tvp)
4020 		ASSERT_VI_UNLOCKED(a->a_tvp, "VOP_RENAME");
4021 	ASSERT_VI_UNLOCKED(a->a_tdvp, "VOP_RENAME");
4022 	ASSERT_VI_UNLOCKED(a->a_fvp, "VOP_RENAME");
4023 	ASSERT_VI_UNLOCKED(a->a_fdvp, "VOP_RENAME");
4024 
4025 	/* Check the source (from). */
4026 	if (a->a_tdvp->v_vnlock != a->a_fdvp->v_vnlock &&
4027 	    (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fdvp->v_vnlock))
4028 		ASSERT_VOP_UNLOCKED(a->a_fdvp, "vop_rename: fdvp locked");
4029 	if (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fvp->v_vnlock)
4030 		ASSERT_VOP_UNLOCKED(a->a_fvp, "vop_rename: fvp locked");
4031 
4032 	/* Check the target. */
4033 	if (a->a_tvp)
4034 		ASSERT_VOP_LOCKED(a->a_tvp, "vop_rename: tvp not locked");
4035 	ASSERT_VOP_LOCKED(a->a_tdvp, "vop_rename: tdvp not locked");
4036 #endif
4037 	if (a->a_tdvp != a->a_fdvp)
4038 		vhold(a->a_fdvp);
4039 	if (a->a_tvp != a->a_fvp)
4040 		vhold(a->a_fvp);
4041 	vhold(a->a_tdvp);
4042 	if (a->a_tvp)
4043 		vhold(a->a_tvp);
4044 }
4045 
4046 void
4047 vop_strategy_pre(void *ap)
4048 {
4049 #ifdef DEBUG_VFS_LOCKS
4050 	struct vop_strategy_args *a;
4051 	struct buf *bp;
4052 
4053 	a = ap;
4054 	bp = a->a_bp;
4055 
4056 	/*
4057 	 * Cluster ops lock their component buffers but not the IO container.
4058 	 */
4059 	if ((bp->b_flags & B_CLUSTER) != 0)
4060 		return;
4061 
4062 	if (panicstr == NULL && !BUF_ISLOCKED(bp)) {
4063 		if (vfs_badlock_print)
4064 			printf(
4065 			    "VOP_STRATEGY: bp is not locked but should be\n");
4066 		if (vfs_badlock_ddb)
4067 			kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
4068 	}
4069 #endif
4070 }
4071 
4072 void
4073 vop_lock_pre(void *ap)
4074 {
4075 #ifdef DEBUG_VFS_LOCKS
4076 	struct vop_lock1_args *a = ap;
4077 
4078 	if ((a->a_flags & LK_INTERLOCK) == 0)
4079 		ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
4080 	else
4081 		ASSERT_VI_LOCKED(a->a_vp, "VOP_LOCK");
4082 #endif
4083 }
4084 
4085 void
4086 vop_lock_post(void *ap, int rc)
4087 {
4088 #ifdef DEBUG_VFS_LOCKS
4089 	struct vop_lock1_args *a = ap;
4090 
4091 	ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
4092 	if (rc == 0 && (a->a_flags & LK_EXCLOTHER) == 0)
4093 		ASSERT_VOP_LOCKED(a->a_vp, "VOP_LOCK");
4094 #endif
4095 }
4096 
4097 void
4098 vop_unlock_pre(void *ap)
4099 {
4100 #ifdef DEBUG_VFS_LOCKS
4101 	struct vop_unlock_args *a = ap;
4102 
4103 	if (a->a_flags & LK_INTERLOCK)
4104 		ASSERT_VI_LOCKED(a->a_vp, "VOP_UNLOCK");
4105 	ASSERT_VOP_LOCKED(a->a_vp, "VOP_UNLOCK");
4106 #endif
4107 }
4108 
4109 void
4110 vop_unlock_post(void *ap, int rc)
4111 {
4112 #ifdef DEBUG_VFS_LOCKS
4113 	struct vop_unlock_args *a = ap;
4114 
4115 	if (a->a_flags & LK_INTERLOCK)
4116 		ASSERT_VI_UNLOCKED(a->a_vp, "VOP_UNLOCK");
4117 #endif
4118 }
4119 
4120 void
4121 vop_create_post(void *ap, int rc)
4122 {
4123 	struct vop_create_args *a = ap;
4124 
4125 	if (!rc)
4126 		VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
4127 }
4128 
4129 void
4130 vop_deleteextattr_post(void *ap, int rc)
4131 {
4132 	struct vop_deleteextattr_args *a = ap;
4133 
4134 	if (!rc)
4135 		VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
4136 }
4137 
4138 void
4139 vop_link_post(void *ap, int rc)
4140 {
4141 	struct vop_link_args *a = ap;
4142 
4143 	if (!rc) {
4144 		VFS_KNOTE_LOCKED(a->a_vp, NOTE_LINK);
4145 		VFS_KNOTE_LOCKED(a->a_tdvp, NOTE_WRITE);
4146 	}
4147 }
4148 
4149 void
4150 vop_mkdir_post(void *ap, int rc)
4151 {
4152 	struct vop_mkdir_args *a = ap;
4153 
4154 	if (!rc)
4155 		VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE | NOTE_LINK);
4156 }
4157 
4158 void
4159 vop_mknod_post(void *ap, int rc)
4160 {
4161 	struct vop_mknod_args *a = ap;
4162 
4163 	if (!rc)
4164 		VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
4165 }
4166 
4167 void
4168 vop_remove_post(void *ap, int rc)
4169 {
4170 	struct vop_remove_args *a = ap;
4171 
4172 	if (!rc) {
4173 		VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
4174 		VFS_KNOTE_LOCKED(a->a_vp, NOTE_DELETE);
4175 	}
4176 }
4177 
4178 void
4179 vop_rename_post(void *ap, int rc)
4180 {
4181 	struct vop_rename_args *a = ap;
4182 
4183 	if (!rc) {
4184 		VFS_KNOTE_UNLOCKED(a->a_fdvp, NOTE_WRITE);
4185 		VFS_KNOTE_UNLOCKED(a->a_tdvp, NOTE_WRITE);
4186 		VFS_KNOTE_UNLOCKED(a->a_fvp, NOTE_RENAME);
4187 		if (a->a_tvp)
4188 			VFS_KNOTE_UNLOCKED(a->a_tvp, NOTE_DELETE);
4189 	}
4190 	if (a->a_tdvp != a->a_fdvp)
4191 		vdrop(a->a_fdvp);
4192 	if (a->a_tvp != a->a_fvp)
4193 		vdrop(a->a_fvp);
4194 	vdrop(a->a_tdvp);
4195 	if (a->a_tvp)
4196 		vdrop(a->a_tvp);
4197 }
4198 
4199 void
4200 vop_rmdir_post(void *ap, int rc)
4201 {
4202 	struct vop_rmdir_args *a = ap;
4203 
4204 	if (!rc) {
4205 		VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE | NOTE_LINK);
4206 		VFS_KNOTE_LOCKED(a->a_vp, NOTE_DELETE);
4207 	}
4208 }
4209 
4210 void
4211 vop_setattr_post(void *ap, int rc)
4212 {
4213 	struct vop_setattr_args *a = ap;
4214 
4215 	if (!rc)
4216 		VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
4217 }
4218 
4219 void
4220 vop_setextattr_post(void *ap, int rc)
4221 {
4222 	struct vop_setextattr_args *a = ap;
4223 
4224 	if (!rc)
4225 		VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
4226 }
4227 
4228 void
4229 vop_symlink_post(void *ap, int rc)
4230 {
4231 	struct vop_symlink_args *a = ap;
4232 
4233 	if (!rc)
4234 		VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
4235 }
4236 
4237 static struct knlist fs_knlist;
4238 
4239 static void
4240 vfs_event_init(void *arg)
4241 {
4242 	knlist_init_mtx(&fs_knlist, NULL);
4243 }
4244 /* XXX - correct order? */
4245 SYSINIT(vfs_knlist, SI_SUB_VFS, SI_ORDER_ANY, vfs_event_init, NULL);
4246 
4247 void
4248 vfs_event_signal(fsid_t *fsid, uint32_t event, intptr_t data __unused)
4249 {
4250 
4251 	KNOTE_UNLOCKED(&fs_knlist, event);
4252 }
4253 
4254 static int	filt_fsattach(struct knote *kn);
4255 static void	filt_fsdetach(struct knote *kn);
4256 static int	filt_fsevent(struct knote *kn, long hint);
4257 
4258 struct filterops fs_filtops = {
4259 	.f_isfd = 0,
4260 	.f_attach = filt_fsattach,
4261 	.f_detach = filt_fsdetach,
4262 	.f_event = filt_fsevent
4263 };
4264 
4265 static int
4266 filt_fsattach(struct knote *kn)
4267 {
4268 
4269 	kn->kn_flags |= EV_CLEAR;
4270 	knlist_add(&fs_knlist, kn, 0);
4271 	return (0);
4272 }
4273 
4274 static void
4275 filt_fsdetach(struct knote *kn)
4276 {
4277 
4278 	knlist_remove(&fs_knlist, kn, 0);
4279 }
4280 
4281 static int
4282 filt_fsevent(struct knote *kn, long hint)
4283 {
4284 
4285 	kn->kn_fflags |= hint;
4286 	return (kn->kn_fflags != 0);
4287 }
4288 
4289 static int
4290 sysctl_vfs_ctl(SYSCTL_HANDLER_ARGS)
4291 {
4292 	struct vfsidctl vc;
4293 	int error;
4294 	struct mount *mp;
4295 
4296 	error = SYSCTL_IN(req, &vc, sizeof(vc));
4297 	if (error)
4298 		return (error);
4299 	if (vc.vc_vers != VFS_CTL_VERS1)
4300 		return (EINVAL);
4301 	mp = vfs_getvfs(&vc.vc_fsid);
4302 	if (mp == NULL)
4303 		return (ENOENT);
4304 	/* ensure that a specific sysctl goes to the right filesystem. */
4305 	if (strcmp(vc.vc_fstypename, "*") != 0 &&
4306 	    strcmp(vc.vc_fstypename, mp->mnt_vfc->vfc_name) != 0) {
4307 		vfs_rel(mp);
4308 		return (EINVAL);
4309 	}
4310 	VCTLTOREQ(&vc, req);
4311 	error = VFS_SYSCTL(mp, vc.vc_op, req);
4312 	vfs_rel(mp);
4313 	return (error);
4314 }
4315 
4316 SYSCTL_PROC(_vfs, OID_AUTO, ctl, CTLTYPE_OPAQUE | CTLFLAG_WR,
4317     NULL, 0, sysctl_vfs_ctl, "",
4318     "Sysctl by fsid");
4319 
4320 /*
4321  * Function to initialize a va_filerev field sensibly.
4322  * XXX: Wouldn't a random number make a lot more sense ??
4323  */
4324 u_quad_t
4325 init_va_filerev(void)
4326 {
4327 	struct bintime bt;
4328 
4329 	getbinuptime(&bt);
4330 	return (((u_quad_t)bt.sec << 32LL) | (bt.frac >> 32LL));
4331 }
4332 
4333 static int	filt_vfsread(struct knote *kn, long hint);
4334 static int	filt_vfswrite(struct knote *kn, long hint);
4335 static int	filt_vfsvnode(struct knote *kn, long hint);
4336 static void	filt_vfsdetach(struct knote *kn);
4337 static struct filterops vfsread_filtops = {
4338 	.f_isfd = 1,
4339 	.f_detach = filt_vfsdetach,
4340 	.f_event = filt_vfsread
4341 };
4342 static struct filterops vfswrite_filtops = {
4343 	.f_isfd = 1,
4344 	.f_detach = filt_vfsdetach,
4345 	.f_event = filt_vfswrite
4346 };
4347 static struct filterops vfsvnode_filtops = {
4348 	.f_isfd = 1,
4349 	.f_detach = filt_vfsdetach,
4350 	.f_event = filt_vfsvnode
4351 };
4352 
4353 static void
4354 vfs_knllock(void *arg)
4355 {
4356 	struct vnode *vp = arg;
4357 
4358 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
4359 }
4360 
4361 static void
4362 vfs_knlunlock(void *arg)
4363 {
4364 	struct vnode *vp = arg;
4365 
4366 	VOP_UNLOCK(vp, 0);
4367 }
4368 
4369 static void
4370 vfs_knl_assert_locked(void *arg)
4371 {
4372 #ifdef DEBUG_VFS_LOCKS
4373 	struct vnode *vp = arg;
4374 
4375 	ASSERT_VOP_LOCKED(vp, "vfs_knl_assert_locked");
4376 #endif
4377 }
4378 
4379 static void
4380 vfs_knl_assert_unlocked(void *arg)
4381 {
4382 #ifdef DEBUG_VFS_LOCKS
4383 	struct vnode *vp = arg;
4384 
4385 	ASSERT_VOP_UNLOCKED(vp, "vfs_knl_assert_unlocked");
4386 #endif
4387 }
4388 
4389 int
4390 vfs_kqfilter(struct vop_kqfilter_args *ap)
4391 {
4392 	struct vnode *vp = ap->a_vp;
4393 	struct knote *kn = ap->a_kn;
4394 	struct knlist *knl;
4395 
4396 	switch (kn->kn_filter) {
4397 	case EVFILT_READ:
4398 		kn->kn_fop = &vfsread_filtops;
4399 		break;
4400 	case EVFILT_WRITE:
4401 		kn->kn_fop = &vfswrite_filtops;
4402 		break;
4403 	case EVFILT_VNODE:
4404 		kn->kn_fop = &vfsvnode_filtops;
4405 		break;
4406 	default:
4407 		return (EINVAL);
4408 	}
4409 
4410 	kn->kn_hook = (caddr_t)vp;
4411 
4412 	v_addpollinfo(vp);
4413 	if (vp->v_pollinfo == NULL)
4414 		return (ENOMEM);
4415 	knl = &vp->v_pollinfo->vpi_selinfo.si_note;
4416 	vhold(vp);
4417 	knlist_add(knl, kn, 0);
4418 
4419 	return (0);
4420 }
4421 
4422 /*
4423  * Detach knote from vnode
4424  */
4425 static void
4426 filt_vfsdetach(struct knote *kn)
4427 {
4428 	struct vnode *vp = (struct vnode *)kn->kn_hook;
4429 
4430 	KASSERT(vp->v_pollinfo != NULL, ("Missing v_pollinfo"));
4431 	knlist_remove(&vp->v_pollinfo->vpi_selinfo.si_note, kn, 0);
4432 	vdrop(vp);
4433 }
4434 
4435 /*ARGSUSED*/
4436 static int
4437 filt_vfsread(struct knote *kn, long hint)
4438 {
4439 	struct vnode *vp = (struct vnode *)kn->kn_hook;
4440 	struct vattr va;
4441 	int res;
4442 
4443 	/*
4444 	 * filesystem is gone, so set the EOF flag and schedule
4445 	 * the knote for deletion.
4446 	 */
4447 	if (hint == NOTE_REVOKE) {
4448 		VI_LOCK(vp);
4449 		kn->kn_flags |= (EV_EOF | EV_ONESHOT);
4450 		VI_UNLOCK(vp);
4451 		return (1);
4452 	}
4453 
4454 	if (VOP_GETATTR(vp, &va, curthread->td_ucred))
4455 		return (0);
4456 
4457 	VI_LOCK(vp);
4458 	kn->kn_data = va.va_size - kn->kn_fp->f_offset;
4459 	res = (kn->kn_data != 0);
4460 	VI_UNLOCK(vp);
4461 	return (res);
4462 }
4463 
4464 /*ARGSUSED*/
4465 static int
4466 filt_vfswrite(struct knote *kn, long hint)
4467 {
4468 	struct vnode *vp = (struct vnode *)kn->kn_hook;
4469 
4470 	VI_LOCK(vp);
4471 
4472 	/*
4473 	 * filesystem is gone, so set the EOF flag and schedule
4474 	 * the knote for deletion.
4475 	 */
4476 	if (hint == NOTE_REVOKE)
4477 		kn->kn_flags |= (EV_EOF | EV_ONESHOT);
4478 
4479 	kn->kn_data = 0;
4480 	VI_UNLOCK(vp);
4481 	return (1);
4482 }
4483 
4484 static int
4485 filt_vfsvnode(struct knote *kn, long hint)
4486 {
4487 	struct vnode *vp = (struct vnode *)kn->kn_hook;
4488 	int res;
4489 
4490 	VI_LOCK(vp);
4491 	if (kn->kn_sfflags & hint)
4492 		kn->kn_fflags |= hint;
4493 	if (hint == NOTE_REVOKE) {
4494 		kn->kn_flags |= EV_EOF;
4495 		VI_UNLOCK(vp);
4496 		return (1);
4497 	}
4498 	res = (kn->kn_fflags != 0);
4499 	VI_UNLOCK(vp);
4500 	return (res);
4501 }
4502 
4503 int
4504 vfs_read_dirent(struct vop_readdir_args *ap, struct dirent *dp, off_t off)
4505 {
4506 	int error;
4507 
4508 	if (dp->d_reclen > ap->a_uio->uio_resid)
4509 		return (ENAMETOOLONG);
4510 	error = uiomove(dp, dp->d_reclen, ap->a_uio);
4511 	if (error) {
4512 		if (ap->a_ncookies != NULL) {
4513 			if (ap->a_cookies != NULL)
4514 				free(ap->a_cookies, M_TEMP);
4515 			ap->a_cookies = NULL;
4516 			*ap->a_ncookies = 0;
4517 		}
4518 		return (error);
4519 	}
4520 	if (ap->a_ncookies == NULL)
4521 		return (0);
4522 
4523 	KASSERT(ap->a_cookies,
4524 	    ("NULL ap->a_cookies value with non-NULL ap->a_ncookies!"));
4525 
4526 	*ap->a_cookies = realloc(*ap->a_cookies,
4527 	    (*ap->a_ncookies + 1) * sizeof(u_long), M_TEMP, M_WAITOK | M_ZERO);
4528 	(*ap->a_cookies)[*ap->a_ncookies] = off;
4529 	return (0);
4530 }
4531 
4532 /*
4533  * Mark for update the access time of the file if the filesystem
4534  * supports VOP_MARKATIME.  This functionality is used by execve and
4535  * mmap, so we want to avoid the I/O implied by directly setting
4536  * va_atime for the sake of efficiency.
4537  */
4538 void
4539 vfs_mark_atime(struct vnode *vp, struct ucred *cred)
4540 {
4541 	struct mount *mp;
4542 
4543 	mp = vp->v_mount;
4544 	ASSERT_VOP_LOCKED(vp, "vfs_mark_atime");
4545 	if (mp != NULL && (mp->mnt_flag & (MNT_NOATIME | MNT_RDONLY)) == 0)
4546 		(void)VOP_MARKATIME(vp);
4547 }
4548 
4549 /*
4550  * The purpose of this routine is to remove granularity from accmode_t,
4551  * reducing it into standard unix access bits - VEXEC, VREAD, VWRITE,
4552  * VADMIN and VAPPEND.
4553  *
4554  * If it returns 0, the caller is supposed to continue with the usual
4555  * access checks using 'accmode' as modified by this routine.  If it
4556  * returns nonzero value, the caller is supposed to return that value
4557  * as errno.
4558  *
4559  * Note that after this routine runs, accmode may be zero.
4560  */
4561 int
4562 vfs_unixify_accmode(accmode_t *accmode)
4563 {
4564 	/*
4565 	 * There is no way to specify explicit "deny" rule using
4566 	 * file mode or POSIX.1e ACLs.
4567 	 */
4568 	if (*accmode & VEXPLICIT_DENY) {
4569 		*accmode = 0;
4570 		return (0);
4571 	}
4572 
4573 	/*
4574 	 * None of these can be translated into usual access bits.
4575 	 * Also, the common case for NFSv4 ACLs is to not contain
4576 	 * either of these bits. Caller should check for VWRITE
4577 	 * on the containing directory instead.
4578 	 */
4579 	if (*accmode & (VDELETE_CHILD | VDELETE))
4580 		return (EPERM);
4581 
4582 	if (*accmode & VADMIN_PERMS) {
4583 		*accmode &= ~VADMIN_PERMS;
4584 		*accmode |= VADMIN;
4585 	}
4586 
4587 	/*
4588 	 * There is no way to deny VREAD_ATTRIBUTES, VREAD_ACL
4589 	 * or VSYNCHRONIZE using file mode or POSIX.1e ACL.
4590 	 */
4591 	*accmode &= ~(VSTAT_PERMS | VSYNCHRONIZE);
4592 
4593 	return (0);
4594 }
4595 
4596 /*
4597  * These are helper functions for filesystems to traverse all
4598  * their vnodes.  See MNT_VNODE_FOREACH_ALL() in sys/mount.h.
4599  *
4600  * This interface replaces MNT_VNODE_FOREACH.
4601  */
4602 
4603 MALLOC_DEFINE(M_VNODE_MARKER, "vnodemarker", "vnode marker");
4604 
4605 struct vnode *
4606 __mnt_vnode_next_all(struct vnode **mvp, struct mount *mp)
4607 {
4608 	struct vnode *vp;
4609 
4610 	if (should_yield())
4611 		kern_yield(PRI_USER);
4612 	MNT_ILOCK(mp);
4613 	KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
4614 	vp = TAILQ_NEXT(*mvp, v_nmntvnodes);
4615 	while (vp != NULL && (vp->v_type == VMARKER ||
4616 	    (vp->v_iflag & VI_DOOMED) != 0))
4617 		vp = TAILQ_NEXT(vp, v_nmntvnodes);
4618 
4619 	/* Check if we are done */
4620 	if (vp == NULL) {
4621 		__mnt_vnode_markerfree_all(mvp, mp);
4622 		/* MNT_IUNLOCK(mp); -- done in above function */
4623 		mtx_assert(MNT_MTX(mp), MA_NOTOWNED);
4624 		return (NULL);
4625 	}
4626 	TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
4627 	TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
4628 	VI_LOCK(vp);
4629 	MNT_IUNLOCK(mp);
4630 	return (vp);
4631 }
4632 
4633 struct vnode *
4634 __mnt_vnode_first_all(struct vnode **mvp, struct mount *mp)
4635 {
4636 	struct vnode *vp;
4637 
4638 	*mvp = malloc(sizeof(struct vnode), M_VNODE_MARKER, M_WAITOK | M_ZERO);
4639 	MNT_ILOCK(mp);
4640 	MNT_REF(mp);
4641 	(*mvp)->v_type = VMARKER;
4642 
4643 	vp = TAILQ_FIRST(&mp->mnt_nvnodelist);
4644 	while (vp != NULL && (vp->v_type == VMARKER ||
4645 	    (vp->v_iflag & VI_DOOMED) != 0))
4646 		vp = TAILQ_NEXT(vp, v_nmntvnodes);
4647 
4648 	/* Check if we are done */
4649 	if (vp == NULL) {
4650 		MNT_REL(mp);
4651 		MNT_IUNLOCK(mp);
4652 		free(*mvp, M_VNODE_MARKER);
4653 		*mvp = NULL;
4654 		return (NULL);
4655 	}
4656 	(*mvp)->v_mount = mp;
4657 	TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
4658 	VI_LOCK(vp);
4659 	MNT_IUNLOCK(mp);
4660 	return (vp);
4661 }
4662 
4663 
4664 void
4665 __mnt_vnode_markerfree_all(struct vnode **mvp, struct mount *mp)
4666 {
4667 
4668 	if (*mvp == NULL) {
4669 		MNT_IUNLOCK(mp);
4670 		return;
4671 	}
4672 
4673 	mtx_assert(MNT_MTX(mp), MA_OWNED);
4674 
4675 	KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
4676 	TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
4677 	MNT_REL(mp);
4678 	MNT_IUNLOCK(mp);
4679 	free(*mvp, M_VNODE_MARKER);
4680 	*mvp = NULL;
4681 }
4682 
4683 /*
4684  * These are helper functions for filesystems to traverse their
4685  * active vnodes.  See MNT_VNODE_FOREACH_ACTIVE() in sys/mount.h
4686  */
4687 static void
4688 mnt_vnode_markerfree_active(struct vnode **mvp, struct mount *mp)
4689 {
4690 
4691 	KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
4692 
4693 	MNT_ILOCK(mp);
4694 	MNT_REL(mp);
4695 	MNT_IUNLOCK(mp);
4696 	free(*mvp, M_VNODE_MARKER);
4697 	*mvp = NULL;
4698 }
4699 
4700 static struct vnode *
4701 mnt_vnode_next_active(struct vnode **mvp, struct mount *mp)
4702 {
4703 	struct vnode *vp, *nvp;
4704 
4705 	mtx_assert(&vnode_free_list_mtx, MA_OWNED);
4706 	KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
4707 restart:
4708 	vp = TAILQ_NEXT(*mvp, v_actfreelist);
4709 	TAILQ_REMOVE(&mp->mnt_activevnodelist, *mvp, v_actfreelist);
4710 	while (vp != NULL) {
4711 		if (vp->v_type == VMARKER) {
4712 			vp = TAILQ_NEXT(vp, v_actfreelist);
4713 			continue;
4714 		}
4715 		if (!VI_TRYLOCK(vp)) {
4716 			if (mp_ncpus == 1 || should_yield()) {
4717 				TAILQ_INSERT_BEFORE(vp, *mvp, v_actfreelist);
4718 				mtx_unlock(&vnode_free_list_mtx);
4719 				pause("vnacti", 1);
4720 				mtx_lock(&vnode_free_list_mtx);
4721 				goto restart;
4722 			}
4723 			continue;
4724 		}
4725 		KASSERT(vp->v_type != VMARKER, ("locked marker %p", vp));
4726 		KASSERT(vp->v_mount == mp || vp->v_mount == NULL,
4727 		    ("alien vnode on the active list %p %p", vp, mp));
4728 		if (vp->v_mount == mp && (vp->v_iflag & VI_DOOMED) == 0)
4729 			break;
4730 		nvp = TAILQ_NEXT(vp, v_actfreelist);
4731 		VI_UNLOCK(vp);
4732 		vp = nvp;
4733 	}
4734 
4735 	/* Check if we are done */
4736 	if (vp == NULL) {
4737 		mtx_unlock(&vnode_free_list_mtx);
4738 		mnt_vnode_markerfree_active(mvp, mp);
4739 		return (NULL);
4740 	}
4741 	TAILQ_INSERT_AFTER(&mp->mnt_activevnodelist, vp, *mvp, v_actfreelist);
4742 	mtx_unlock(&vnode_free_list_mtx);
4743 	ASSERT_VI_LOCKED(vp, "active iter");
4744 	KASSERT((vp->v_iflag & VI_ACTIVE) != 0, ("Non-active vp %p", vp));
4745 	return (vp);
4746 }
4747 
4748 struct vnode *
4749 __mnt_vnode_next_active(struct vnode **mvp, struct mount *mp)
4750 {
4751 
4752 	if (should_yield())
4753 		kern_yield(PRI_USER);
4754 	mtx_lock(&vnode_free_list_mtx);
4755 	return (mnt_vnode_next_active(mvp, mp));
4756 }
4757 
4758 struct vnode *
4759 __mnt_vnode_first_active(struct vnode **mvp, struct mount *mp)
4760 {
4761 	struct vnode *vp;
4762 
4763 	*mvp = malloc(sizeof(struct vnode), M_VNODE_MARKER, M_WAITOK | M_ZERO);
4764 	MNT_ILOCK(mp);
4765 	MNT_REF(mp);
4766 	MNT_IUNLOCK(mp);
4767 	(*mvp)->v_type = VMARKER;
4768 	(*mvp)->v_mount = mp;
4769 
4770 	mtx_lock(&vnode_free_list_mtx);
4771 	vp = TAILQ_FIRST(&mp->mnt_activevnodelist);
4772 	if (vp == NULL) {
4773 		mtx_unlock(&vnode_free_list_mtx);
4774 		mnt_vnode_markerfree_active(mvp, mp);
4775 		return (NULL);
4776 	}
4777 	TAILQ_INSERT_BEFORE(vp, *mvp, v_actfreelist);
4778 	return (mnt_vnode_next_active(mvp, mp));
4779 }
4780 
4781 void
4782 __mnt_vnode_markerfree_active(struct vnode **mvp, struct mount *mp)
4783 {
4784 
4785 	if (*mvp == NULL)
4786 		return;
4787 
4788 	mtx_lock(&vnode_free_list_mtx);
4789 	TAILQ_REMOVE(&mp->mnt_activevnodelist, *mvp, v_actfreelist);
4790 	mtx_unlock(&vnode_free_list_mtx);
4791 	mnt_vnode_markerfree_active(mvp, mp);
4792 }
4793