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