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