xref: /dragonfly/sys/kern/vfs_subr.c (revision e4710cad)
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  * 3. 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  * $FreeBSD: src/sys/kern/vfs_subr.c,v 1.249.2.30 2003/04/04 20:35:57 tegge Exp $
36  */
37 
38 /*
39  * External virtual filesystem routines
40  */
41 #include "opt_ddb.h"
42 #include "opt_inet.h"
43 #include "opt_inet6.h"
44 
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/buf.h>
48 #include <sys/conf.h>
49 #include <sys/dirent.h>
50 #include <sys/eventhandler.h>
51 #include <sys/fcntl.h>
52 #include <sys/file.h>
53 #include <sys/kernel.h>
54 #include <sys/kthread.h>
55 #include <sys/malloc.h>
56 #include <sys/mbuf.h>
57 #include <sys/mount.h>
58 #include <sys/priv.h>
59 #include <sys/proc.h>
60 #include <sys/reboot.h>
61 #include <sys/socket.h>
62 #include <sys/stat.h>
63 #include <sys/sysctl.h>
64 #include <sys/syslog.h>
65 #include <sys/unistd.h>
66 #include <sys/vmmeter.h>
67 #include <sys/vnode.h>
68 
69 #include <machine/limits.h>
70 
71 #include <vm/vm.h>
72 #include <vm/vm_object.h>
73 #include <vm/vm_extern.h>
74 #include <vm/vm_kern.h>
75 #include <vm/pmap.h>
76 #include <vm/vm_map.h>
77 #include <vm/vm_page.h>
78 #include <vm/vm_pager.h>
79 #include <vm/vnode_pager.h>
80 #include <vm/vm_zone.h>
81 
82 #include <sys/buf2.h>
83 #include <sys/mplock2.h>
84 #include <vm/vm_page2.h>
85 
86 #include <netinet/in.h>
87 
88 static MALLOC_DEFINE(M_NETCRED, "Export Host", "Export host address structure");
89 
90 __read_mostly int numvnodes;
91 SYSCTL_INT(_debug, OID_AUTO, numvnodes, CTLFLAG_RD, &numvnodes, 0,
92     "Number of vnodes allocated");
93 __read_mostly int verbose_reclaims;
94 SYSCTL_INT(_debug, OID_AUTO, verbose_reclaims, CTLFLAG_RD, &verbose_reclaims, 0,
95     "Output filename of reclaimed vnode(s)");
96 
97 __read_mostly enum vtype iftovt_tab[16] = {
98 	VNON, VFIFO, VCHR, VNON, VDIR, VNON, VBLK, VNON,
99 	VREG, VNON, VLNK, VNON, VSOCK, VNON, VNON, VBAD,
100 };
101 __read_mostly int vttoif_tab[9] = {
102 	0, S_IFREG, S_IFDIR, S_IFBLK, S_IFCHR, S_IFLNK,
103 	S_IFSOCK, S_IFIFO, S_IFMT,
104 };
105 
106 static int reassignbufcalls;
107 SYSCTL_INT(_vfs, OID_AUTO, reassignbufcalls, CTLFLAG_RW, &reassignbufcalls,
108     0, "Number of times buffers have been reassigned to the proper list");
109 
110 __read_mostly static int check_buf_overlap = 2;	/* invasive check */
111 SYSCTL_INT(_vfs, OID_AUTO, check_buf_overlap, CTLFLAG_RW, &check_buf_overlap,
112     0, "Enable overlapping buffer checks");
113 
114 int	nfs_mount_type = -1;
115 static struct lwkt_token spechash_token;
116 struct nfs_public nfs_pub;	/* publicly exported FS */
117 
118 __read_mostly int maxvnodes;
119 SYSCTL_INT(_kern, KERN_MAXVNODES, maxvnodes, CTLFLAG_RW,
120 	   &maxvnodes, 0, "Maximum number of vnodes");
121 
122 static struct radix_node_head *vfs_create_addrlist_af(int af,
123 		    struct netexport *nep);
124 static void	vfs_free_addrlist (struct netexport *nep);
125 static int	vfs_free_netcred (struct radix_node *rn, void *w);
126 static void	vfs_free_addrlist_af (struct radix_node_head **prnh);
127 static int	vfs_hang_addrlist (struct mount *mp, struct netexport *nep,
128 	            const struct export_args *argp);
129 
130 __read_mostly int prtactive = 0; /* 1 => print out reclaim of active vnodes */
131 
132 /*
133  * Red black tree functions
134  */
135 static int rb_buf_compare(struct buf *b1, struct buf *b2);
136 RB_GENERATE2(buf_rb_tree, buf, b_rbnode, rb_buf_compare, off_t, b_loffset);
137 RB_GENERATE2(buf_rb_hash, buf, b_rbhash, rb_buf_compare, off_t, b_loffset);
138 
139 static int
140 rb_buf_compare(struct buf *b1, struct buf *b2)
141 {
142 	if (b1->b_loffset < b2->b_loffset)
143 		return(-1);
144 	if (b1->b_loffset > b2->b_loffset)
145 		return(1);
146 	return(0);
147 }
148 
149 /*
150  * Initialize the vnode management data structures.
151  *
152  * Called from vfsinit()
153  */
154 #define MAXVNBREAKMEM	(1L * 1024 * 1024 * 1024)
155 #define MINVNODES	2000
156 #define MAXVNODES	4000000
157 
158 void
159 vfs_subr_init(void)
160 {
161 	int factor1;	/* Limit based on ram (x 2 above 1GB) */
162 	int factor2;	/* Limit based on available KVM */
163 	size_t freemem;
164 
165 	/*
166 	 * Size maxvnodes to available memory.  Size significantly
167 	 * smaller on low-memory systems (calculations for the first
168 	 * 1GB of ram), and pump it up a bit when free memory is
169 	 * above 1GB.
170 	 *
171 	 * The general minimum is maxproc * 8 (we want someone pushing
172 	 * up maxproc a lot to also get more vnodes).  Usually maxproc
173 	 * does not affect this calculation.
174 	 *
175 	 * There isn't much of a point allowing maxvnodes to exceed a
176 	 * few million as our modern filesystems cache pages in the
177 	 * underlying block device and not so much hanging off of VM
178 	 * objects.
179 	 */
180 	factor1 = 50 * (sizeof(struct vm_object) + sizeof(struct vnode));
181 	factor2 = 30 * (sizeof(struct vm_object) + sizeof(struct vnode));
182 
183 	freemem = (int64_t)vmstats.v_page_count * PAGE_SIZE;
184 
185 	maxvnodes = freemem / factor1;
186 	if (freemem > MAXVNBREAKMEM)
187 		maxvnodes += (freemem - MAXVNBREAKMEM) / factor1;
188 	maxvnodes = imax(maxvnodes, maxproc * 8);
189 	maxvnodes = imin(maxvnodes, KvaSize / factor2);
190 	maxvnodes = imin(maxvnodes, MAXVNODES);
191 	maxvnodes = imax(maxvnodes, MINVNODES);
192 
193 	lwkt_token_init(&spechash_token, "spechash");
194 }
195 
196 /*
197  * Knob to control the precision of file timestamps:
198  *
199  *   0 = seconds only; nanoseconds zeroed.
200  *   1 = seconds and nanoseconds, accurate within 1/HZ.
201  *   2 = seconds and nanoseconds, truncated to microseconds.
202  * >=3 = seconds and nanoseconds, maximum precision.
203  */
204 enum { TSP_SEC, TSP_HZ, TSP_USEC, TSP_NSEC };
205 
206 __read_mostly static int timestamp_precision = TSP_SEC;
207 SYSCTL_INT(_vfs, OID_AUTO, timestamp_precision, CTLFLAG_RW,
208 		&timestamp_precision, 0, "Precision of file timestamps");
209 
210 /*
211  * Get a current timestamp.
212  *
213  * MPSAFE
214  */
215 void
216 vfs_timestamp(struct timespec *tsp)
217 {
218 	struct timeval tv;
219 
220 	switch (timestamp_precision) {
221 	case TSP_SEC:
222 		tsp->tv_sec = time_second;
223 		tsp->tv_nsec = 0;
224 		break;
225 	case TSP_HZ:
226 		getnanotime(tsp);
227 		break;
228 	case TSP_USEC:
229 		microtime(&tv);
230 		TIMEVAL_TO_TIMESPEC(&tv, tsp);
231 		break;
232 	case TSP_NSEC:
233 	default:
234 		nanotime(tsp);
235 		break;
236 	}
237 }
238 
239 /*
240  * Set vnode attributes to VNOVAL
241  */
242 void
243 vattr_null(struct vattr *vap)
244 {
245 	vap->va_type = VNON;
246 	vap->va_size = VNOVAL;
247 	vap->va_bytes = VNOVAL;
248 	vap->va_mode = VNOVAL;
249 	vap->va_nlink = VNOVAL;
250 	vap->va_uid = VNOVAL;
251 	vap->va_gid = VNOVAL;
252 	vap->va_fsid = VNOVAL;
253 	vap->va_fileid = VNOVAL;
254 	vap->va_blocksize = VNOVAL;
255 	vap->va_rmajor = VNOVAL;
256 	vap->va_rminor = VNOVAL;
257 	vap->va_atime.tv_sec = VNOVAL;
258 	vap->va_atime.tv_nsec = VNOVAL;
259 	vap->va_mtime.tv_sec = VNOVAL;
260 	vap->va_mtime.tv_nsec = VNOVAL;
261 	vap->va_ctime.tv_sec = VNOVAL;
262 	vap->va_ctime.tv_nsec = VNOVAL;
263 	vap->va_flags = VNOVAL;
264 	vap->va_gen = VNOVAL;
265 	vap->va_vaflags = 0;
266 	/* va_*_uuid fields are only valid if related flags are set */
267 }
268 
269 /*
270  * Flush out and invalidate all buffers associated with a vnode.
271  *
272  * vp must be locked.
273  */
274 static int vinvalbuf_bp(struct buf *bp, void *data);
275 
276 struct vinvalbuf_bp_info {
277 	struct vnode *vp;
278 	int slptimeo;
279 	int lkflags;
280 	int flags;
281 	int clean;
282 };
283 
284 int
285 vinvalbuf(struct vnode *vp, int flags, int slpflag, int slptimeo)
286 {
287 	struct vinvalbuf_bp_info info;
288 	vm_object_t object;
289 	int error;
290 
291 	lwkt_gettoken(&vp->v_token);
292 
293 	/*
294 	 * If we are being asked to save, call fsync to ensure that the inode
295 	 * is updated.
296 	 */
297 	if (flags & V_SAVE) {
298 		error = bio_track_wait(&vp->v_track_write, slpflag, slptimeo);
299 		if (error)
300 			goto done;
301 		if (!RB_EMPTY(&vp->v_rbdirty_tree)) {
302 			if ((error = VOP_FSYNC(vp, MNT_WAIT, 0)) != 0)
303 				goto done;
304 #if 0
305 			/*
306 			 * Dirty bufs may be left or generated via races
307 			 * in circumstances where vinvalbuf() is called on
308 			 * a vnode not undergoing reclamation.   Only
309 			 * panic if we are trying to reclaim the vnode.
310 			 */
311 			if ((vp->v_flag & VRECLAIMED) &&
312 			    (bio_track_active(&vp->v_track_write) ||
313 			    !RB_EMPTY(&vp->v_rbdirty_tree))) {
314 				panic("vinvalbuf: dirty bufs");
315 			}
316 #endif
317 		}
318   	}
319 	info.slptimeo = slptimeo;
320 	info.lkflags = LK_EXCLUSIVE | LK_SLEEPFAIL;
321 	if (slpflag & PCATCH)
322 		info.lkflags |= LK_PCATCH;
323 	info.flags = flags;
324 	info.vp = vp;
325 
326 	/*
327 	 * Flush the buffer cache until nothing is left, wait for all I/O
328 	 * to complete.  At least one pass is required.  We might block
329 	 * in the pip code so we have to re-check.  Order is important.
330 	 */
331 	do {
332 		/*
333 		 * Flush buffer cache
334 		 */
335 		if (!RB_EMPTY(&vp->v_rbclean_tree)) {
336 			info.clean = 1;
337 			error = RB_SCAN(buf_rb_tree, &vp->v_rbclean_tree,
338 					NULL, vinvalbuf_bp, &info);
339 		}
340 		if (!RB_EMPTY(&vp->v_rbdirty_tree)) {
341 			info.clean = 0;
342 			error = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree,
343 					NULL, vinvalbuf_bp, &info);
344 		}
345 
346 		/*
347 		 * Wait for I/O completion.
348 		 */
349 		bio_track_wait(&vp->v_track_write, 0, 0);
350 		if ((object = vp->v_object) != NULL)
351 			refcount_wait(&object->paging_in_progress, "vnvlbx");
352 	} while (bio_track_active(&vp->v_track_write) ||
353 		 !RB_EMPTY(&vp->v_rbclean_tree) ||
354 		 !RB_EMPTY(&vp->v_rbdirty_tree));
355 
356 	/*
357 	 * Destroy the copy in the VM cache, too.
358 	 */
359 	if ((object = vp->v_object) != NULL) {
360 		vm_object_page_remove(object, 0, 0,
361 			(flags & V_SAVE) ? TRUE : FALSE);
362 	}
363 
364 	if (!RB_EMPTY(&vp->v_rbdirty_tree) || !RB_EMPTY(&vp->v_rbclean_tree))
365 		panic("vinvalbuf: flush failed");
366 	if (!RB_EMPTY(&vp->v_rbhash_tree))
367 		panic("vinvalbuf: flush failed, buffers still present");
368 	error = 0;
369 done:
370 	lwkt_reltoken(&vp->v_token);
371 	return (error);
372 }
373 
374 static int
375 vinvalbuf_bp(struct buf *bp, void *data)
376 {
377 	struct vinvalbuf_bp_info *info = data;
378 	int error;
379 
380 	if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
381 		atomic_add_int(&bp->b_refs, 1);
382 		error = BUF_TIMELOCK(bp, info->lkflags,
383 				     "vinvalbuf", info->slptimeo);
384 		atomic_subtract_int(&bp->b_refs, 1);
385 		if (error == 0) {
386 			BUF_UNLOCK(bp);
387 			error = ENOLCK;
388 		}
389 		if (error == ENOLCK)
390 			return(0);
391 		return (-error);
392 	}
393 	KKASSERT(bp->b_vp == info->vp);
394 
395 	/*
396 	 * Must check clean/dirty status after successfully locking as
397 	 * it may race.
398 	 */
399 	if ((info->clean && (bp->b_flags & B_DELWRI)) ||
400 	    (info->clean == 0 && (bp->b_flags & B_DELWRI) == 0)) {
401 		BUF_UNLOCK(bp);
402 		return(0);
403 	}
404 
405 	/*
406 	 * NOTE:  NO B_LOCKED CHECK.  Also no buf_checkwrite()
407 	 * check.  This code will write out the buffer, period.
408 	 */
409 	bremfree(bp);
410 	if (((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI) &&
411 	    (info->flags & V_SAVE)) {
412 		cluster_awrite(bp);
413 	} else if (info->flags & V_SAVE) {
414 		/*
415 		 * Cannot set B_NOCACHE on a clean buffer as this will
416 		 * destroy the VM backing store which might actually
417 		 * be dirty (and unsynchronized).
418 		 */
419 		bp->b_flags |= (B_INVAL | B_RELBUF);
420 		brelse(bp);
421 	} else {
422 		bp->b_flags |= (B_INVAL | B_NOCACHE | B_RELBUF);
423 		brelse(bp);
424 	}
425 	return(0);
426 }
427 
428 /*
429  * Truncate a file's buffer and pages to a specified length.  This
430  * is in lieu of the old vinvalbuf mechanism, which performed unneeded
431  * sync activity.
432  *
433  * The vnode must be locked.
434  */
435 static int vtruncbuf_bp_trunc_cmp(struct buf *bp, void *data);
436 static int vtruncbuf_bp_trunc(struct buf *bp, void *data);
437 static int vtruncbuf_bp_metasync_cmp(struct buf *bp, void *data);
438 static int vtruncbuf_bp_metasync(struct buf *bp, void *data);
439 
440 struct vtruncbuf_info {
441 	struct vnode *vp;
442 	off_t	truncloffset;
443 	int	clean;
444 };
445 
446 int
447 vtruncbuf(struct vnode *vp, off_t length, int blksize)
448 {
449 	struct vtruncbuf_info info;
450 	const char *filename;
451 	int count;
452 
453 	/*
454 	 * Round up to the *next* block, then destroy the buffers in question.
455 	 * Since we are only removing some of the buffers we must rely on the
456 	 * scan count to determine whether a loop is necessary.
457 	 */
458 	if ((count = (int)(length % blksize)) != 0)
459 		info.truncloffset = length + (blksize - count);
460 	else
461 		info.truncloffset = length;
462 	info.vp = vp;
463 
464 	lwkt_gettoken(&vp->v_token);
465 	do {
466 		info.clean = 1;
467 		count = RB_SCAN(buf_rb_tree, &vp->v_rbclean_tree,
468 				vtruncbuf_bp_trunc_cmp,
469 				vtruncbuf_bp_trunc, &info);
470 		info.clean = 0;
471 		count += RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree,
472 				vtruncbuf_bp_trunc_cmp,
473 				vtruncbuf_bp_trunc, &info);
474 	} while(count);
475 
476 	/*
477 	 * For safety, fsync any remaining metadata if the file is not being
478 	 * truncated to 0.  Since the metadata does not represent the entire
479 	 * dirty list we have to rely on the hit count to ensure that we get
480 	 * all of it.
481 	 */
482 	if (length > 0) {
483 		do {
484 			count = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree,
485 					vtruncbuf_bp_metasync_cmp,
486 					vtruncbuf_bp_metasync, &info);
487 		} while (count);
488 	}
489 
490 	/*
491 	 * Clean out any left over VM backing store.
492 	 *
493 	 * It is possible to have in-progress I/O from buffers that were
494 	 * not part of the truncation.  This should not happen if we
495 	 * are truncating to 0-length.
496 	 */
497 	vnode_pager_setsize(vp, length);
498 	bio_track_wait(&vp->v_track_write, 0, 0);
499 
500 	/*
501 	 * Debugging only
502 	 */
503 	spin_lock(&vp->v_spin);
504 	filename = TAILQ_FIRST(&vp->v_namecache) ?
505 		   TAILQ_FIRST(&vp->v_namecache)->nc_name : "?";
506 	spin_unlock(&vp->v_spin);
507 
508 	/*
509 	 * Make sure no buffers were instantiated while we were trying
510 	 * to clean out the remaining VM pages.  This could occur due
511 	 * to busy dirty VM pages being flushed out to disk.
512 	 */
513 	do {
514 		info.clean = 1;
515 		count = RB_SCAN(buf_rb_tree, &vp->v_rbclean_tree,
516 				vtruncbuf_bp_trunc_cmp,
517 				vtruncbuf_bp_trunc, &info);
518 		info.clean = 0;
519 		count += RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree,
520 				vtruncbuf_bp_trunc_cmp,
521 				vtruncbuf_bp_trunc, &info);
522 		if (count) {
523 			kprintf("Warning: vtruncbuf():  Had to re-clean %d "
524 			       "left over buffers in %s\n", count, filename);
525 		}
526 	} while(count);
527 
528 	lwkt_reltoken(&vp->v_token);
529 
530 	return (0);
531 }
532 
533 /*
534  * The callback buffer is beyond the new file EOF and must be destroyed.
535  * Note that the compare function must conform to the RB_SCAN's requirements.
536  */
537 static
538 int
539 vtruncbuf_bp_trunc_cmp(struct buf *bp, void *data)
540 {
541 	struct vtruncbuf_info *info = data;
542 
543 	if (bp->b_loffset >= info->truncloffset)
544 		return(0);
545 	return(-1);
546 }
547 
548 static
549 int
550 vtruncbuf_bp_trunc(struct buf *bp, void *data)
551 {
552 	struct vtruncbuf_info *info = data;
553 
554 	/*
555 	 * Do not try to use a buffer we cannot immediately lock, but sleep
556 	 * anyway to prevent a livelock.  The code will loop until all buffers
557 	 * can be acted upon.
558 	 *
559 	 * We must always revalidate the buffer after locking it to deal
560 	 * with MP races.
561 	 */
562 	if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
563 		atomic_add_int(&bp->b_refs, 1);
564 		if (BUF_LOCK(bp, LK_EXCLUSIVE|LK_SLEEPFAIL) == 0)
565 			BUF_UNLOCK(bp);
566 		atomic_subtract_int(&bp->b_refs, 1);
567 	} else if ((info->clean && (bp->b_flags & B_DELWRI)) ||
568 		   (info->clean == 0 && (bp->b_flags & B_DELWRI) == 0) ||
569 		   bp->b_vp != info->vp ||
570 		   vtruncbuf_bp_trunc_cmp(bp, data)) {
571 		BUF_UNLOCK(bp);
572 	} else {
573 		bremfree(bp);
574 		bp->b_flags |= (B_INVAL | B_RELBUF | B_NOCACHE);
575 		brelse(bp);
576 	}
577 	return(1);
578 }
579 
580 /*
581  * Fsync all meta-data after truncating a file to be non-zero.  Only metadata
582  * blocks (with a negative loffset) are scanned.
583  * Note that the compare function must conform to the RB_SCAN's requirements.
584  */
585 static int
586 vtruncbuf_bp_metasync_cmp(struct buf *bp, void *data __unused)
587 {
588 	if (bp->b_loffset < 0)
589 		return(0);
590 	return(1);
591 }
592 
593 static int
594 vtruncbuf_bp_metasync(struct buf *bp, void *data)
595 {
596 	struct vtruncbuf_info *info = data;
597 
598 	if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
599 		atomic_add_int(&bp->b_refs, 1);
600 		if (BUF_LOCK(bp, LK_EXCLUSIVE|LK_SLEEPFAIL) == 0)
601 			BUF_UNLOCK(bp);
602 		atomic_subtract_int(&bp->b_refs, 1);
603 	} else if ((bp->b_flags & B_DELWRI) == 0 ||
604 		   bp->b_vp != info->vp ||
605 		   vtruncbuf_bp_metasync_cmp(bp, data)) {
606 		BUF_UNLOCK(bp);
607 	} else {
608 		bremfree(bp);
609 		if (bp->b_vp == info->vp)
610 			bawrite(bp);
611 		else
612 			bwrite(bp);
613 	}
614 	return(1);
615 }
616 
617 /*
618  * vfsync - implements a multipass fsync on a file which understands
619  * dependancies and meta-data.  The passed vnode must be locked.  The
620  * waitfor argument may be MNT_WAIT or MNT_NOWAIT, or MNT_LAZY.
621  *
622  * When fsyncing data asynchronously just do one consolidated pass starting
623  * with the most negative block number.  This may not get all the data due
624  * to dependancies.
625  *
626  * When fsyncing data synchronously do a data pass, then a metadata pass,
627  * then do additional data+metadata passes to try to get all the data out.
628  *
629  * Caller must ref the vnode but does not have to lock it.
630  */
631 static int vfsync_wait_output(struct vnode *vp,
632 			    int (*waitoutput)(struct vnode *, struct thread *));
633 static int vfsync_dummy_cmp(struct buf *bp __unused, void *data __unused);
634 static int vfsync_data_only_cmp(struct buf *bp, void *data);
635 static int vfsync_meta_only_cmp(struct buf *bp, void *data);
636 static int vfsync_lazy_range_cmp(struct buf *bp, void *data);
637 static int vfsync_bp(struct buf *bp, void *data);
638 
639 struct vfsync_info {
640 	struct vnode *vp;
641 	int fastpass;
642 	int synchronous;
643 	int syncdeps;
644 	int lazycount;
645 	int lazylimit;
646 	int skippedbufs;
647 	int (*checkdef)(struct buf *);
648 	int (*cmpfunc)(struct buf *, void *);
649 };
650 
651 int
652 vfsync(struct vnode *vp, int waitfor, int passes,
653 	int (*checkdef)(struct buf *),
654 	int (*waitoutput)(struct vnode *, struct thread *))
655 {
656 	struct vfsync_info info;
657 	int error;
658 
659 	bzero(&info, sizeof(info));
660 	info.vp = vp;
661 	if ((info.checkdef = checkdef) == NULL)
662 		info.syncdeps = 1;
663 
664 	lwkt_gettoken(&vp->v_token);
665 
666 	switch(waitfor) {
667 	case MNT_LAZY | MNT_NOWAIT:
668 	case MNT_LAZY:
669 		/*
670 		 * Lazy (filesystem syncer typ) Asynchronous plus limit the
671 		 * number of data (not meta) pages we try to flush to 1MB.
672 		 * A non-zero return means that lazy limit was reached.
673 		 */
674 		info.lazylimit = 1024 * 1024;
675 		info.syncdeps = 1;
676 		info.cmpfunc = vfsync_lazy_range_cmp;
677 		error = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree,
678 				vfsync_lazy_range_cmp, vfsync_bp, &info);
679 		info.cmpfunc = vfsync_meta_only_cmp;
680 		RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree,
681 			vfsync_meta_only_cmp, vfsync_bp, &info);
682 		if (error == 0)
683 			vp->v_lazyw = 0;
684 		else if (!RB_EMPTY(&vp->v_rbdirty_tree))
685 			vn_syncer_add(vp, 1);
686 		error = 0;
687 		break;
688 	case MNT_NOWAIT:
689 		/*
690 		 * Asynchronous.  Do a data-only pass and a meta-only pass.
691 		 */
692 		info.syncdeps = 1;
693 		info.cmpfunc = vfsync_data_only_cmp;
694 		RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, vfsync_data_only_cmp,
695 			vfsync_bp, &info);
696 		info.cmpfunc = vfsync_meta_only_cmp;
697 		RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, vfsync_meta_only_cmp,
698 			vfsync_bp, &info);
699 		error = 0;
700 		break;
701 	default:
702 		/*
703 		 * Synchronous.  Do a data-only pass, then a meta-data+data
704 		 * pass, then additional integrated passes to try to get
705 		 * all the dependancies flushed.
706 		 */
707 		info.cmpfunc = vfsync_data_only_cmp;
708 		info.fastpass = 1;
709 		RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, vfsync_data_only_cmp,
710 			vfsync_bp, &info);
711 		info.fastpass = 0;
712 		error = vfsync_wait_output(vp, waitoutput);
713 		if (error == 0) {
714 			info.skippedbufs = 0;
715 			info.cmpfunc = vfsync_dummy_cmp;
716 			RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, NULL,
717 				vfsync_bp, &info);
718 			error = vfsync_wait_output(vp, waitoutput);
719 			if (info.skippedbufs) {
720 				kprintf("Warning: vfsync skipped %d dirty "
721 					"buf%s in pass2!\n",
722 					info.skippedbufs,
723 					((info.skippedbufs > 1) ? "s" : ""));
724 			}
725 		}
726 		while (error == 0 && passes > 0 &&
727 		       !RB_EMPTY(&vp->v_rbdirty_tree)
728 		) {
729 			info.skippedbufs = 0;
730 			if (--passes == 0) {
731 				info.synchronous = 1;
732 				info.syncdeps = 1;
733 			}
734 			info.cmpfunc = vfsync_dummy_cmp;
735 			error = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, NULL,
736 					vfsync_bp, &info);
737 			if (error < 0)
738 				error = -error;
739 			info.syncdeps = 1;
740 			if (error == 0)
741 				error = vfsync_wait_output(vp, waitoutput);
742 			if (info.skippedbufs && passes == 0) {
743 				kprintf("Warning: vfsync skipped %d dirty "
744 					"buf%s in final pass!\n",
745 					info.skippedbufs,
746 					((info.skippedbufs > 1) ? "s" : ""));
747 			}
748 		}
749 #if 0
750 		/*
751 		 * This case can occur normally because vnode lock might
752 		 * not be held.
753 		 */
754 		if (!RB_EMPTY(&vp->v_rbdirty_tree))
755 			kprintf("dirty bufs left after final pass\n");
756 #endif
757 		break;
758 	}
759 	lwkt_reltoken(&vp->v_token);
760 
761 	return(error);
762 }
763 
764 static int
765 vfsync_wait_output(struct vnode *vp,
766 		   int (*waitoutput)(struct vnode *, struct thread *))
767 {
768 	int error;
769 
770 	error = bio_track_wait(&vp->v_track_write, 0, 0);
771 	if (waitoutput)
772 		error = waitoutput(vp, curthread);
773 	return(error);
774 }
775 
776 static int
777 vfsync_dummy_cmp(struct buf *bp __unused, void *data __unused)
778 {
779 	return(0);
780 }
781 
782 static int
783 vfsync_data_only_cmp(struct buf *bp, void *data)
784 {
785 	if (bp->b_loffset < 0)
786 		return(-1);
787 	return(0);
788 }
789 
790 static int
791 vfsync_meta_only_cmp(struct buf *bp, void *data)
792 {
793 	if (bp->b_loffset < 0)
794 		return(0);
795 	return(1);
796 }
797 
798 static int
799 vfsync_lazy_range_cmp(struct buf *bp, void *data)
800 {
801 	struct vfsync_info *info = data;
802 
803 	if (bp->b_loffset < info->vp->v_lazyw)
804 		return(-1);
805 	return(0);
806 }
807 
808 static int
809 vfsync_bp(struct buf *bp, void *data)
810 {
811 	struct vfsync_info *info = data;
812 	struct vnode *vp = info->vp;
813 	int error;
814 
815 	if (info->fastpass) {
816 		/*
817 		 * Ignore buffers that we cannot immediately lock.
818 		 */
819 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
820 			/*
821 			 * Removed BUF_TIMELOCK(..., 1), even a 1-tick
822 			 * delay can mess up performance
823 			 *
824 			 * Another reason is that during a dirty-buffer
825 			 * scan a clustered write can start I/O on buffers
826 			 * ahead of the scan, causing the scan to not
827 			 * get a lock here.  Usually this means the write
828 			 * is already in progress so, in fact, we *want*
829 			 * to skip the buffer.
830 			 */
831 			++info->skippedbufs;
832 			return(0);
833 		}
834 	} else if (info->synchronous == 0) {
835 		/*
836 		 * Normal pass, give the buffer a little time to become
837 		 * available to us.
838 		 */
839 		if (BUF_TIMELOCK(bp, LK_EXCLUSIVE, "bflst2", hz / 10)) {
840 			++info->skippedbufs;
841 			return(0);
842 		}
843 	} else {
844 		/*
845 		 * Synchronous pass, give the buffer a lot of time before
846 		 * giving up.
847 		 */
848 		if (BUF_TIMELOCK(bp, LK_EXCLUSIVE, "bflst3", hz * 10)) {
849 			++info->skippedbufs;
850 			return(0);
851 		}
852 	}
853 
854 	/*
855 	 * We must revalidate the buffer after locking.
856 	 */
857 	if ((bp->b_flags & B_DELWRI) == 0 ||
858 	    bp->b_vp != info->vp ||
859 	    info->cmpfunc(bp, data)) {
860 		BUF_UNLOCK(bp);
861 		return(0);
862 	}
863 
864 	/*
865 	 * If syncdeps is not set we do not try to write buffers which have
866 	 * dependancies.
867 	 */
868 	if (!info->synchronous && info->syncdeps == 0 && info->checkdef(bp)) {
869 		BUF_UNLOCK(bp);
870 		return(0);
871 	}
872 
873 	/*
874 	 * B_NEEDCOMMIT (primarily used by NFS) is a state where the buffer
875 	 * has been written but an additional handshake with the device
876 	 * is required before we can dispose of the buffer.  We have no idea
877 	 * how to do this so we have to skip these buffers.
878 	 */
879 	if (bp->b_flags & B_NEEDCOMMIT) {
880 		BUF_UNLOCK(bp);
881 		return(0);
882 	}
883 
884 	/*
885 	 * Ask bioops if it is ok to sync.  If not the VFS may have
886 	 * set B_LOCKED so we have to cycle the buffer.
887 	 */
888 	if (LIST_FIRST(&bp->b_dep) != NULL && buf_checkwrite(bp)) {
889 		bremfree(bp);
890 		brelse(bp);
891 		return(0);
892 	}
893 
894 	if (info->synchronous) {
895 		/*
896 		 * Synchronous flush.  An error may be returned and will
897 		 * stop the scan.
898 		 */
899 		bremfree(bp);
900 		error = bwrite(bp);
901 	} else {
902 		/*
903 		 * Asynchronous flush.  We use the error return to support
904 		 * MNT_LAZY flushes.
905 		 *
906 		 * In low-memory situations we revert to synchronous
907 		 * operation.  This should theoretically prevent the I/O
908 		 * path from exhausting memory in a non-recoverable way.
909 		 */
910 		vp->v_lazyw = bp->b_loffset;
911 		bremfree(bp);
912 		if (vm_page_count_min(0)) {
913 			/* low memory */
914 			info->lazycount += bp->b_bufsize;
915 			bwrite(bp);
916 		} else {
917 			/* normal */
918 			info->lazycount += cluster_awrite(bp);
919 			waitrunningbufspace();
920 			/*vm_wait_nominal();*/
921 		}
922 		if (info->lazylimit && info->lazycount >= info->lazylimit)
923 			error = 1;
924 		else
925 			error = 0;
926 	}
927 	return(-error);
928 }
929 
930 /*
931  * Associate a buffer with a vnode.
932  *
933  * MPSAFE
934  */
935 int
936 bgetvp(struct vnode *vp, struct buf *bp, int testsize)
937 {
938 	KASSERT(bp->b_vp == NULL, ("bgetvp: not free"));
939 	KKASSERT((bp->b_flags & (B_HASHED|B_DELWRI|B_VNCLEAN|B_VNDIRTY)) == 0);
940 
941 	/*
942 	 * Insert onto list for new vnode.
943 	 */
944 	lwkt_gettoken(&vp->v_token);
945 
946 	if (buf_rb_hash_RB_INSERT(&vp->v_rbhash_tree, bp)) {
947 		lwkt_reltoken(&vp->v_token);
948 		return (EEXIST);
949 	}
950 
951 	/*
952 	 * Diagnostics (mainly for HAMMER debugging).  Check for
953 	 * overlapping buffers.
954 	 */
955 	if (check_buf_overlap) {
956 		struct buf *bx;
957 		bx = buf_rb_hash_RB_PREV(bp);
958 		if (bx) {
959 			if (bx->b_loffset + bx->b_bufsize > bp->b_loffset) {
960 				kprintf("bgetvp: overlapl %016jx/%d %016jx "
961 					"bx %p bp %p\n",
962 					(intmax_t)bx->b_loffset,
963 					bx->b_bufsize,
964 					(intmax_t)bp->b_loffset,
965 					bx, bp);
966 				if (check_buf_overlap > 1)
967 					panic("bgetvp - overlapping buffer");
968 			}
969 		}
970 		bx = buf_rb_hash_RB_NEXT(bp);
971 		if (bx) {
972 			if (bp->b_loffset + testsize > bx->b_loffset) {
973 				kprintf("bgetvp: overlapr %016jx/%d %016jx "
974 					"bp %p bx %p\n",
975 					(intmax_t)bp->b_loffset,
976 					testsize,
977 					(intmax_t)bx->b_loffset,
978 					bp, bx);
979 				if (check_buf_overlap > 1)
980 					panic("bgetvp - overlapping buffer");
981 			}
982 		}
983 	}
984 	bp->b_vp = vp;
985 	bp->b_flags |= B_HASHED;
986 	bp->b_flags |= B_VNCLEAN;
987 	if (buf_rb_tree_RB_INSERT(&vp->v_rbclean_tree, bp))
988 		panic("reassignbuf: dup lblk/clean vp %p bp %p", vp, bp);
989 	/*vhold(vp);*/
990 	lwkt_reltoken(&vp->v_token);
991 	return(0);
992 }
993 
994 /*
995  * Disassociate a buffer from a vnode.
996  *
997  * MPSAFE
998  */
999 void
1000 brelvp(struct buf *bp)
1001 {
1002 	struct vnode *vp;
1003 
1004 	KASSERT(bp->b_vp != NULL, ("brelvp: NULL"));
1005 
1006 	/*
1007 	 * Delete from old vnode list, if on one.
1008 	 */
1009 	vp = bp->b_vp;
1010 	lwkt_gettoken(&vp->v_token);
1011 	if (bp->b_flags & (B_VNDIRTY | B_VNCLEAN)) {
1012 		if (bp->b_flags & B_VNDIRTY)
1013 			buf_rb_tree_RB_REMOVE(&vp->v_rbdirty_tree, bp);
1014 		else
1015 			buf_rb_tree_RB_REMOVE(&vp->v_rbclean_tree, bp);
1016 		bp->b_flags &= ~(B_VNDIRTY | B_VNCLEAN);
1017 	}
1018 	if (bp->b_flags & B_HASHED) {
1019 		buf_rb_hash_RB_REMOVE(&vp->v_rbhash_tree, bp);
1020 		bp->b_flags &= ~B_HASHED;
1021 	}
1022 
1023 	/*
1024 	 * Only remove from synclist when no dirty buffers are left AND
1025 	 * the VFS has not flagged the vnode's inode as being dirty.
1026 	 */
1027 	if ((vp->v_flag & (VONWORKLST | VISDIRTY | VOBJDIRTY)) == VONWORKLST &&
1028 	    RB_EMPTY(&vp->v_rbdirty_tree)) {
1029 		vn_syncer_remove(vp, 0);
1030 	}
1031 	bp->b_vp = NULL;
1032 
1033 	lwkt_reltoken(&vp->v_token);
1034 
1035 	/*vdrop(vp);*/
1036 }
1037 
1038 /*
1039  * Reassign the buffer to the proper clean/dirty list based on B_DELWRI.
1040  * This routine is called when the state of the B_DELWRI bit is changed.
1041  *
1042  * Must be called with vp->v_token held.
1043  * MPSAFE
1044  */
1045 void
1046 reassignbuf(struct buf *bp)
1047 {
1048 	struct vnode *vp = bp->b_vp;
1049 	int delay;
1050 
1051 	ASSERT_LWKT_TOKEN_HELD(&vp->v_token);
1052 	++reassignbufcalls;
1053 
1054 	/*
1055 	 * B_PAGING flagged buffers cannot be reassigned because their vp
1056 	 * is not fully linked in.
1057 	 */
1058 	if (bp->b_flags & B_PAGING)
1059 		panic("cannot reassign paging buffer");
1060 
1061 	if (bp->b_flags & B_DELWRI) {
1062 		/*
1063 		 * Move to the dirty list, add the vnode to the worklist
1064 		 */
1065 		if (bp->b_flags & B_VNCLEAN) {
1066 			buf_rb_tree_RB_REMOVE(&vp->v_rbclean_tree, bp);
1067 			bp->b_flags &= ~B_VNCLEAN;
1068 		}
1069 		if ((bp->b_flags & B_VNDIRTY) == 0) {
1070 			if (buf_rb_tree_RB_INSERT(&vp->v_rbdirty_tree, bp)) {
1071 				panic("reassignbuf: dup lblk vp %p bp %p",
1072 				      vp, bp);
1073 			}
1074 			bp->b_flags |= B_VNDIRTY;
1075 		}
1076 		if ((vp->v_flag & VONWORKLST) == 0) {
1077 			switch (vp->v_type) {
1078 			case VDIR:
1079 				delay = dirdelay;
1080 				break;
1081 			case VCHR:
1082 			case VBLK:
1083 				if (vp->v_rdev &&
1084 				    vp->v_rdev->si_mountpoint != NULL) {
1085 					delay = metadelay;
1086 					break;
1087 				}
1088 				/* fall through */
1089 			default:
1090 				delay = filedelay;
1091 			}
1092 			vn_syncer_add(vp, delay);
1093 		}
1094 	} else {
1095 		/*
1096 		 * Move to the clean list, remove the vnode from the worklist
1097 		 * if no dirty blocks remain.
1098 		 */
1099 		if (bp->b_flags & B_VNDIRTY) {
1100 			buf_rb_tree_RB_REMOVE(&vp->v_rbdirty_tree, bp);
1101 			bp->b_flags &= ~B_VNDIRTY;
1102 		}
1103 		if ((bp->b_flags & B_VNCLEAN) == 0) {
1104 			if (buf_rb_tree_RB_INSERT(&vp->v_rbclean_tree, bp)) {
1105 				panic("reassignbuf: dup lblk vp %p bp %p",
1106 				      vp, bp);
1107 			}
1108 			bp->b_flags |= B_VNCLEAN;
1109 		}
1110 
1111 		/*
1112 		 * Only remove from synclist when no dirty buffers are left
1113 		 * AND the VFS has not flagged the vnode's inode as being
1114 		 * dirty.
1115 		 */
1116 		if ((vp->v_flag & (VONWORKLST | VISDIRTY | VOBJDIRTY)) ==
1117 		     VONWORKLST &&
1118 		    RB_EMPTY(&vp->v_rbdirty_tree)) {
1119 			vn_syncer_remove(vp, 0);
1120 		}
1121 	}
1122 }
1123 
1124 /*
1125  * Create a vnode for a block device.  Used for mounting the root file
1126  * system.
1127  *
1128  * A vref()'d vnode is returned.
1129  */
1130 extern struct vop_ops *devfs_vnode_dev_vops_p;
1131 int
1132 bdevvp(cdev_t dev, struct vnode **vpp)
1133 {
1134 	struct vnode *vp;
1135 	struct vnode *nvp;
1136 	int error;
1137 
1138 	if (dev == NULL) {
1139 		*vpp = NULLVP;
1140 		return (ENXIO);
1141 	}
1142 	error = getspecialvnode(VT_NON, NULL, &devfs_vnode_dev_vops_p,
1143 				&nvp, 0, 0);
1144 	if (error) {
1145 		*vpp = NULLVP;
1146 		return (error);
1147 	}
1148 	vp = nvp;
1149 	vp->v_type = VCHR;
1150 #if 0
1151 	vp->v_rdev = dev;
1152 #endif
1153 	v_associate_rdev(vp, dev);
1154 	vp->v_umajor = dev->si_umajor;
1155 	vp->v_uminor = dev->si_uminor;
1156 	vx_unlock(vp);
1157 	*vpp = vp;
1158 	return (0);
1159 }
1160 
1161 int
1162 v_associate_rdev(struct vnode *vp, cdev_t dev)
1163 {
1164 	if (dev == NULL)
1165 		return(ENXIO);
1166 	if (dev_is_good(dev) == 0)
1167 		return(ENXIO);
1168 	KKASSERT(vp->v_rdev == NULL);
1169 	vp->v_rdev = reference_dev(dev);
1170 	lwkt_gettoken(&spechash_token);
1171 	SLIST_INSERT_HEAD(&dev->si_hlist, vp, v_cdevnext);
1172 	lwkt_reltoken(&spechash_token);
1173 	return(0);
1174 }
1175 
1176 void
1177 v_release_rdev(struct vnode *vp)
1178 {
1179 	cdev_t dev;
1180 
1181 	if ((dev = vp->v_rdev) != NULL) {
1182 		lwkt_gettoken(&spechash_token);
1183 		SLIST_REMOVE(&dev->si_hlist, vp, vnode, v_cdevnext);
1184 		vp->v_rdev = NULL;
1185 		release_dev(dev);
1186 		lwkt_reltoken(&spechash_token);
1187 	}
1188 }
1189 
1190 /*
1191  * Add a vnode to the alias list hung off the cdev_t.  We only associate
1192  * the device number with the vnode.  The actual device is not associated
1193  * until the vnode is opened (usually in spec_open()), and will be
1194  * disassociated on last close.
1195  */
1196 void
1197 addaliasu(struct vnode *nvp, int x, int y)
1198 {
1199 	if (nvp->v_type != VBLK && nvp->v_type != VCHR)
1200 		panic("addaliasu on non-special vnode");
1201 	nvp->v_umajor = x;
1202 	nvp->v_uminor = y;
1203 }
1204 
1205 /*
1206  * Simple call that a filesystem can make to try to get rid of a
1207  * vnode.  It will fail if anyone is referencing the vnode (including
1208  * the caller).
1209  *
1210  * The filesystem can check whether its in-memory inode structure still
1211  * references the vp on return.
1212  *
1213  * May only be called if the vnode is in a known state (i.e. being prevented
1214  * from being deallocated by some other condition such as a vfs inode hold).
1215  */
1216 void
1217 vclean_unlocked(struct vnode *vp)
1218 {
1219 	vx_get(vp);
1220 	if (VREFCNT(vp) <= 1)
1221 		vgone_vxlocked(vp);
1222 	vx_put(vp);
1223 }
1224 
1225 /*
1226  * Disassociate a vnode from its underlying filesystem.
1227  *
1228  * The vnode must be VX locked and referenced.  In all normal situations
1229  * there are no active references.  If vclean_vxlocked() is called while
1230  * there are active references, the vnode is being ripped out and we have
1231  * to call VOP_CLOSE() as appropriate before we can reclaim it.
1232  */
1233 void
1234 vclean_vxlocked(struct vnode *vp, int flags)
1235 {
1236 	int active;
1237 	int n;
1238 	vm_object_t object;
1239 	struct namecache *ncp;
1240 
1241 	/*
1242 	 * If the vnode has already been reclaimed we have nothing to do.
1243 	 */
1244 	if (vp->v_flag & VRECLAIMED)
1245 		return;
1246 
1247 	/*
1248 	 * Set flag to interlock operation, flag finalization to ensure
1249 	 * that the vnode winds up on the inactive list, and set v_act to 0.
1250 	 */
1251 	vsetflags(vp, VRECLAIMED);
1252 	atomic_set_int(&vp->v_refcnt, VREF_FINALIZE);
1253 	vp->v_act = 0;
1254 
1255 	if (verbose_reclaims) {
1256 		if ((ncp = TAILQ_FIRST(&vp->v_namecache)) != NULL)
1257 			kprintf("Debug: reclaim %p %s\n", vp, ncp->nc_name);
1258 	}
1259 
1260 	/*
1261 	 * Scrap the vfs cache
1262 	 */
1263 	while (cache_inval_vp(vp, 0) != 0) {
1264 		kprintf("Warning: vnode %p clean/cache_resolution "
1265 			"race detected\n", vp);
1266 		tsleep(vp, 0, "vclninv", 2);
1267 	}
1268 
1269 	/*
1270 	 * Check to see if the vnode is in use. If so we have to reference it
1271 	 * before we clean it out so that its count cannot fall to zero and
1272 	 * generate a race against ourselves to recycle it.
1273 	 */
1274 	active = (VREFCNT(vp) > 0);
1275 
1276 	/*
1277 	 * Clean out any buffers associated with the vnode and destroy its
1278 	 * object, if it has one.
1279 	 */
1280 	vinvalbuf(vp, V_SAVE, 0, 0);
1281 
1282 	/*
1283 	 * If purging an active vnode (typically during a forced unmount
1284 	 * or reboot), it must be closed and deactivated before being
1285 	 * reclaimed.  This isn't really all that safe, but what can
1286 	 * we do? XXX.
1287 	 *
1288 	 * Note that neither of these routines unlocks the vnode.
1289 	 */
1290 	if (active && (flags & DOCLOSE)) {
1291 		while ((n = vp->v_opencount) != 0) {
1292 			if (vp->v_writecount)
1293 				VOP_CLOSE(vp, FWRITE|FNONBLOCK, NULL);
1294 			else
1295 				VOP_CLOSE(vp, FNONBLOCK, NULL);
1296 			if (vp->v_opencount == n) {
1297 				kprintf("Warning: unable to force-close"
1298 				       " vnode %p\n", vp);
1299 				break;
1300 			}
1301 		}
1302 	}
1303 
1304 	/*
1305 	 * If the vnode has not been deactivated, deactivated it.  Deactivation
1306 	 * can create new buffers and VM pages so we have to call vinvalbuf()
1307 	 * again to make sure they all get flushed.
1308 	 *
1309 	 * This can occur if a file with a link count of 0 needs to be
1310 	 * truncated.
1311 	 *
1312 	 * If the vnode is already dead don't try to deactivate it.
1313 	 */
1314 	if ((vp->v_flag & VINACTIVE) == 0) {
1315 		vsetflags(vp, VINACTIVE);
1316 		if (vp->v_mount)
1317 			VOP_INACTIVE(vp);
1318 		vinvalbuf(vp, V_SAVE, 0, 0);
1319 	}
1320 
1321 	/*
1322 	 * If the vnode has an object, destroy it.
1323 	 */
1324 	while ((object = vp->v_object) != NULL) {
1325 		vm_object_hold(object);
1326 		if (object == vp->v_object)
1327 			break;
1328 		vm_object_drop(object);
1329 	}
1330 
1331 	if (object != NULL) {
1332 		if (object->ref_count == 0) {
1333 			if ((object->flags & OBJ_DEAD) == 0)
1334 				vm_object_terminate(object);
1335 			vm_object_drop(object);
1336 			vclrflags(vp, VOBJBUF);
1337 		} else {
1338 			vm_pager_deallocate(object);
1339 			vclrflags(vp, VOBJBUF);
1340 			vm_object_drop(object);
1341 		}
1342 	}
1343 	KKASSERT((vp->v_flag & VOBJBUF) == 0);
1344 
1345 	if (vp->v_flag & VOBJDIRTY)
1346 		vclrobjdirty(vp);
1347 
1348 	/*
1349 	 * Reclaim the vnode if not already dead.
1350 	 */
1351 	if (vp->v_mount && VOP_RECLAIM(vp))
1352 		panic("vclean: cannot reclaim");
1353 
1354 	/*
1355 	 * Done with purge, notify sleepers of the grim news.
1356 	 */
1357 	vp->v_ops = &dead_vnode_vops_p;
1358 	vn_gone(vp);
1359 	vp->v_tag = VT_NON;
1360 
1361 	/*
1362 	 * If we are destroying an active vnode, reactivate it now that
1363 	 * we have reassociated it with deadfs.  This prevents the system
1364 	 * from crashing on the vnode due to it being unexpectedly marked
1365 	 * as inactive or reclaimed.
1366 	 */
1367 	if (active && (flags & DOCLOSE)) {
1368 		vclrflags(vp, VINACTIVE | VRECLAIMED);
1369 	}
1370 }
1371 
1372 /*
1373  * Eliminate all activity associated with the requested vnode
1374  * and with all vnodes aliased to the requested vnode.
1375  *
1376  * The vnode must be referenced but should not be locked.
1377  */
1378 int
1379 vrevoke(struct vnode *vp, struct ucred *cred)
1380 {
1381 	struct vnode *vq;
1382 	struct vnode *vqn;
1383 	cdev_t dev;
1384 	int error;
1385 
1386 	/*
1387 	 * If the vnode has a device association, scrap all vnodes associated
1388 	 * with the device.  Don't let the device disappear on us while we
1389 	 * are scrapping the vnodes.
1390 	 *
1391 	 * The passed vp will probably show up in the list, do not VX lock
1392 	 * it twice!
1393 	 *
1394 	 * Releasing the vnode's rdev here can mess up specfs's call to
1395 	 * device close, so don't do it.  The vnode has been disassociated
1396 	 * and the device will be closed after the last ref on the related
1397 	 * fp goes away (if not still open by e.g. the kernel).
1398 	 */
1399 	if (vp->v_type != VCHR) {
1400 		error = fdrevoke(vp, DTYPE_VNODE, cred);
1401 		return (error);
1402 	}
1403 	if ((dev = vp->v_rdev) == NULL) {
1404 		return(0);
1405 	}
1406 	reference_dev(dev);
1407 	lwkt_gettoken(&spechash_token);
1408 
1409 restart:
1410 	vqn = SLIST_FIRST(&dev->si_hlist);
1411 	if (vqn)
1412 		vhold(vqn);
1413 	while ((vq = vqn) != NULL) {
1414 		if (VREFCNT(vq) > 0) {
1415 			vref(vq);
1416 			fdrevoke(vq, DTYPE_VNODE, cred);
1417 			/*v_release_rdev(vq);*/
1418 			vrele(vq);
1419 			if (vq->v_rdev != dev) {
1420 				vdrop(vq);
1421 				goto restart;
1422 			}
1423 		}
1424 		vqn = SLIST_NEXT(vq, v_cdevnext);
1425 		if (vqn)
1426 			vhold(vqn);
1427 		vdrop(vq);
1428 	}
1429 	lwkt_reltoken(&spechash_token);
1430 	dev_drevoke(dev);
1431 	release_dev(dev);
1432 	return (0);
1433 }
1434 
1435 /*
1436  * This is called when the object underlying a vnode is being destroyed,
1437  * such as in a remove().  Try to recycle the vnode immediately if the
1438  * only active reference is our reference.
1439  *
1440  * Directory vnodes in the namecache with children cannot be immediately
1441  * recycled because numerous VOP_N*() ops require them to be stable.
1442  *
1443  * To avoid recursive recycling from VOP_INACTIVE implemenetations this
1444  * function is a NOP if VRECLAIMED is already set.
1445  */
1446 int
1447 vrecycle(struct vnode *vp)
1448 {
1449 	if (VREFCNT(vp) <= 1 && (vp->v_flag & VRECLAIMED) == 0) {
1450 		if (cache_inval_vp_nonblock(vp))
1451 			return(0);
1452 		vgone_vxlocked(vp);
1453 		return (1);
1454 	}
1455 	return (0);
1456 }
1457 
1458 /*
1459  * Return the maximum I/O size allowed for strategy calls on VP.
1460  *
1461  * If vp is VCHR or VBLK we dive the device, otherwise we use
1462  * the vp's mount info.
1463  *
1464  * The returned value is clamped at MAXPHYS as most callers cannot use
1465  * buffers larger than that size.
1466  */
1467 int
1468 vmaxiosize(struct vnode *vp)
1469 {
1470 	int maxiosize;
1471 
1472 	if (vp->v_type == VBLK || vp->v_type == VCHR)
1473 		maxiosize = vp->v_rdev->si_iosize_max;
1474 	else
1475 		maxiosize = vp->v_mount->mnt_iosize_max;
1476 
1477 	if (maxiosize > MAXPHYS)
1478 		maxiosize = MAXPHYS;
1479 	return (maxiosize);
1480 }
1481 
1482 /*
1483  * Eliminate all activity associated with a vnode in preparation for
1484  * destruction.
1485  *
1486  * The vnode must be VX locked and refd and will remain VX locked and refd
1487  * on return.  This routine may be called with the vnode in any state, as
1488  * long as it is VX locked.  The vnode will be cleaned out and marked
1489  * VRECLAIMED but will not actually be reused until all existing refs and
1490  * holds go away.
1491  *
1492  * NOTE: This routine may be called on a vnode which has not yet been
1493  * already been deactivated (VOP_INACTIVE), or on a vnode which has
1494  * already been reclaimed.
1495  *
1496  * This routine is not responsible for placing us back on the freelist.
1497  * Instead, it happens automatically when the caller releases the VX lock
1498  * (assuming there aren't any other references).
1499  */
1500 void
1501 vgone_vxlocked(struct vnode *vp)
1502 {
1503 	/*
1504 	 * assert that the VX lock is held.  This is an absolute requirement
1505 	 * now for vgone_vxlocked() to be called.
1506 	 */
1507 	KKASSERT(lockinuse(&vp->v_lock));
1508 
1509 	/*
1510 	 * Clean out the filesystem specific data and set the VRECLAIMED
1511 	 * bit.  Also deactivate the vnode if necessary.
1512 	 *
1513 	 * The vnode should have automatically been removed from the syncer
1514 	 * list as syncer/dirty flags cleared during the cleaning.
1515 	 */
1516 	vclean_vxlocked(vp, DOCLOSE);
1517 
1518 	/*
1519 	 * Normally panic if the vnode is still dirty, unless we are doing
1520 	 * a forced unmount (tmpfs typically).
1521 	 */
1522 	if (vp->v_flag & VONWORKLST) {
1523 		if (vp->v_mount->mnt_kern_flag & MNTK_UNMOUNTF) {
1524 			/* force removal */
1525 			vn_syncer_remove(vp, 1);
1526 		} else {
1527 			panic("vp %p still dirty in vgone after flush", vp);
1528 		}
1529 	}
1530 
1531 	/*
1532 	 * Delete from old mount point vnode list, if on one.
1533 	 */
1534 	if (vp->v_mount != NULL) {
1535 		KKASSERT(vp->v_data == NULL);
1536 		insmntque(vp, NULL);
1537 	}
1538 
1539 	/*
1540 	 * If special device, remove it from special device alias list
1541 	 * if it is on one.  This should normally only occur if a vnode is
1542 	 * being revoked as the device should otherwise have been released
1543 	 * naturally.
1544 	 */
1545 	if ((vp->v_type == VBLK || vp->v_type == VCHR) && vp->v_rdev != NULL) {
1546 		v_release_rdev(vp);
1547 	}
1548 
1549 	/*
1550 	 * Set us to VBAD
1551 	 */
1552 	vp->v_type = VBAD;
1553 }
1554 
1555 /*
1556  * Lookup a vnode by device number.
1557  *
1558  * Returns non-zero and *vpp set to a vref'd vnode on success.
1559  * Returns zero on failure.
1560  */
1561 int
1562 vfinddev(cdev_t dev, enum vtype type, struct vnode **vpp)
1563 {
1564 	struct vnode *vp;
1565 
1566 	lwkt_gettoken(&spechash_token);
1567 	SLIST_FOREACH(vp, &dev->si_hlist, v_cdevnext) {
1568 		if (type == vp->v_type) {
1569 			*vpp = vp;
1570 			vref(vp);
1571 			lwkt_reltoken(&spechash_token);
1572 			return (1);
1573 		}
1574 	}
1575 	lwkt_reltoken(&spechash_token);
1576 	return (0);
1577 }
1578 
1579 /*
1580  * Calculate the total number of references to a special device.  This
1581  * routine may only be called for VBLK and VCHR vnodes since v_rdev is
1582  * an overloaded field.  Since udev2dev can now return NULL, we have
1583  * to check for a NULL v_rdev.
1584  */
1585 int
1586 count_dev(cdev_t dev)
1587 {
1588 	struct vnode *vp;
1589 	int count = 0;
1590 
1591 	if (SLIST_FIRST(&dev->si_hlist)) {
1592 		lwkt_gettoken(&spechash_token);
1593 		SLIST_FOREACH(vp, &dev->si_hlist, v_cdevnext) {
1594 			count += vp->v_opencount;
1595 		}
1596 		lwkt_reltoken(&spechash_token);
1597 	}
1598 	return(count);
1599 }
1600 
1601 int
1602 vcount(struct vnode *vp)
1603 {
1604 	if (vp->v_rdev == NULL)
1605 		return(0);
1606 	return(count_dev(vp->v_rdev));
1607 }
1608 
1609 /*
1610  * Initialize VMIO for a vnode.  This routine MUST be called before a
1611  * VFS can issue buffer cache ops on a vnode.  It is typically called
1612  * when a vnode is initialized from its inode.
1613  */
1614 int
1615 vinitvmio(struct vnode *vp, off_t filesize, int blksize, int boff)
1616 {
1617 	vm_object_t object;
1618 	int error = 0;
1619 
1620 	object = vp->v_object;
1621 	if (object) {
1622 		vm_object_hold(object);
1623 		KKASSERT(vp->v_object == object);
1624 	}
1625 
1626 	if (object == NULL) {
1627 		object = vnode_pager_alloc(vp, filesize, 0, 0, blksize, boff);
1628 
1629 		/*
1630 		 * Dereference the reference we just created.  This assumes
1631 		 * that the object is associated with the vp.  Allow it to
1632 		 * have zero refs.  It cannot be destroyed as long as it
1633 		 * is associated with the vnode.
1634 		 */
1635 		vm_object_hold(object);
1636 		atomic_add_int(&object->ref_count, -1);
1637 		vrele(vp);
1638 	} else {
1639 		KKASSERT((object->flags & OBJ_DEAD) == 0);
1640 	}
1641 	KASSERT(vp->v_object != NULL, ("vinitvmio: NULL object"));
1642 	vsetflags(vp, VOBJBUF);
1643 	vm_object_drop(object);
1644 
1645 	return (error);
1646 }
1647 
1648 
1649 /*
1650  * Print out a description of a vnode.
1651  */
1652 static char *typename[] =
1653 {"VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD"};
1654 
1655 void
1656 vprint(char *label, struct vnode *vp)
1657 {
1658 	char buf[96];
1659 
1660 	if (label != NULL)
1661 		kprintf("%s: %p: ", label, (void *)vp);
1662 	else
1663 		kprintf("%p: ", (void *)vp);
1664 	kprintf("type %s, refcnt %08x, writecount %d, holdcnt %d,",
1665 		typename[vp->v_type],
1666 		vp->v_refcnt, vp->v_writecount, vp->v_auxrefs);
1667 	buf[0] = '\0';
1668 	if (vp->v_flag & VROOT)
1669 		strcat(buf, "|VROOT");
1670 	if (vp->v_flag & VPFSROOT)
1671 		strcat(buf, "|VPFSROOT");
1672 	if (vp->v_flag & VTEXT)
1673 		strcat(buf, "|VTEXT");
1674 	if (vp->v_flag & VSYSTEM)
1675 		strcat(buf, "|VSYSTEM");
1676 	if (vp->v_flag & VOBJBUF)
1677 		strcat(buf, "|VOBJBUF");
1678 	if (buf[0] != '\0')
1679 		kprintf(" flags (%s)", &buf[1]);
1680 	if (vp->v_data == NULL) {
1681 		kprintf("\n");
1682 	} else {
1683 		kprintf("\n\t");
1684 		VOP_PRINT(vp);
1685 	}
1686 }
1687 
1688 /*
1689  * Do the usual access checking.
1690  * file_mode, uid and gid are from the vnode in question,
1691  * while acc_mode and cred are from the VOP_ACCESS parameter list
1692  */
1693 int
1694 vaccess(enum vtype type, mode_t file_mode, uid_t uid, gid_t gid,
1695     mode_t acc_mode, struct ucred *cred)
1696 {
1697 	mode_t mask;
1698 	int ismember;
1699 
1700 	/*
1701 	 * Super-user always gets read/write access, but execute access depends
1702 	 * on at least one execute bit being set.
1703 	 */
1704 	if (priv_check_cred(cred, PRIV_ROOT, 0) == 0) {
1705 		if ((acc_mode & VEXEC) && type != VDIR &&
1706 		    (file_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0)
1707 			return (EACCES);
1708 		return (0);
1709 	}
1710 
1711 	mask = 0;
1712 
1713 	/* Otherwise, check the owner. */
1714 	if (cred->cr_uid == uid) {
1715 		if (acc_mode & VEXEC)
1716 			mask |= S_IXUSR;
1717 		if (acc_mode & VREAD)
1718 			mask |= S_IRUSR;
1719 		if (acc_mode & VWRITE)
1720 			mask |= S_IWUSR;
1721 		return ((file_mode & mask) == mask ? 0 : EACCES);
1722 	}
1723 
1724 	/* Otherwise, check the groups. */
1725 	ismember = groupmember(gid, cred);
1726 	if (cred->cr_svgid == gid || ismember) {
1727 		if (acc_mode & VEXEC)
1728 			mask |= S_IXGRP;
1729 		if (acc_mode & VREAD)
1730 			mask |= S_IRGRP;
1731 		if (acc_mode & VWRITE)
1732 			mask |= S_IWGRP;
1733 		return ((file_mode & mask) == mask ? 0 : EACCES);
1734 	}
1735 
1736 	/* Otherwise, check everyone else. */
1737 	if (acc_mode & VEXEC)
1738 		mask |= S_IXOTH;
1739 	if (acc_mode & VREAD)
1740 		mask |= S_IROTH;
1741 	if (acc_mode & VWRITE)
1742 		mask |= S_IWOTH;
1743 	return ((file_mode & mask) == mask ? 0 : EACCES);
1744 }
1745 
1746 #ifdef DDB
1747 #include <ddb/ddb.h>
1748 
1749 static int db_show_locked_vnodes(struct mount *mp, void *data);
1750 
1751 /*
1752  * List all of the locked vnodes in the system.
1753  * Called when debugging the kernel.
1754  */
1755 DB_SHOW_COMMAND(lockedvnodes, lockedvnodes)
1756 {
1757 	kprintf("Locked vnodes\n");
1758 	mountlist_scan(db_show_locked_vnodes, NULL,
1759 			MNTSCAN_FORWARD|MNTSCAN_NOBUSY);
1760 }
1761 
1762 static int
1763 db_show_locked_vnodes(struct mount *mp, void *data __unused)
1764 {
1765 	struct vnode *vp;
1766 
1767 	TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
1768 		if (vn_islocked(vp))
1769 			vprint(NULL, vp);
1770 	}
1771 	return(0);
1772 }
1773 #endif
1774 
1775 /*
1776  * Top level filesystem related information gathering.
1777  */
1778 static int	sysctl_ovfs_conf (SYSCTL_HANDLER_ARGS);
1779 
1780 static int
1781 vfs_sysctl(SYSCTL_HANDLER_ARGS)
1782 {
1783 	int *name = (int *)arg1 - 1;	/* XXX */
1784 	u_int namelen = arg2 + 1;	/* XXX */
1785 	struct vfsconf *vfsp;
1786 	int maxtypenum;
1787 
1788 #if 1 || defined(COMPAT_PRELITE2)
1789 	/* Resolve ambiguity between VFS_VFSCONF and VFS_GENERIC. */
1790 	if (namelen == 1)
1791 		return (sysctl_ovfs_conf(oidp, arg1, arg2, req));
1792 #endif
1793 
1794 #ifdef notyet
1795 	/* all sysctl names at this level are at least name and field */
1796 	if (namelen < 2)
1797 		return (ENOTDIR);		/* overloaded */
1798 	if (name[0] != VFS_GENERIC) {
1799 		vfsp = vfsconf_find_by_typenum(name[0]);
1800 		if (vfsp == NULL)
1801 			return (EOPNOTSUPP);
1802 		return ((*vfsp->vfc_vfsops->vfs_sysctl)(&name[1], namelen - 1,
1803 		    oldp, oldlenp, newp, newlen, p));
1804 	}
1805 #endif
1806 	switch (name[1]) {
1807 	case VFS_MAXTYPENUM:
1808 		if (namelen != 2)
1809 			return (ENOTDIR);
1810 		maxtypenum = vfsconf_get_maxtypenum();
1811 		return (SYSCTL_OUT(req, &maxtypenum, sizeof(maxtypenum)));
1812 	case VFS_CONF:
1813 		if (namelen != 3)
1814 			return (ENOTDIR);	/* overloaded */
1815 		vfsp = vfsconf_find_by_typenum(name[2]);
1816 		if (vfsp == NULL)
1817 			return (EOPNOTSUPP);
1818 		return (SYSCTL_OUT(req, vfsp, sizeof *vfsp));
1819 	}
1820 	return (EOPNOTSUPP);
1821 }
1822 
1823 SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RD, vfs_sysctl,
1824 	"Generic filesystem");
1825 
1826 #if 1 || defined(COMPAT_PRELITE2)
1827 
1828 static int
1829 sysctl_ovfs_conf_iter(struct vfsconf *vfsp, void *data)
1830 {
1831 	int error;
1832 	struct ovfsconf ovfs;
1833 	struct sysctl_req *req = (struct sysctl_req*) data;
1834 
1835 	bzero(&ovfs, sizeof(ovfs));
1836 	ovfs.vfc_vfsops = vfsp->vfc_vfsops;	/* XXX used as flag */
1837 	strcpy(ovfs.vfc_name, vfsp->vfc_name);
1838 	ovfs.vfc_index = vfsp->vfc_typenum;
1839 	ovfs.vfc_refcount = vfsp->vfc_refcount;
1840 	ovfs.vfc_flags = vfsp->vfc_flags;
1841 	error = SYSCTL_OUT(req, &ovfs, sizeof ovfs);
1842 	if (error)
1843 		return error; /* abort iteration with error code */
1844 	else
1845 		return 0; /* continue iterating with next element */
1846 }
1847 
1848 static int
1849 sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS)
1850 {
1851 	return vfsconf_each(sysctl_ovfs_conf_iter, (void*)req);
1852 }
1853 
1854 #endif /* 1 || COMPAT_PRELITE2 */
1855 
1856 /*
1857  * Check to see if a filesystem is mounted on a block device.
1858  */
1859 int
1860 vfs_mountedon(struct vnode *vp)
1861 {
1862 	cdev_t dev;
1863 
1864 	if ((dev = vp->v_rdev) == NULL) {
1865 /*		if (vp->v_type != VBLK)
1866 			dev = get_dev(vp->v_uminor, vp->v_umajor); */
1867 	}
1868 	if (dev != NULL && dev->si_mountpoint)
1869 		return (EBUSY);
1870 	return (0);
1871 }
1872 
1873 /*
1874  * Unmount all filesystems. The list is traversed in reverse order
1875  * of mounting to avoid dependencies.
1876  *
1877  * We want the umountall to be able to break out of its loop if a
1878  * failure occurs, after scanning all possible mounts, so the callback
1879  * returns 0 on error.
1880  *
1881  * NOTE: Do not call mountlist_remove(mp) on error any more, this will
1882  *	 confuse mountlist_scan()'s unbusy check.
1883  */
1884 static int vfs_umountall_callback(struct mount *mp, void *data);
1885 
1886 void
1887 vfs_unmountall(int halting)
1888 {
1889 	int count;
1890 
1891 	do {
1892 		count = mountlist_scan(vfs_umountall_callback, &halting,
1893 				       MNTSCAN_REVERSE|MNTSCAN_NOBUSY);
1894 	} while (count);
1895 }
1896 
1897 static
1898 int
1899 vfs_umountall_callback(struct mount *mp, void *data)
1900 {
1901 	int error;
1902 	int halting = *(int *)data;
1903 
1904 	/*
1905 	 * NOTE: When halting, dounmount will disconnect but leave
1906 	 *	 certain mount points intact.  e.g. devfs.
1907 	 */
1908 	error = dounmount(mp, MNT_FORCE, halting);
1909 	if (error) {
1910 		kprintf("unmount of filesystem mounted from %s failed (",
1911 			mp->mnt_stat.f_mntfromname);
1912 		if (error == EBUSY)
1913 			kprintf("BUSY)\n");
1914 		else
1915 			kprintf("%d)\n", error);
1916 		return 0;
1917 	} else {
1918 		return 1;
1919 	}
1920 }
1921 
1922 /*
1923  * Checks the mount flags for parameter mp and put the names comma-separated
1924  * into a string buffer buf with a size limit specified by len.
1925  *
1926  * It returns the number of bytes written into buf, and (*errorp) will be
1927  * set to 0, EINVAL (if passed length is 0), or ENOSPC (supplied buffer was
1928  * not large enough).  The buffer will be 0-terminated if len was not 0.
1929  */
1930 size_t
1931 vfs_flagstostr(int flags, const struct mountctl_opt *optp,
1932 	       char *buf, size_t len, int *errorp)
1933 {
1934 	static const struct mountctl_opt optnames[] = {
1935 		{ MNT_RDONLY,           "read-only" },
1936 		{ MNT_SYNCHRONOUS,      "synchronous" },
1937 		{ MNT_NOEXEC,           "noexec" },
1938 		{ MNT_NOSUID,           "nosuid" },
1939 		{ MNT_NODEV,            "nodev" },
1940 		{ MNT_AUTOMOUNTED,      "automounted" },
1941 		{ MNT_ASYNC,            "asynchronous" },
1942 		{ MNT_SUIDDIR,          "suiddir" },
1943 		{ MNT_SOFTDEP,          "soft-updates" },
1944 		{ MNT_NOSYMFOLLOW,      "nosymfollow" },
1945 		{ MNT_TRIM,             "trim" },
1946 		{ MNT_NOATIME,          "noatime" },
1947 		{ MNT_NOCLUSTERR,       "noclusterr" },
1948 		{ MNT_NOCLUSTERW,       "noclusterw" },
1949 		{ MNT_EXRDONLY,         "NFS read-only" },
1950 		{ MNT_EXPORTED,         "NFS exported" },
1951 		/* Remaining NFS flags could come here */
1952 		{ MNT_LOCAL,            "local" },
1953 		{ MNT_QUOTA,            "with-quotas" },
1954 		/* { MNT_ROOTFS,           "rootfs" }, */
1955 		/* { MNT_IGNORE,           "ignore" }, */
1956 		{ 0,			NULL}
1957 	};
1958 	int bwritten;
1959 	int bleft;
1960 	int optlen;
1961 	int actsize;
1962 
1963 	*errorp = 0;
1964 	bwritten = 0;
1965 	bleft = len - 1;	/* leave room for trailing \0 */
1966 
1967 	/*
1968 	 * Checks the size of the string. If it contains
1969 	 * any data, then we will append the new flags to
1970 	 * it.
1971 	 */
1972 	actsize = strlen(buf);
1973 	if (actsize > 0)
1974 		buf += actsize;
1975 
1976 	/* Default flags if no flags passed */
1977 	if (optp == NULL)
1978 		optp = optnames;
1979 
1980 	if (bleft < 0) {	/* degenerate case, 0-length buffer */
1981 		*errorp = EINVAL;
1982 		return(0);
1983 	}
1984 
1985 	for (; flags && optp->o_opt; ++optp) {
1986 		if ((flags & optp->o_opt) == 0)
1987 			continue;
1988 		optlen = strlen(optp->o_name);
1989 		if (bwritten || actsize > 0) {
1990 			if (bleft < 2) {
1991 				*errorp = ENOSPC;
1992 				break;
1993 			}
1994 			buf[bwritten++] = ',';
1995 			buf[bwritten++] = ' ';
1996 			bleft -= 2;
1997 		}
1998 		if (bleft < optlen) {
1999 			*errorp = ENOSPC;
2000 			break;
2001 		}
2002 		bcopy(optp->o_name, buf + bwritten, optlen);
2003 		bwritten += optlen;
2004 		bleft -= optlen;
2005 		flags &= ~optp->o_opt;
2006 	}
2007 
2008 	/*
2009 	 * Space already reserved for trailing \0
2010 	 */
2011 	buf[bwritten] = 0;
2012 	return (bwritten);
2013 }
2014 
2015 /*
2016  * Build hash lists of net addresses and hang them off the mount point.
2017  * Called by ufs_mount() to set up the lists of export addresses.
2018  */
2019 static int
2020 vfs_hang_addrlist(struct mount *mp, struct netexport *nep,
2021 		const struct export_args *argp)
2022 {
2023 	struct netcred *np;
2024 	struct radix_node_head *rnh;
2025 	int i;
2026 	struct radix_node *rn;
2027 	struct sockaddr *saddr, *smask = NULL;
2028 	int error;
2029 
2030 	if (argp->ex_addrlen == 0) {
2031 		if (mp->mnt_flag & MNT_DEFEXPORTED)
2032 			return (EPERM);
2033 		np = &nep->ne_defexported;
2034 		np->netc_exflags = argp->ex_flags;
2035 		np->netc_anon = argp->ex_anon;
2036 		np->netc_anon.cr_ref = 1;
2037 		mp->mnt_flag |= MNT_DEFEXPORTED;
2038 		return (0);
2039 	}
2040 
2041 	if (argp->ex_addrlen < 0 || argp->ex_addrlen > MLEN)
2042 		return (EINVAL);
2043 	if (argp->ex_masklen < 0 || argp->ex_masklen > MLEN)
2044 		return (EINVAL);
2045 
2046 	i = sizeof(struct netcred) + argp->ex_addrlen + argp->ex_masklen;
2047 	np = (struct netcred *)kmalloc(i, M_NETCRED, M_WAITOK | M_ZERO);
2048 	saddr = (struct sockaddr *) (np + 1);
2049 	if ((error = copyin(argp->ex_addr, (caddr_t) saddr, argp->ex_addrlen)))
2050 		goto out;
2051 	if (saddr->sa_len > argp->ex_addrlen)
2052 		saddr->sa_len = argp->ex_addrlen;
2053 	if (argp->ex_masklen) {
2054 		smask = (struct sockaddr *)((caddr_t)saddr + argp->ex_addrlen);
2055 		error = copyin(argp->ex_mask, (caddr_t)smask, argp->ex_masklen);
2056 		if (error)
2057 			goto out;
2058 		if (smask->sa_len > argp->ex_masklen)
2059 			smask->sa_len = argp->ex_masklen;
2060 	}
2061 	NE_LOCK(nep);
2062 	if (nep->ne_maskhead == NULL) {
2063 		if (!rn_inithead((void **)&nep->ne_maskhead, NULL, 0)) {
2064 			error = ENOBUFS;
2065 			goto out;
2066 		}
2067 	}
2068 	if ((rnh = vfs_create_addrlist_af(saddr->sa_family, nep)) == NULL) {
2069 		error = ENOBUFS;
2070 		goto out;
2071 	}
2072 	rn = (*rnh->rnh_addaddr)((char *)saddr, (char *)smask, rnh,
2073 				 np->netc_rnodes);
2074 	NE_UNLOCK(nep);
2075 	if (rn == NULL || np != (struct netcred *)rn) {	/* already exists */
2076 		error = EPERM;
2077 		goto out;
2078 	}
2079 	np->netc_exflags = argp->ex_flags;
2080 	np->netc_anon = argp->ex_anon;
2081 	np->netc_anon.cr_ref = 1;
2082 	return (0);
2083 
2084 out:
2085 	kfree(np, M_NETCRED);
2086 	return (error);
2087 }
2088 
2089 /*
2090  * Free netcred structures installed in the netexport
2091  */
2092 static int
2093 vfs_free_netcred(struct radix_node *rn, void *w)
2094 {
2095 	struct radix_node_head *rnh = (struct radix_node_head *)w;
2096 
2097 	(*rnh->rnh_deladdr) (rn->rn_key, rn->rn_mask, rnh);
2098 	kfree(rn, M_NETCRED);
2099 
2100 	return (0);
2101 }
2102 
2103 /*
2104  * callback to free an element of the mask table installed in the
2105  * netexport.  These may be created indirectly and are not netcred
2106  * structures.
2107  */
2108 static int
2109 vfs_free_netcred_mask(struct radix_node *rn, void *w)
2110 {
2111 	struct radix_node_head *rnh = (struct radix_node_head *)w;
2112 
2113 	(*rnh->rnh_deladdr) (rn->rn_key, rn->rn_mask, rnh);
2114 	kfree(rn, M_RTABLE);
2115 
2116 	return (0);
2117 }
2118 
2119 static struct radix_node_head *
2120 vfs_create_addrlist_af(int af, struct netexport *nep)
2121 {
2122 	struct radix_node_head *rnh = NULL;
2123 #if defined(INET) || defined(INET6)
2124 	struct radix_node_head *maskhead = nep->ne_maskhead;
2125 	int off;
2126 #endif
2127 
2128 	NE_ASSERT_LOCKED(nep);
2129 #if defined(INET) || defined(INET6)
2130 	KKASSERT(maskhead != NULL);
2131 #endif
2132 	switch (af) {
2133 #ifdef INET
2134 	case AF_INET:
2135 		if ((rnh = nep->ne_inethead) == NULL) {
2136 			off = offsetof(struct sockaddr_in, sin_addr) << 3;
2137 			if (!rn_inithead((void **)&rnh, maskhead, off))
2138 				return (NULL);
2139 			nep->ne_inethead = rnh;
2140 		}
2141 		break;
2142 #endif
2143 #ifdef INET6
2144 	case AF_INET6:
2145 		if ((rnh = nep->ne_inet6head) == NULL) {
2146 			off = offsetof(struct sockaddr_in6, sin6_addr) << 3;
2147 			if (!rn_inithead((void **)&rnh, maskhead, off))
2148 				return (NULL);
2149 			nep->ne_inet6head = rnh;
2150 		}
2151 		break;
2152 #endif
2153 	}
2154 	return (rnh);
2155 }
2156 
2157 /*
2158  * helper function for freeing netcred elements
2159  */
2160 static void
2161 vfs_free_addrlist_af(struct radix_node_head **prnh)
2162 {
2163 	struct radix_node_head *rnh = *prnh;
2164 
2165 	(*rnh->rnh_walktree) (rnh, vfs_free_netcred, rnh);
2166 	kfree(rnh, M_RTABLE);
2167 	*prnh = NULL;
2168 }
2169 
2170 /*
2171  * helper function for freeing mask elements
2172  */
2173 static void
2174 vfs_free_addrlist_masks(struct radix_node_head **prnh)
2175 {
2176 	struct radix_node_head *rnh = *prnh;
2177 
2178 	(*rnh->rnh_walktree) (rnh, vfs_free_netcred_mask, rnh);
2179 	kfree(rnh, M_RTABLE);
2180 	*prnh = NULL;
2181 }
2182 
2183 /*
2184  * Free the net address hash lists that are hanging off the mount points.
2185  */
2186 static void
2187 vfs_free_addrlist(struct netexport *nep)
2188 {
2189 	NE_LOCK(nep);
2190 	if (nep->ne_inethead != NULL)
2191 		vfs_free_addrlist_af(&nep->ne_inethead);
2192 	if (nep->ne_inet6head != NULL)
2193 		vfs_free_addrlist_af(&nep->ne_inet6head);
2194 	if (nep->ne_maskhead)
2195 		vfs_free_addrlist_masks(&nep->ne_maskhead);
2196 	NE_UNLOCK(nep);
2197 }
2198 
2199 int
2200 vfs_export(struct mount *mp, struct netexport *nep,
2201 	   const struct export_args *argp)
2202 {
2203 	int error;
2204 
2205 	if (argp->ex_flags & MNT_DELEXPORT) {
2206 		if (mp->mnt_flag & MNT_EXPUBLIC) {
2207 			vfs_setpublicfs(NULL, NULL, NULL);
2208 			mp->mnt_flag &= ~MNT_EXPUBLIC;
2209 		}
2210 		vfs_free_addrlist(nep);
2211 		mp->mnt_flag &= ~(MNT_EXPORTED | MNT_DEFEXPORTED);
2212 	}
2213 	if (argp->ex_flags & MNT_EXPORTED) {
2214 		if (argp->ex_flags & MNT_EXPUBLIC) {
2215 			if ((error = vfs_setpublicfs(mp, nep, argp)) != 0)
2216 				return (error);
2217 			mp->mnt_flag |= MNT_EXPUBLIC;
2218 		}
2219 		if ((error = vfs_hang_addrlist(mp, nep, argp)))
2220 			return (error);
2221 		mp->mnt_flag |= MNT_EXPORTED;
2222 	}
2223 	return (0);
2224 }
2225 
2226 
2227 /*
2228  * Set the publicly exported filesystem (WebNFS). Currently, only
2229  * one public filesystem is possible in the spec (RFC 2054 and 2055)
2230  */
2231 int
2232 vfs_setpublicfs(struct mount *mp, struct netexport *nep,
2233 		const struct export_args *argp)
2234 {
2235 	int error;
2236 	struct vnode *rvp;
2237 	char *cp;
2238 
2239 	/*
2240 	 * mp == NULL -> invalidate the current info, the FS is
2241 	 * no longer exported. May be called from either vfs_export
2242 	 * or unmount, so check if it hasn't already been done.
2243 	 */
2244 	if (mp == NULL) {
2245 		if (nfs_pub.np_valid) {
2246 			nfs_pub.np_valid = 0;
2247 			if (nfs_pub.np_index != NULL) {
2248 				kfree(nfs_pub.np_index, M_TEMP);
2249 				nfs_pub.np_index = NULL;
2250 			}
2251 		}
2252 		return (0);
2253 	}
2254 
2255 	/*
2256 	 * Only one allowed at a time.
2257 	 */
2258 	if (nfs_pub.np_valid != 0 && mp != nfs_pub.np_mount)
2259 		return (EBUSY);
2260 
2261 	/*
2262 	 * Get real filehandle for root of exported FS.
2263 	 */
2264 	bzero((caddr_t)&nfs_pub.np_handle, sizeof(nfs_pub.np_handle));
2265 	nfs_pub.np_handle.fh_fsid = mp->mnt_stat.f_fsid;
2266 
2267 	if ((error = VFS_ROOT(mp, &rvp)))
2268 		return (error);
2269 
2270 	if ((error = VFS_VPTOFH(rvp, &nfs_pub.np_handle.fh_fid)))
2271 		return (error);
2272 
2273 	vput(rvp);
2274 
2275 	/*
2276 	 * If an indexfile was specified, pull it in.
2277 	 */
2278 	if (argp->ex_indexfile != NULL) {
2279 		int namelen;
2280 
2281 		error = vn_get_namelen(rvp, &namelen);
2282 		if (error)
2283 			return (error);
2284 		nfs_pub.np_index = kmalloc(namelen, M_TEMP, M_WAITOK);
2285 		error = copyinstr(argp->ex_indexfile, nfs_pub.np_index,
2286 		    namelen, NULL);
2287 		if (!error) {
2288 			/*
2289 			 * Check for illegal filenames.
2290 			 */
2291 			for (cp = nfs_pub.np_index; *cp; cp++) {
2292 				if (*cp == '/') {
2293 					error = EINVAL;
2294 					break;
2295 				}
2296 			}
2297 		}
2298 		if (error) {
2299 			kfree(nfs_pub.np_index, M_TEMP);
2300 			return (error);
2301 		}
2302 	}
2303 
2304 	nfs_pub.np_mount = mp;
2305 	nfs_pub.np_valid = 1;
2306 	return (0);
2307 }
2308 
2309 struct netcred *
2310 vfs_export_lookup(struct mount *mp, struct netexport *nep,
2311 		struct sockaddr *nam)
2312 {
2313 	struct netcred *np;
2314 	struct radix_node_head *rnh;
2315 	struct sockaddr *saddr;
2316 
2317 	np = NULL;
2318 	if (mp->mnt_flag & MNT_EXPORTED) {
2319 		/*
2320 		 * Lookup in the export list first.
2321 		 */
2322 		NE_LOCK(nep);
2323 		if (nam != NULL) {
2324 			saddr = nam;
2325 			switch (saddr->sa_family) {
2326 #ifdef INET
2327 			case AF_INET:
2328 				rnh = nep->ne_inethead;
2329 				break;
2330 #endif
2331 #ifdef INET6
2332 			case AF_INET6:
2333 				rnh = nep->ne_inet6head;
2334 				break;
2335 #endif
2336 			default:
2337 				rnh = NULL;
2338 			}
2339 			if (rnh != NULL) {
2340 				np = (struct netcred *)
2341 					(*rnh->rnh_matchaddr)((char *)saddr,
2342 							      rnh);
2343 				if (np && np->netc_rnodes->rn_flags & RNF_ROOT)
2344 					np = NULL;
2345 			}
2346 		}
2347 		NE_UNLOCK(nep);
2348 		/*
2349 		 * If no address match, use the default if it exists.
2350 		 */
2351 		if (np == NULL && mp->mnt_flag & MNT_DEFEXPORTED)
2352 			np = &nep->ne_defexported;
2353 	}
2354 	return (np);
2355 }
2356 
2357 /*
2358  * perform msync on all vnodes under a mount point.  The mount point must
2359  * be locked.  This code is also responsible for lazy-freeing unreferenced
2360  * vnodes whos VM objects no longer contain pages.
2361  *
2362  * NOTE: MNT_WAIT still skips vnodes in the VXLOCK state.
2363  *
2364  * NOTE: XXX VOP_PUTPAGES and friends requires that the vnode be locked,
2365  * but vnode_pager_putpages() doesn't lock the vnode.  We have to do it
2366  * way up in this high level function.
2367  */
2368 static int vfs_msync_scan1(struct mount *mp, struct vnode *vp, void *data);
2369 static int vfs_msync_scan2(struct mount *mp, struct vnode *vp, void *data);
2370 
2371 void
2372 vfs_msync(struct mount *mp, int flags)
2373 {
2374 	int vmsc_flags;
2375 
2376 	/*
2377 	 * tmpfs sets this flag to prevent msync(), sync, and the
2378 	 * filesystem periodic syncer from trying to flush VM pages
2379 	 * to swap.  Only pure memory pressure flushes tmpfs VM pages
2380 	 * to swap.
2381 	 */
2382 	if (mp->mnt_kern_flag & MNTK_NOMSYNC)
2383 		return;
2384 
2385 	/*
2386 	 * Ok, scan the vnodes for work.  If the filesystem is using the
2387 	 * syncer thread feature we can use vsyncscan() instead of
2388 	 * vmntvnodescan(), which is much faster.
2389 	 */
2390 	vmsc_flags = VMSC_GETVP;
2391 	if (flags != MNT_WAIT)
2392 		vmsc_flags |= VMSC_NOWAIT;
2393 
2394 	if (mp->mnt_kern_flag & MNTK_THR_SYNC) {
2395 		vsyncscan(mp, vmsc_flags, vfs_msync_scan2,
2396 			  (void *)(intptr_t)flags);
2397 	} else {
2398 		vmntvnodescan(mp, vmsc_flags,
2399 			      vfs_msync_scan1, vfs_msync_scan2,
2400 			      (void *)(intptr_t)flags);
2401 	}
2402 }
2403 
2404 /*
2405  * scan1 is a fast pre-check.  There could be hundreds of thousands of
2406  * vnodes, we cannot afford to do anything heavy weight until we have a
2407  * fairly good indication that there is work to do.
2408  */
2409 static
2410 int
2411 vfs_msync_scan1(struct mount *mp, struct vnode *vp, void *data)
2412 {
2413 	int flags = (int)(intptr_t)data;
2414 
2415 	if ((vp->v_flag & VRECLAIMED) == 0) {
2416 		if (vp->v_auxrefs == 0 && VREFCNT(vp) <= 0 &&
2417 		    vp->v_object) {
2418 			return(0);	/* call scan2 */
2419 		}
2420 		if ((mp->mnt_flag & MNT_RDONLY) == 0 &&
2421 		    (vp->v_flag & VOBJDIRTY) &&
2422 		    (flags == MNT_WAIT || vn_islocked(vp) == 0)) {
2423 			return(0);	/* call scan2 */
2424 		}
2425 	}
2426 
2427 	/*
2428 	 * do not call scan2, continue the loop
2429 	 */
2430 	return(-1);
2431 }
2432 
2433 /*
2434  * This callback is handed a locked vnode.
2435  */
2436 static
2437 int
2438 vfs_msync_scan2(struct mount *mp, struct vnode *vp, void *data)
2439 {
2440 	vm_object_t obj;
2441 	int flags = (int)(intptr_t)data;
2442 	int opcflags;
2443 
2444 	if (vp->v_flag & VRECLAIMED)
2445 		return(0);
2446 
2447 	if ((mp->mnt_flag & MNT_RDONLY) == 0 && (vp->v_flag & VOBJDIRTY)) {
2448 		if ((obj = vp->v_object) != NULL) {
2449 			if (flags == MNT_WAIT) {
2450 				/*
2451 				 * VFS_MSYNC is called with MNT_WAIT when
2452 				 * unmounting.
2453 				 */
2454 				opcflags = OBJPC_SYNC;
2455 			} else if (vp->v_writecount || obj->ref_count) {
2456 				/*
2457 				 * VFS_MSYNC is otherwise called via the
2458 				 * periodic filesystem sync or the 'sync'
2459 				 * command.  Honor MADV_NOSYNC / MAP_NOSYNC
2460 				 * if the file is open for writing or memory
2461 				 * mapped.  Pages flagged PG_NOSYNC will not
2462 				 * be automatically flushed at this time.
2463 				 *
2464 				 * The obj->ref_count test is not perfect
2465 				 * since temporary refs may be present, but
2466 				 * the periodic filesystem sync will ultimately
2467 				 * catch it if the file is not open and not
2468 				 * mapped.
2469 				 */
2470 				opcflags = OBJPC_NOSYNC;
2471 			} else {
2472 				/*
2473 				 * If the file is no longer open for writing
2474 				 * and also no longer mapped, do not honor
2475 				 * MAP_NOSYNC.  That is, fully synchronize
2476 				 * the file.
2477 				 *
2478 				 * This still occurs on the periodic fs sync,
2479 				 * so frontend programs which turn the file
2480 				 * over quickly enough can still avoid the
2481 				 * sync, but ultimately we do want to flush
2482 				 * even MADV_NOSYNC pages once it is no longer
2483 				 * mapped or open for writing.
2484 				 */
2485 				opcflags = 0;
2486 			}
2487 			vm_object_page_clean(obj, 0, 0, opcflags);
2488 		}
2489 	}
2490 	return(0);
2491 }
2492 
2493 /*
2494  * Wake up anyone interested in vp because it is being revoked.
2495  */
2496 void
2497 vn_gone(struct vnode *vp)
2498 {
2499 	lwkt_gettoken(&vp->v_token);
2500 	KNOTE(&vp->v_pollinfo.vpi_kqinfo.ki_note, NOTE_REVOKE);
2501 	lwkt_reltoken(&vp->v_token);
2502 }
2503 
2504 /*
2505  * extract the cdev_t from a VBLK or VCHR.  The vnode must have been opened
2506  * (or v_rdev might be NULL).
2507  */
2508 cdev_t
2509 vn_todev(struct vnode *vp)
2510 {
2511 	if (vp->v_type != VBLK && vp->v_type != VCHR)
2512 		return (NULL);
2513 	KKASSERT(vp->v_rdev != NULL);
2514 	return (vp->v_rdev);
2515 }
2516 
2517 /*
2518  * Check if vnode represents a disk device.  The vnode does not need to be
2519  * opened.
2520  *
2521  * MPALMOSTSAFE
2522  */
2523 int
2524 vn_isdisk(struct vnode *vp, int *errp)
2525 {
2526 	cdev_t dev;
2527 
2528 	if (vp->v_type != VCHR) {
2529 		if (errp != NULL)
2530 			*errp = ENOTBLK;
2531 		return (0);
2532 	}
2533 
2534 	dev = vp->v_rdev;
2535 
2536 	if (dev == NULL) {
2537 		if (errp != NULL)
2538 			*errp = ENXIO;
2539 		return (0);
2540 	}
2541 	if (dev_is_good(dev) == 0) {
2542 		if (errp != NULL)
2543 			*errp = ENXIO;
2544 		return (0);
2545 	}
2546 	if ((dev_dflags(dev) & D_DISK) == 0) {
2547 		if (errp != NULL)
2548 			*errp = ENOTBLK;
2549 		return (0);
2550 	}
2551 	if (errp != NULL)
2552 		*errp = 0;
2553 	return (1);
2554 }
2555 
2556 int
2557 vn_get_namelen(struct vnode *vp, int *namelen)
2558 {
2559 	int error;
2560 	register_t retval[2];
2561 
2562 	error = VOP_PATHCONF(vp, _PC_NAME_MAX, retval);
2563 	if (error)
2564 		return (error);
2565 	*namelen = (int)retval[0];
2566 	return (0);
2567 }
2568 
2569 int
2570 vop_write_dirent(int *error, struct uio *uio, ino_t d_ino, uint8_t d_type,
2571 		uint16_t d_namlen, const char *d_name)
2572 {
2573 	struct dirent *dp;
2574 	size_t len;
2575 
2576 	len = _DIRENT_RECLEN(d_namlen);
2577 	if (len > uio->uio_resid)
2578 		return(1);
2579 
2580 	dp = kmalloc(len, M_TEMP, M_WAITOK | M_ZERO);
2581 
2582 	dp->d_ino = d_ino;
2583 	dp->d_namlen = d_namlen;
2584 	dp->d_type = d_type;
2585 	bcopy(d_name, dp->d_name, d_namlen);
2586 
2587 	*error = uiomove((caddr_t)dp, len, uio);
2588 
2589 	kfree(dp, M_TEMP);
2590 
2591 	return(0);
2592 }
2593 
2594 void
2595 vn_mark_atime(struct vnode *vp, struct thread *td)
2596 {
2597 	struct proc *p = td->td_proc;
2598 	struct ucred *cred = p ? p->p_ucred : proc0.p_ucred;
2599 
2600 	if ((vp->v_mount->mnt_flag & (MNT_NOATIME | MNT_RDONLY)) == 0) {
2601 		VOP_MARKATIME(vp, cred);
2602 	}
2603 }
2604 
2605 /*
2606  * Calculate the number of entries in an inode-related chained hash table.
2607  * With today's memory sizes, maxvnodes can wind up being a very large
2608  * number.  There is no reason to waste memory, so tolerate some stacking.
2609  */
2610 int
2611 vfs_inodehashsize(void)
2612 {
2613 	int hsize;
2614 
2615 	hsize = 32;
2616 	while (hsize < maxvnodes)
2617 		hsize <<= 1;
2618 	while (hsize > maxvnodes * 2)
2619 		hsize >>= 1;		/* nominal 2x stacking */
2620 
2621 	if (maxvnodes > 1024 * 1024)
2622 		hsize >>= 1;		/* nominal 8x stacking */
2623 
2624 	if (maxvnodes > 128 * 1024)
2625 		hsize >>= 1;		/* nominal 4x stacking */
2626 
2627 	if (hsize < 16)
2628 		hsize = 16;
2629 
2630 	return hsize;
2631 }
2632