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