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