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