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