xref: /dflybsd-src/sys/kern/vfs_subr.c (revision 2381583524bd7679b9e475f7ce722874d1eea618)
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. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *	This product includes software developed by the University of
21  *	California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  *	@(#)vfs_subr.c	8.31 (Berkeley) 5/26/95
39  * $FreeBSD: src/sys/kern/vfs_subr.c,v 1.249.2.30 2003/04/04 20:35:57 tegge Exp $
40  * $DragonFly: src/sys/kern/vfs_subr.c,v 1.113 2008/05/08 01:41:05 dillon Exp $
41  */
42 
43 /*
44  * External virtual filesystem routines
45  */
46 #include "opt_ddb.h"
47 
48 #include <sys/param.h>
49 #include <sys/systm.h>
50 #include <sys/buf.h>
51 #include <sys/conf.h>
52 #include <sys/dirent.h>
53 #include <sys/domain.h>
54 #include <sys/eventhandler.h>
55 #include <sys/fcntl.h>
56 #include <sys/kernel.h>
57 #include <sys/kthread.h>
58 #include <sys/malloc.h>
59 #include <sys/mbuf.h>
60 #include <sys/mount.h>
61 #include <sys/proc.h>
62 #include <sys/reboot.h>
63 #include <sys/socket.h>
64 #include <sys/stat.h>
65 #include <sys/sysctl.h>
66 #include <sys/syslog.h>
67 #include <sys/unistd.h>
68 #include <sys/vmmeter.h>
69 #include <sys/vnode.h>
70 
71 #include <machine/limits.h>
72 
73 #include <vm/vm.h>
74 #include <vm/vm_object.h>
75 #include <vm/vm_extern.h>
76 #include <vm/vm_kern.h>
77 #include <vm/pmap.h>
78 #include <vm/vm_map.h>
79 #include <vm/vm_page.h>
80 #include <vm/vm_pager.h>
81 #include <vm/vnode_pager.h>
82 #include <vm/vm_zone.h>
83 
84 #include <sys/buf2.h>
85 #include <sys/thread2.h>
86 #include <sys/sysref2.h>
87 
88 static MALLOC_DEFINE(M_NETADDR, "Export Host", "Export host address structure");
89 
90 int numvnodes;
91 SYSCTL_INT(_debug, OID_AUTO, numvnodes, CTLFLAG_RD, &numvnodes, 0, "");
92 int vfs_fastdev = 1;
93 SYSCTL_INT(_vfs, OID_AUTO, fastdev, CTLFLAG_RW, &vfs_fastdev, 0, "");
94 
95 enum vtype iftovt_tab[16] = {
96 	VNON, VFIFO, VCHR, VNON, VDIR, VNON, VBLK, VNON,
97 	VREG, VNON, VLNK, VNON, VSOCK, VNON, VNON, VBAD,
98 };
99 int vttoif_tab[9] = {
100 	0, S_IFREG, S_IFDIR, S_IFBLK, S_IFCHR, S_IFLNK,
101 	S_IFSOCK, S_IFIFO, S_IFMT,
102 };
103 
104 static int reassignbufcalls;
105 SYSCTL_INT(_vfs, OID_AUTO, reassignbufcalls, CTLFLAG_RW,
106 		&reassignbufcalls, 0, "");
107 static int reassignbufloops;
108 SYSCTL_INT(_vfs, OID_AUTO, reassignbufloops, CTLFLAG_RW,
109 		&reassignbufloops, 0, "");
110 static int reassignbufsortgood;
111 SYSCTL_INT(_vfs, OID_AUTO, reassignbufsortgood, CTLFLAG_RW,
112 		&reassignbufsortgood, 0, "");
113 static int reassignbufsortbad;
114 SYSCTL_INT(_vfs, OID_AUTO, reassignbufsortbad, CTLFLAG_RW,
115 		&reassignbufsortbad, 0, "");
116 static int reassignbufmethod = 1;
117 SYSCTL_INT(_vfs, OID_AUTO, reassignbufmethod, CTLFLAG_RW,
118 		&reassignbufmethod, 0, "");
119 
120 int	nfs_mount_type = -1;
121 static struct lwkt_token spechash_token;
122 struct nfs_public nfs_pub;	/* publicly exported FS */
123 
124 int desiredvnodes;
125 SYSCTL_INT(_kern, KERN_MAXVNODES, maxvnodes, CTLFLAG_RW,
126 		&desiredvnodes, 0, "Maximum number of vnodes");
127 
128 static void	vfs_free_addrlist (struct netexport *nep);
129 static int	vfs_free_netcred (struct radix_node *rn, void *w);
130 static int	vfs_hang_addrlist (struct mount *mp, struct netexport *nep,
131 				       const struct export_args *argp);
132 
133 extern int dev_ref_debug;
134 
135 /*
136  * Red black tree functions
137  */
138 static int rb_buf_compare(struct buf *b1, struct buf *b2);
139 RB_GENERATE2(buf_rb_tree, buf, b_rbnode, rb_buf_compare, off_t, b_loffset);
140 RB_GENERATE2(buf_rb_hash, buf, b_rbhash, rb_buf_compare, off_t, b_loffset);
141 
142 static int
143 rb_buf_compare(struct buf *b1, struct buf *b2)
144 {
145 	if (b1->b_loffset < b2->b_loffset)
146 		return(-1);
147 	if (b1->b_loffset > b2->b_loffset)
148 		return(1);
149 	return(0);
150 }
151 
152 /*
153  * Returns non-zero if the vnode is a candidate for lazy msyncing.
154  */
155 static __inline int
156 vshouldmsync(struct vnode *vp)
157 {
158 	if (vp->v_auxrefs != 0 || vp->v_sysref.refcnt > 0)
159 		return (0);		/* other holders */
160 	if (vp->v_object &&
161 	    (vp->v_object->ref_count || vp->v_object->resident_page_count)) {
162 		return (0);
163 	}
164 	return (1);
165 }
166 
167 /*
168  * Initialize the vnode management data structures.
169  *
170  * Called from vfsinit()
171  */
172 void
173 vfs_subr_init(void)
174 {
175 	/*
176 	 * Desired vnodes is a result of the physical page count
177 	 * and the size of kernel's heap.  It scales in proportion
178 	 * to the amount of available physical memory.  This can
179 	 * cause trouble on 64-bit and large memory platforms.
180 	 */
181 	/* desiredvnodes = maxproc + vmstats.v_page_count / 4; */
182 	desiredvnodes =
183 		min(maxproc + vmstats.v_page_count / 4,
184 		    2 * KvaSize /
185 		    (5 * (sizeof(struct vm_object) + sizeof(struct vnode))));
186 
187 	lwkt_token_init(&spechash_token);
188 }
189 
190 /*
191  * Knob to control the precision of file timestamps:
192  *
193  *   0 = seconds only; nanoseconds zeroed.
194  *   1 = seconds and nanoseconds, accurate within 1/HZ.
195  *   2 = seconds and nanoseconds, truncated to microseconds.
196  * >=3 = seconds and nanoseconds, maximum precision.
197  */
198 enum { TSP_SEC, TSP_HZ, TSP_USEC, TSP_NSEC };
199 
200 static int timestamp_precision = TSP_SEC;
201 SYSCTL_INT(_vfs, OID_AUTO, timestamp_precision, CTLFLAG_RW,
202 		&timestamp_precision, 0, "");
203 
204 /*
205  * Get a current timestamp.
206  */
207 void
208 vfs_timestamp(struct timespec *tsp)
209 {
210 	struct timeval tv;
211 
212 	switch (timestamp_precision) {
213 	case TSP_SEC:
214 		tsp->tv_sec = time_second;
215 		tsp->tv_nsec = 0;
216 		break;
217 	case TSP_HZ:
218 		getnanotime(tsp);
219 		break;
220 	case TSP_USEC:
221 		microtime(&tv);
222 		TIMEVAL_TO_TIMESPEC(&tv, tsp);
223 		break;
224 	case TSP_NSEC:
225 	default:
226 		nanotime(tsp);
227 		break;
228 	}
229 }
230 
231 /*
232  * Set vnode attributes to VNOVAL
233  */
234 void
235 vattr_null(struct vattr *vap)
236 {
237 	vap->va_type = VNON;
238 	vap->va_size = VNOVAL;
239 	vap->va_bytes = VNOVAL;
240 	vap->va_mode = VNOVAL;
241 	vap->va_nlink = VNOVAL;
242 	vap->va_uid = VNOVAL;
243 	vap->va_gid = VNOVAL;
244 	vap->va_fsid = VNOVAL;
245 	vap->va_fileid = VNOVAL;
246 	vap->va_blocksize = VNOVAL;
247 	vap->va_rmajor = VNOVAL;
248 	vap->va_rminor = VNOVAL;
249 	vap->va_atime.tv_sec = VNOVAL;
250 	vap->va_atime.tv_nsec = VNOVAL;
251 	vap->va_mtime.tv_sec = VNOVAL;
252 	vap->va_mtime.tv_nsec = VNOVAL;
253 	vap->va_ctime.tv_sec = VNOVAL;
254 	vap->va_ctime.tv_nsec = VNOVAL;
255 	vap->va_flags = VNOVAL;
256 	vap->va_gen = VNOVAL;
257 	vap->va_vaflags = 0;
258 	vap->va_fsmid = VNOVAL;
259 	/* va_*_uuid fields are only valid if related flags are set */
260 }
261 
262 /*
263  * Flush out and invalidate all buffers associated with a vnode.
264  *
265  * vp must be locked.
266  */
267 static int vinvalbuf_bp(struct buf *bp, void *data);
268 
269 struct vinvalbuf_bp_info {
270 	struct vnode *vp;
271 	int slptimeo;
272 	int lkflags;
273 	int flags;
274 };
275 
276 void
277 vupdatefsmid(struct vnode *vp)
278 {
279 	atomic_set_int(&vp->v_flag, VFSMID);
280 }
281 
282 int
283 vinvalbuf(struct vnode *vp, int flags, int slpflag, int slptimeo)
284 {
285 	struct vinvalbuf_bp_info info;
286 	int error;
287 	vm_object_t object;
288 
289 	/*
290 	 * If we are being asked to save, call fsync to ensure that the inode
291 	 * is updated.
292 	 */
293 	if (flags & V_SAVE) {
294 		crit_enter();
295 		while (vp->v_track_write.bk_active) {
296 			vp->v_track_write.bk_waitflag = 1;
297 			error = tsleep(&vp->v_track_write, slpflag,
298 					"vinvlbuf", slptimeo);
299 			if (error) {
300 				crit_exit();
301 				return (error);
302 			}
303 		}
304 		if (!RB_EMPTY(&vp->v_rbdirty_tree)) {
305 			crit_exit();
306 			if ((error = VOP_FSYNC(vp, MNT_WAIT)) != 0)
307 				return (error);
308 			crit_enter();
309 			if (vp->v_track_write.bk_active > 0 ||
310 			    !RB_EMPTY(&vp->v_rbdirty_tree))
311 				panic("vinvalbuf: dirty bufs");
312 		}
313 		crit_exit();
314   	}
315 	crit_enter();
316 	info.slptimeo = slptimeo;
317 	info.lkflags = LK_EXCLUSIVE | LK_SLEEPFAIL;
318 	if (slpflag & PCATCH)
319 		info.lkflags |= LK_PCATCH;
320 	info.flags = flags;
321 	info.vp = vp;
322 
323 	/*
324 	 * Flush the buffer cache until nothing is left.
325 	 */
326 	while (!RB_EMPTY(&vp->v_rbclean_tree) ||
327 	    !RB_EMPTY(&vp->v_rbdirty_tree)) {
328 		error = RB_SCAN(buf_rb_tree, &vp->v_rbclean_tree, NULL,
329 				vinvalbuf_bp, &info);
330 		if (error == 0) {
331 			error = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, NULL,
332 					vinvalbuf_bp, &info);
333 		}
334 	}
335 
336 	/*
337 	 * Wait for I/O to complete.  XXX needs cleaning up.  The vnode can
338 	 * have write I/O in-progress but if there is a VM object then the
339 	 * VM object can also have read-I/O in-progress.
340 	 */
341 	do {
342 		while (vp->v_track_write.bk_active > 0) {
343 			vp->v_track_write.bk_waitflag = 1;
344 			tsleep(&vp->v_track_write, 0, "vnvlbv", 0);
345 		}
346 		if ((object = vp->v_object) != NULL) {
347 			while (object->paging_in_progress)
348 				vm_object_pip_sleep(object, "vnvlbx");
349 		}
350 	} while (vp->v_track_write.bk_active > 0);
351 
352 	crit_exit();
353 
354 	/*
355 	 * Destroy the copy in the VM cache, too.
356 	 */
357 	if ((object = vp->v_object) != NULL) {
358 		vm_object_page_remove(object, 0, 0,
359 			(flags & V_SAVE) ? TRUE : FALSE);
360 	}
361 
362 	if (!RB_EMPTY(&vp->v_rbdirty_tree) || !RB_EMPTY(&vp->v_rbclean_tree))
363 		panic("vinvalbuf: flush failed");
364 	if (!RB_EMPTY(&vp->v_rbhash_tree))
365 		panic("vinvalbuf: flush failed, buffers still present");
366 	return (0);
367 }
368 
369 static int
370 vinvalbuf_bp(struct buf *bp, void *data)
371 {
372 	struct vinvalbuf_bp_info *info = data;
373 	int error;
374 
375 	if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
376 		error = BUF_TIMELOCK(bp, info->lkflags,
377 				     "vinvalbuf", info->slptimeo);
378 		if (error == 0) {
379 			BUF_UNLOCK(bp);
380 			error = ENOLCK;
381 		}
382 		if (error == ENOLCK)
383 			return(0);
384 		return (-error);
385 	}
386 
387 	KKASSERT(bp->b_vp == info->vp);
388 
389 	/*
390 	 * XXX Since there are no node locks for NFS, I
391 	 * believe there is a slight chance that a delayed
392 	 * write will occur while sleeping just above, so
393 	 * check for it.  Note that vfs_bio_awrite expects
394 	 * buffers to reside on a queue, while bwrite() and
395 	 * brelse() do not.
396 	 *
397 	 * NOTE:  NO B_LOCKED CHECK.  Also no buf_checkwrite()
398 	 * check.  This code will write out the buffer, period.
399 	 */
400 	if (((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI) &&
401 	    (info->flags & V_SAVE)) {
402 		if (bp->b_vp == info->vp) {
403 			if (bp->b_flags & B_CLUSTEROK) {
404 				vfs_bio_awrite(bp);
405 			} else {
406 				bremfree(bp);
407 				bp->b_flags |= B_ASYNC;
408 				bwrite(bp);
409 			}
410 		} else {
411 			bremfree(bp);
412 			bwrite(bp);
413 		}
414 	} else if (info->flags & V_SAVE) {
415 		/*
416 		 * Cannot set B_NOCACHE on a clean buffer as this will
417 		 * destroy the VM backing store which might actually
418 		 * be dirty (and unsynchronized).
419 		 */
420 		bremfree(bp);
421 		bp->b_flags |= (B_INVAL | B_RELBUF);
422 		bp->b_flags &= ~B_ASYNC;
423 		brelse(bp);
424 	} else {
425 		bremfree(bp);
426 		bp->b_flags |= (B_INVAL | B_NOCACHE | B_RELBUF);
427 		bp->b_flags &= ~B_ASYNC;
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 int
446 vtruncbuf(struct vnode *vp, off_t length, int blksize)
447 {
448 	off_t truncloffset;
449 	int count;
450 	const char *filename;
451 
452 	/*
453 	 * Round up to the *next* block, then destroy the buffers in question.
454 	 * Since we are only removing some of the buffers we must rely on the
455 	 * scan count to determine whether a loop is necessary.
456 	 */
457 	if ((count = (int)(length % blksize)) != 0)
458 		truncloffset = length + (blksize - count);
459 	else
460 		truncloffset = length;
461 
462 	crit_enter();
463 	do {
464 		count = RB_SCAN(buf_rb_tree, &vp->v_rbclean_tree,
465 				vtruncbuf_bp_trunc_cmp,
466 				vtruncbuf_bp_trunc, &truncloffset);
467 		count += RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree,
468 				vtruncbuf_bp_trunc_cmp,
469 				vtruncbuf_bp_trunc, &truncloffset);
470 	} while(count);
471 
472 	/*
473 	 * For safety, fsync any remaining metadata if the file is not being
474 	 * truncated to 0.  Since the metadata does not represent the entire
475 	 * dirty list we have to rely on the hit count to ensure that we get
476 	 * all of it.
477 	 */
478 	if (length > 0) {
479 		do {
480 			count = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree,
481 					vtruncbuf_bp_metasync_cmp,
482 					vtruncbuf_bp_metasync, vp);
483 		} while (count);
484 	}
485 
486 	/*
487 	 * Clean out any left over VM backing store.
488 	 */
489 	crit_exit();
490 
491 	vnode_pager_setsize(vp, length);
492 
493 	crit_enter();
494 
495 	/*
496 	 * It is possible to have in-progress I/O from buffers that were
497 	 * not part of the truncation.  This should not happen if we
498 	 * are truncating to 0-length.
499 	 */
500 	filename = TAILQ_FIRST(&vp->v_namecache) ?
501 		   TAILQ_FIRST(&vp->v_namecache)->nc_name : "?";
502 
503 	while ((count = vp->v_track_write.bk_active) > 0) {
504 		vp->v_track_write.bk_waitflag = 1;
505 		tsleep(&vp->v_track_write, 0, "vbtrunc", 0);
506 		if (length == 0) {
507 			kprintf("Warning: vtruncbuf(): Had to wait for "
508 			       "%d buffer I/Os to finish in %s\n",
509 			       count, filename);
510 		}
511 	}
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 		count = RB_SCAN(buf_rb_tree, &vp->v_rbclean_tree,
520 				vtruncbuf_bp_trunc_cmp,
521 				vtruncbuf_bp_trunc, &truncloffset);
522 		count += RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree,
523 				vtruncbuf_bp_trunc_cmp,
524 				vtruncbuf_bp_trunc, &truncloffset);
525 		if (count) {
526 			kprintf("Warning: vtruncbuf():  Had to re-clean %d "
527 			       "left over buffers in %s\n", count, filename);
528 		}
529 	} while(count);
530 
531 	crit_exit();
532 
533 	return (0);
534 }
535 
536 /*
537  * The callback buffer is beyond the new file EOF and must be destroyed.
538  * Note that the compare function must conform to the RB_SCAN's requirements.
539  */
540 static
541 int
542 vtruncbuf_bp_trunc_cmp(struct buf *bp, void *data)
543 {
544 	if (bp->b_loffset >= *(off_t *)data)
545 		return(0);
546 	return(-1);
547 }
548 
549 static
550 int
551 vtruncbuf_bp_trunc(struct buf *bp, void *data)
552 {
553 	/*
554 	 * Do not try to use a buffer we cannot immediately lock, but sleep
555 	 * anyway to prevent a livelock.  The code will loop until all buffers
556 	 * can be acted upon.
557 	 */
558 	if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
559 		if (BUF_LOCK(bp, LK_EXCLUSIVE|LK_SLEEPFAIL) == 0)
560 			BUF_UNLOCK(bp);
561 	} else {
562 		bremfree(bp);
563 		bp->b_flags |= (B_INVAL | B_RELBUF | B_NOCACHE);
564 		bp->b_flags &= ~B_ASYNC;
565 		brelse(bp);
566 	}
567 	return(1);
568 }
569 
570 /*
571  * Fsync all meta-data after truncating a file to be non-zero.  Only metadata
572  * blocks (with a negative loffset) are scanned.
573  * Note that the compare function must conform to the RB_SCAN's requirements.
574  */
575 static int
576 vtruncbuf_bp_metasync_cmp(struct buf *bp, void *data)
577 {
578 	if (bp->b_loffset < 0)
579 		return(0);
580 	return(1);
581 }
582 
583 static int
584 vtruncbuf_bp_metasync(struct buf *bp, void *data)
585 {
586 	struct vnode *vp = data;
587 
588 	if (bp->b_flags & B_DELWRI) {
589 		/*
590 		 * Do not try to use a buffer we cannot immediately lock,
591 		 * but sleep anyway to prevent a livelock.  The code will
592 		 * loop until all buffers can be acted upon.
593 		 */
594 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
595 			if (BUF_LOCK(bp, LK_EXCLUSIVE|LK_SLEEPFAIL) == 0)
596 				BUF_UNLOCK(bp);
597 		} else {
598 			bremfree(bp);
599 			if (bp->b_vp == vp) {
600 				bp->b_flags |= B_ASYNC;
601 			} else {
602 				bp->b_flags &= ~B_ASYNC;
603 			}
604 			bwrite(bp);
605 		}
606 		return(1);
607 	} else {
608 		return(0);
609 	}
610 }
611 
612 /*
613  * vfsync - implements a multipass fsync on a file which understands
614  * dependancies and meta-data.  The passed vnode must be locked.  The
615  * waitfor argument may be MNT_WAIT or MNT_NOWAIT, or MNT_LAZY.
616  *
617  * When fsyncing data asynchronously just do one consolidated pass starting
618  * with the most negative block number.  This may not get all the data due
619  * to dependancies.
620  *
621  * When fsyncing data synchronously do a data pass, then a metadata pass,
622  * then do additional data+metadata passes to try to get all the data out.
623  */
624 static int vfsync_wait_output(struct vnode *vp,
625 			    int (*waitoutput)(struct vnode *, struct thread *));
626 static int vfsync_data_only_cmp(struct buf *bp, void *data);
627 static int vfsync_meta_only_cmp(struct buf *bp, void *data);
628 static int vfsync_lazy_range_cmp(struct buf *bp, void *data);
629 static int vfsync_bp(struct buf *bp, void *data);
630 
631 struct vfsync_info {
632 	struct vnode *vp;
633 	int synchronous;
634 	int syncdeps;
635 	int lazycount;
636 	int lazylimit;
637 	int skippedbufs;
638 	int (*checkdef)(struct buf *);
639 };
640 
641 int
642 vfsync(struct vnode *vp, int waitfor, int passes,
643 	int (*checkdef)(struct buf *),
644 	int (*waitoutput)(struct vnode *, struct thread *))
645 {
646 	struct vfsync_info info;
647 	int error;
648 
649 	bzero(&info, sizeof(info));
650 	info.vp = vp;
651 	if ((info.checkdef = checkdef) == NULL)
652 		info.syncdeps = 1;
653 
654 	crit_enter_id("vfsync");
655 
656 	switch(waitfor) {
657 	case MNT_LAZY:
658 		/*
659 		 * Lazy (filesystem syncer typ) Asynchronous plus limit the
660 		 * number of data (not meta) pages we try to flush to 1MB.
661 		 * A non-zero return means that lazy limit was reached.
662 		 */
663 		info.lazylimit = 1024 * 1024;
664 		info.syncdeps = 1;
665 		error = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree,
666 				vfsync_lazy_range_cmp, vfsync_bp, &info);
667 		RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree,
668 				vfsync_meta_only_cmp, vfsync_bp, &info);
669 		if (error == 0)
670 			vp->v_lazyw = 0;
671 		else if (!RB_EMPTY(&vp->v_rbdirty_tree))
672 			vn_syncer_add_to_worklist(vp, 1);
673 		error = 0;
674 		break;
675 	case MNT_NOWAIT:
676 		/*
677 		 * Asynchronous.  Do a data-only pass and a meta-only pass.
678 		 */
679 		info.syncdeps = 1;
680 		RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, vfsync_data_only_cmp,
681 			vfsync_bp, &info);
682 		RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, vfsync_meta_only_cmp,
683 			vfsync_bp, &info);
684 		error = 0;
685 		break;
686 	default:
687 		/*
688 		 * Synchronous.  Do a data-only pass, then a meta-data+data
689 		 * pass, then additional integrated passes to try to get
690 		 * all the dependancies flushed.
691 		 */
692 		RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, vfsync_data_only_cmp,
693 			vfsync_bp, &info);
694 		error = vfsync_wait_output(vp, waitoutput);
695 		if (error == 0) {
696 			info.skippedbufs = 0;
697 			RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, NULL,
698 				vfsync_bp, &info);
699 			error = vfsync_wait_output(vp, waitoutput);
700 			if (info.skippedbufs)
701 				kprintf("Warning: vfsync skipped %d dirty bufs in pass2!\n", info.skippedbufs);
702 		}
703 		while (error == 0 && passes > 0 &&
704 		    !RB_EMPTY(&vp->v_rbdirty_tree)) {
705 			if (--passes == 0) {
706 				info.synchronous = 1;
707 				info.syncdeps = 1;
708 			}
709 			error = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, NULL,
710 				vfsync_bp, &info);
711 			if (error < 0)
712 				error = -error;
713 			info.syncdeps = 1;
714 			if (error == 0)
715 				error = vfsync_wait_output(vp, waitoutput);
716 		}
717 		break;
718 	}
719 	crit_exit_id("vfsync");
720 	return(error);
721 }
722 
723 static int
724 vfsync_wait_output(struct vnode *vp, int (*waitoutput)(struct vnode *, struct thread *))
725 {
726 	int error = 0;
727 
728 	while (vp->v_track_write.bk_active) {
729 		vp->v_track_write.bk_waitflag = 1;
730 		tsleep(&vp->v_track_write, 0, "fsfsn", 0);
731 	}
732 	if (waitoutput)
733 		error = waitoutput(vp, curthread);
734 	return(error);
735 }
736 
737 static int
738 vfsync_data_only_cmp(struct buf *bp, void *data)
739 {
740 	if (bp->b_loffset < 0)
741 		return(-1);
742 	return(0);
743 }
744 
745 static int
746 vfsync_meta_only_cmp(struct buf *bp, void *data)
747 {
748 	if (bp->b_loffset < 0)
749 		return(0);
750 	return(1);
751 }
752 
753 static int
754 vfsync_lazy_range_cmp(struct buf *bp, void *data)
755 {
756 	struct vfsync_info *info = data;
757 	if (bp->b_loffset < info->vp->v_lazyw)
758 		return(-1);
759 	return(0);
760 }
761 
762 static int
763 vfsync_bp(struct buf *bp, void *data)
764 {
765 	struct vfsync_info *info = data;
766 	struct vnode *vp = info->vp;
767 	int error;
768 
769 	/*
770 	 * if syncdeps is not set we do not try to write buffers which have
771 	 * dependancies.
772 	 */
773 	if (!info->synchronous && info->syncdeps == 0 && info->checkdef(bp))
774 		return(0);
775 
776 	/*
777 	 * Ignore buffers that we cannot immediately lock.  XXX
778 	 */
779 	if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
780 		kprintf("Warning: vfsync_bp skipping dirty buffer %p\n", bp);
781 		++info->skippedbufs;
782 		return(0);
783 	}
784 	if ((bp->b_flags & B_DELWRI) == 0)
785 		panic("vfsync_bp: buffer not dirty");
786 	if (vp != bp->b_vp)
787 		panic("vfsync_bp: buffer vp mismatch");
788 
789 	/*
790 	 * B_NEEDCOMMIT (primarily used by NFS) is a state where the buffer
791 	 * has been written but an additional handshake with the device
792 	 * is required before we can dispose of the buffer.  We have no idea
793 	 * how to do this so we have to skip these buffers.
794 	 */
795 	if (bp->b_flags & B_NEEDCOMMIT) {
796 		BUF_UNLOCK(bp);
797 		return(0);
798 	}
799 
800 	/*
801 	 * Ask bioops if it is ok to sync
802 	 */
803 	if (LIST_FIRST(&bp->b_dep) != NULL && buf_checkwrite(bp)) {
804 		bremfree(bp);
805 		brelse(bp);
806 		return(0);
807 	}
808 
809 	if (info->synchronous) {
810 		/*
811 		 * Synchronous flushing.  An error may be returned.
812 		 */
813 		bremfree(bp);
814 		crit_exit_id("vfsync");
815 		error = bwrite(bp);
816 		crit_enter_id("vfsync");
817 	} else {
818 		/*
819 		 * Asynchronous flushing.  A negative return value simply
820 		 * stops the scan and is not considered an error.  We use
821 		 * this to support limited MNT_LAZY flushes.
822 		 */
823 		vp->v_lazyw = bp->b_loffset;
824 		if ((vp->v_flag & VOBJBUF) && (bp->b_flags & B_CLUSTEROK)) {
825 			info->lazycount += vfs_bio_awrite(bp);
826 		} else {
827 			info->lazycount += bp->b_bufsize;
828 			bremfree(bp);
829 			crit_exit_id("vfsync");
830 			bawrite(bp);
831 			crit_enter_id("vfsync");
832 		}
833 		if (info->lazylimit && info->lazycount >= info->lazylimit)
834 			error = 1;
835 		else
836 			error = 0;
837 	}
838 	return(-error);
839 }
840 
841 /*
842  * Associate a buffer with a vnode.
843  */
844 void
845 bgetvp(struct vnode *vp, struct buf *bp)
846 {
847 	KASSERT(bp->b_vp == NULL, ("bgetvp: not free"));
848 	KKASSERT((bp->b_flags & (B_HASHED|B_DELWRI|B_VNCLEAN|B_VNDIRTY)) == 0);
849 
850 	vhold(vp);
851 	/*
852 	 * Insert onto list for new vnode.
853 	 */
854 	crit_enter();
855 	bp->b_vp = vp;
856 	bp->b_flags |= B_HASHED;
857 	if (buf_rb_hash_RB_INSERT(&vp->v_rbhash_tree, bp))
858 		panic("reassignbuf: dup lblk vp %p bp %p", vp, bp);
859 
860 	bp->b_flags |= B_VNCLEAN;
861 	if (buf_rb_tree_RB_INSERT(&vp->v_rbclean_tree, bp))
862 		panic("reassignbuf: dup lblk/clean vp %p bp %p", vp, bp);
863 	crit_exit();
864 }
865 
866 /*
867  * Disassociate a buffer from a vnode.
868  */
869 void
870 brelvp(struct buf *bp)
871 {
872 	struct vnode *vp;
873 
874 	KASSERT(bp->b_vp != NULL, ("brelvp: NULL"));
875 
876 	/*
877 	 * Delete from old vnode list, if on one.
878 	 */
879 	vp = bp->b_vp;
880 	crit_enter();
881 	if (bp->b_flags & (B_VNDIRTY | B_VNCLEAN)) {
882 		if (bp->b_flags & B_VNDIRTY)
883 			buf_rb_tree_RB_REMOVE(&vp->v_rbdirty_tree, bp);
884 		else
885 			buf_rb_tree_RB_REMOVE(&vp->v_rbclean_tree, bp);
886 		bp->b_flags &= ~(B_VNDIRTY | B_VNCLEAN);
887 	}
888 	if (bp->b_flags & B_HASHED) {
889 		buf_rb_hash_RB_REMOVE(&vp->v_rbhash_tree, bp);
890 		bp->b_flags &= ~B_HASHED;
891 	}
892 	if ((vp->v_flag & VONWORKLST) && RB_EMPTY(&vp->v_rbdirty_tree)) {
893 		vp->v_flag &= ~VONWORKLST;
894 		LIST_REMOVE(vp, v_synclist);
895 	}
896 	crit_exit();
897 	bp->b_vp = NULL;
898 	vdrop(vp);
899 }
900 
901 /*
902  * Reassign the buffer to the proper clean/dirty list based on B_DELWRI.
903  * This routine is called when the state of the B_DELWRI bit is changed.
904  */
905 void
906 reassignbuf(struct buf *bp)
907 {
908 	struct vnode *vp = bp->b_vp;
909 	int delay;
910 
911 	KKASSERT(vp != NULL);
912 	++reassignbufcalls;
913 
914 	/*
915 	 * B_PAGING flagged buffers cannot be reassigned because their vp
916 	 * is not fully linked in.
917 	 */
918 	if (bp->b_flags & B_PAGING)
919 		panic("cannot reassign paging buffer");
920 
921 	crit_enter();
922 	if (bp->b_flags & B_DELWRI) {
923 		/*
924 		 * Move to the dirty list, add the vnode to the worklist
925 		 */
926 		if (bp->b_flags & B_VNCLEAN) {
927 			buf_rb_tree_RB_REMOVE(&vp->v_rbclean_tree, bp);
928 			bp->b_flags &= ~B_VNCLEAN;
929 		}
930 		if ((bp->b_flags & B_VNDIRTY) == 0) {
931 			if (buf_rb_tree_RB_INSERT(&vp->v_rbdirty_tree, bp)) {
932 				panic("reassignbuf: dup lblk vp %p bp %p",
933 				      vp, bp);
934 			}
935 			bp->b_flags |= B_VNDIRTY;
936 		}
937 		if ((vp->v_flag & VONWORKLST) == 0) {
938 			switch (vp->v_type) {
939 			case VDIR:
940 				delay = dirdelay;
941 				break;
942 			case VCHR:
943 			case VBLK:
944 				if (vp->v_rdev &&
945 				    vp->v_rdev->si_mountpoint != NULL) {
946 					delay = metadelay;
947 					break;
948 				}
949 				/* fall through */
950 			default:
951 				delay = filedelay;
952 			}
953 			vn_syncer_add_to_worklist(vp, delay);
954 		}
955 	} else {
956 		/*
957 		 * Move to the clean list, remove the vnode from the worklist
958 		 * if no dirty blocks remain.
959 		 */
960 		if (bp->b_flags & B_VNDIRTY) {
961 			buf_rb_tree_RB_REMOVE(&vp->v_rbdirty_tree, bp);
962 			bp->b_flags &= ~B_VNDIRTY;
963 		}
964 		if ((bp->b_flags & B_VNCLEAN) == 0) {
965 			if (buf_rb_tree_RB_INSERT(&vp->v_rbclean_tree, bp)) {
966 				panic("reassignbuf: dup lblk vp %p bp %p",
967 				      vp, bp);
968 			}
969 			bp->b_flags |= B_VNCLEAN;
970 		}
971 		if ((vp->v_flag & VONWORKLST) &&
972 		    RB_EMPTY(&vp->v_rbdirty_tree)) {
973 			vp->v_flag &= ~VONWORKLST;
974 			LIST_REMOVE(vp, v_synclist);
975 		}
976 	}
977 	crit_exit();
978 }
979 
980 /*
981  * Create a vnode for a block device.
982  * Used for mounting the root file system.
983  */
984 int
985 bdevvp(cdev_t dev, struct vnode **vpp)
986 {
987 	struct vnode *vp;
988 	struct vnode *nvp;
989 	int error;
990 
991 	if (dev == NULL) {
992 		*vpp = NULLVP;
993 		return (ENXIO);
994 	}
995 	error = getspecialvnode(VT_NON, NULL, &spec_vnode_vops_p, &nvp, 0, 0);
996 	if (error) {
997 		*vpp = NULLVP;
998 		return (error);
999 	}
1000 	vp = nvp;
1001 	vp->v_type = VCHR;
1002 	vp->v_umajor = dev->si_umajor;
1003 	vp->v_uminor = dev->si_uminor;
1004 	vx_unlock(vp);
1005 	*vpp = vp;
1006 	return (0);
1007 }
1008 
1009 int
1010 v_associate_rdev(struct vnode *vp, cdev_t dev)
1011 {
1012 	lwkt_tokref ilock;
1013 
1014 	if (dev == NULL)
1015 		return(ENXIO);
1016 	if (dev_is_good(dev) == 0)
1017 		return(ENXIO);
1018 	KKASSERT(vp->v_rdev == NULL);
1019 	if (dev_ref_debug)
1020 		kprintf("Z1");
1021 	vp->v_rdev = reference_dev(dev);
1022 	lwkt_gettoken(&ilock, &spechash_token);
1023 	SLIST_INSERT_HEAD(&dev->si_hlist, vp, v_cdevnext);
1024 	lwkt_reltoken(&ilock);
1025 	return(0);
1026 }
1027 
1028 void
1029 v_release_rdev(struct vnode *vp)
1030 {
1031 	lwkt_tokref ilock;
1032 	cdev_t dev;
1033 
1034 	if ((dev = vp->v_rdev) != NULL) {
1035 		lwkt_gettoken(&ilock, &spechash_token);
1036 		SLIST_REMOVE(&dev->si_hlist, vp, vnode, v_cdevnext);
1037 		vp->v_rdev = NULL;
1038 		release_dev(dev);
1039 		lwkt_reltoken(&ilock);
1040 	}
1041 }
1042 
1043 /*
1044  * Add a vnode to the alias list hung off the cdev_t.  We only associate
1045  * the device number with the vnode.  The actual device is not associated
1046  * until the vnode is opened (usually in spec_open()), and will be
1047  * disassociated on last close.
1048  */
1049 void
1050 addaliasu(struct vnode *nvp, int x, int y)
1051 {
1052 	if (nvp->v_type != VBLK && nvp->v_type != VCHR)
1053 		panic("addaliasu on non-special vnode");
1054 	nvp->v_umajor = x;
1055 	nvp->v_uminor = y;
1056 }
1057 
1058 /*
1059  * Disassociate a vnode from its underlying filesystem.
1060  *
1061  * The vnode must be VX locked and referenced.  In all normal situations
1062  * there are no active references.  If vclean_vxlocked() is called while
1063  * there are active references, the vnode is being ripped out and we have
1064  * to call VOP_CLOSE() as appropriate before we can reclaim it.
1065  */
1066 void
1067 vclean_vxlocked(struct vnode *vp, int flags)
1068 {
1069 	int active;
1070 	int n;
1071 	vm_object_t object;
1072 
1073 	/*
1074 	 * If the vnode has already been reclaimed we have nothing to do.
1075 	 */
1076 	if (vp->v_flag & VRECLAIMED)
1077 		return;
1078 	vp->v_flag |= VRECLAIMED;
1079 
1080 	/*
1081 	 * Scrap the vfs cache
1082 	 */
1083 	while (cache_inval_vp(vp, 0) != 0) {
1084 		kprintf("Warning: vnode %p clean/cache_resolution race detected\n", vp);
1085 		tsleep(vp, 0, "vclninv", 2);
1086 	}
1087 
1088 	/*
1089 	 * Check to see if the vnode is in use. If so we have to reference it
1090 	 * before we clean it out so that its count cannot fall to zero and
1091 	 * generate a race against ourselves to recycle it.
1092 	 */
1093 	active = sysref_isactive(&vp->v_sysref);
1094 
1095 	/*
1096 	 * Clean out any buffers associated with the vnode and destroy its
1097 	 * object, if it has one.
1098 	 */
1099 	vinvalbuf(vp, V_SAVE, 0, 0);
1100 
1101 	/*
1102 	 * If purging an active vnode (typically during a forced unmount
1103 	 * or reboot), it must be closed and deactivated before being
1104 	 * reclaimed.  This isn't really all that safe, but what can
1105 	 * we do? XXX.
1106 	 *
1107 	 * Note that neither of these routines unlocks the vnode.
1108 	 */
1109 	if (active && (flags & DOCLOSE)) {
1110 		while ((n = vp->v_opencount) != 0) {
1111 			if (vp->v_writecount)
1112 				VOP_CLOSE(vp, FWRITE|FNONBLOCK);
1113 			else
1114 				VOP_CLOSE(vp, FNONBLOCK);
1115 			if (vp->v_opencount == n) {
1116 				kprintf("Warning: unable to force-close"
1117 				       " vnode %p\n", vp);
1118 				break;
1119 			}
1120 		}
1121 	}
1122 
1123 	/*
1124 	 * If the vnode has not been deactivated, deactivated it.  Deactivation
1125 	 * can create new buffers and VM pages so we have to call vinvalbuf()
1126 	 * again to make sure they all get flushed.
1127 	 *
1128 	 * This can occur if a file with a link count of 0 needs to be
1129 	 * truncated.
1130 	 */
1131 	if ((vp->v_flag & VINACTIVE) == 0) {
1132 		vp->v_flag |= VINACTIVE;
1133 		VOP_INACTIVE(vp);
1134 		vinvalbuf(vp, V_SAVE, 0, 0);
1135 	}
1136 
1137 	/*
1138 	 * If the vnode has an object, destroy it.
1139 	 */
1140 	if ((object = vp->v_object) != NULL) {
1141 		if (object->ref_count == 0) {
1142 			if ((object->flags & OBJ_DEAD) == 0)
1143 				vm_object_terminate(object);
1144 		} else {
1145 			vm_pager_deallocate(object);
1146 		}
1147 		vp->v_flag &= ~VOBJBUF;
1148 	}
1149 	KKASSERT((vp->v_flag & VOBJBUF) == 0);
1150 
1151 	/*
1152 	 * Reclaim the vnode.
1153 	 */
1154 	if (VOP_RECLAIM(vp))
1155 		panic("vclean: cannot reclaim");
1156 
1157 	/*
1158 	 * Done with purge, notify sleepers of the grim news.
1159 	 */
1160 	vp->v_ops = &dead_vnode_vops_p;
1161 	vn_pollgone(vp);
1162 	vp->v_tag = VT_NON;
1163 
1164 	/*
1165 	 * If we are destroying an active vnode, reactivate it now that
1166 	 * we have reassociated it with deadfs.  This prevents the system
1167 	 * from crashing on the vnode due to it being unexpectedly marked
1168 	 * as inactive or reclaimed.
1169 	 */
1170 	if (active && (flags & DOCLOSE)) {
1171 		vp->v_flag &= ~(VINACTIVE|VRECLAIMED);
1172 	}
1173 }
1174 
1175 /*
1176  * Eliminate all activity associated with the requested vnode
1177  * and with all vnodes aliased to the requested vnode.
1178  *
1179  * The vnode must be referenced and vx_lock()'d
1180  *
1181  * revoke { struct vnode *a_vp, int a_flags }
1182  */
1183 int
1184 vop_stdrevoke(struct vop_revoke_args *ap)
1185 {
1186 	struct vnode *vp, *vq;
1187 	lwkt_tokref ilock;
1188 	cdev_t dev;
1189 
1190 	KASSERT((ap->a_flags & REVOKEALL) != 0, ("vop_revoke"));
1191 
1192 	vp = ap->a_vp;
1193 
1194 	/*
1195 	 * If the vnode is already dead don't try to revoke it
1196 	 */
1197 	if (vp->v_flag & VRECLAIMED)
1198 		return (0);
1199 
1200 	/*
1201 	 * If the vnode has a device association, scrap all vnodes associated
1202 	 * with the device.  Don't let the device disappear on us while we
1203 	 * are scrapping the vnodes.
1204 	 *
1205 	 * The passed vp will probably show up in the list, do not VX lock
1206 	 * it twice!
1207 	 */
1208 	if (vp->v_type != VCHR)
1209 		return(0);
1210 	if ((dev = vp->v_rdev) == NULL) {
1211 		if ((dev = get_dev(vp->v_umajor, vp->v_uminor)) == NULL)
1212 			return(0);
1213 	}
1214 	reference_dev(dev);
1215 	lwkt_gettoken(&ilock, &spechash_token);
1216 	while ((vq = SLIST_FIRST(&dev->si_hlist)) != NULL) {
1217 		if (vp != vq)
1218 			vx_get(vq);
1219 		if (vq == SLIST_FIRST(&dev->si_hlist))
1220 			vgone_vxlocked(vq);
1221 		if (vp != vq)
1222 			vx_put(vq);
1223 	}
1224 	lwkt_reltoken(&ilock);
1225 	release_dev(dev);
1226 	return (0);
1227 }
1228 
1229 /*
1230  * This is called when the object underlying a vnode is being destroyed,
1231  * such as in a remove().  Try to recycle the vnode immediately if the
1232  * only active reference is our reference.
1233  *
1234  * Directory vnodes in the namecache with children cannot be immediately
1235  * recycled because numerous VOP_N*() ops require them to be stable.
1236  */
1237 int
1238 vrecycle(struct vnode *vp)
1239 {
1240 	if (vp->v_sysref.refcnt <= 1) {
1241 		if (cache_inval_vp_nonblock(vp))
1242 			return(0);
1243 		vgone_vxlocked(vp);
1244 		return (1);
1245 	}
1246 	return (0);
1247 }
1248 
1249 /*
1250  * Eliminate all activity associated with a vnode in preparation for reuse.
1251  *
1252  * The vnode must be VX locked and refd and will remain VX locked and refd
1253  * on return.  This routine may be called with the vnode in any state, as
1254  * long as it is VX locked.  The vnode will be cleaned out and marked
1255  * VRECLAIMED but will not actually be reused until all existing refs and
1256  * holds go away.
1257  *
1258  * NOTE: This routine may be called on a vnode which has not yet been
1259  * already been deactivated (VOP_INACTIVE), or on a vnode which has
1260  * already been reclaimed.
1261  *
1262  * This routine is not responsible for placing us back on the freelist.
1263  * Instead, it happens automatically when the caller releases the VX lock
1264  * (assuming there aren't any other references).
1265  */
1266 
1267 void
1268 vgone_vxlocked(struct vnode *vp)
1269 {
1270 	/*
1271 	 * assert that the VX lock is held.  This is an absolute requirement
1272 	 * now for vgone_vxlocked() to be called.
1273 	 */
1274 	KKASSERT(vp->v_lock.lk_exclusivecount == 1);
1275 
1276 	/*
1277 	 * Clean out the filesystem specific data and set the VRECLAIMED
1278 	 * bit.  Also deactivate the vnode if necessary.
1279 	 */
1280 	vclean_vxlocked(vp, DOCLOSE);
1281 
1282 	/*
1283 	 * Delete from old mount point vnode list, if on one.
1284 	 */
1285 	if (vp->v_mount != NULL)
1286 		insmntque(vp, NULL);
1287 
1288 	/*
1289 	 * If special device, remove it from special device alias list
1290 	 * if it is on one.  This should normally only occur if a vnode is
1291 	 * being revoked as the device should otherwise have been released
1292 	 * naturally.
1293 	 */
1294 	if ((vp->v_type == VBLK || vp->v_type == VCHR) && vp->v_rdev != NULL) {
1295 		v_release_rdev(vp);
1296 	}
1297 
1298 	/*
1299 	 * Set us to VBAD
1300 	 */
1301 	vp->v_type = VBAD;
1302 }
1303 
1304 /*
1305  * Lookup a vnode by device number.
1306  */
1307 int
1308 vfinddev(cdev_t dev, enum vtype type, struct vnode **vpp)
1309 {
1310 	lwkt_tokref ilock;
1311 	struct vnode *vp;
1312 
1313 	lwkt_gettoken(&ilock, &spechash_token);
1314 	SLIST_FOREACH(vp, &dev->si_hlist, v_cdevnext) {
1315 		if (type == vp->v_type) {
1316 			*vpp = vp;
1317 			lwkt_reltoken(&ilock);
1318 			return (1);
1319 		}
1320 	}
1321 	lwkt_reltoken(&ilock);
1322 	return (0);
1323 }
1324 
1325 /*
1326  * Calculate the total number of references to a special device.  This
1327  * routine may only be called for VBLK and VCHR vnodes since v_rdev is
1328  * an overloaded field.  Since udev2dev can now return NULL, we have
1329  * to check for a NULL v_rdev.
1330  */
1331 int
1332 count_dev(cdev_t dev)
1333 {
1334 	lwkt_tokref ilock;
1335 	struct vnode *vp;
1336 	int count = 0;
1337 
1338 	if (SLIST_FIRST(&dev->si_hlist)) {
1339 		lwkt_gettoken(&ilock, &spechash_token);
1340 		SLIST_FOREACH(vp, &dev->si_hlist, v_cdevnext) {
1341 			if (vp->v_sysref.refcnt > 0)
1342 				count += vp->v_sysref.refcnt;
1343 		}
1344 		lwkt_reltoken(&ilock);
1345 	}
1346 	return(count);
1347 }
1348 
1349 int
1350 count_udev(int x, int y)
1351 {
1352 	cdev_t dev;
1353 
1354 	if ((dev = get_dev(x, y)) == NULL)
1355 		return(0);
1356 	return(count_dev(dev));
1357 }
1358 
1359 int
1360 vcount(struct vnode *vp)
1361 {
1362 	if (vp->v_rdev == NULL)
1363 		return(0);
1364 	return(count_dev(vp->v_rdev));
1365 }
1366 
1367 /*
1368  * Initialize VMIO for a vnode.  This routine MUST be called before a
1369  * VFS can issue buffer cache ops on a vnode.  It is typically called
1370  * when a vnode is initialized from its inode.
1371  */
1372 int
1373 vinitvmio(struct vnode *vp, off_t filesize)
1374 {
1375 	vm_object_t object;
1376 	int error = 0;
1377 
1378 retry:
1379 	if ((object = vp->v_object) == NULL) {
1380 		object = vnode_pager_alloc(vp, filesize, 0, 0);
1381 		/*
1382 		 * Dereference the reference we just created.  This assumes
1383 		 * that the object is associated with the vp.
1384 		 */
1385 		object->ref_count--;
1386 		vrele(vp);
1387 	} else {
1388 		if (object->flags & OBJ_DEAD) {
1389 			vn_unlock(vp);
1390 			vm_object_dead_sleep(object, "vodead");
1391 			vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1392 			goto retry;
1393 		}
1394 	}
1395 	KASSERT(vp->v_object != NULL, ("vinitvmio: NULL object"));
1396 	vp->v_flag |= VOBJBUF;
1397 	return (error);
1398 }
1399 
1400 
1401 /*
1402  * Print out a description of a vnode.
1403  */
1404 static char *typename[] =
1405 {"VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD"};
1406 
1407 void
1408 vprint(char *label, struct vnode *vp)
1409 {
1410 	char buf[96];
1411 
1412 	if (label != NULL)
1413 		kprintf("%s: %p: ", label, (void *)vp);
1414 	else
1415 		kprintf("%p: ", (void *)vp);
1416 	kprintf("type %s, sysrefs %d, writecount %d, holdcnt %d,",
1417 		typename[vp->v_type],
1418 		vp->v_sysref.refcnt, vp->v_writecount, vp->v_auxrefs);
1419 	buf[0] = '\0';
1420 	if (vp->v_flag & VROOT)
1421 		strcat(buf, "|VROOT");
1422 	if (vp->v_flag & VTEXT)
1423 		strcat(buf, "|VTEXT");
1424 	if (vp->v_flag & VSYSTEM)
1425 		strcat(buf, "|VSYSTEM");
1426 	if (vp->v_flag & VFREE)
1427 		strcat(buf, "|VFREE");
1428 	if (vp->v_flag & VOBJBUF)
1429 		strcat(buf, "|VOBJBUF");
1430 	if (buf[0] != '\0')
1431 		kprintf(" flags (%s)", &buf[1]);
1432 	if (vp->v_data == NULL) {
1433 		kprintf("\n");
1434 	} else {
1435 		kprintf("\n\t");
1436 		VOP_PRINT(vp);
1437 	}
1438 }
1439 
1440 #ifdef DDB
1441 #include <ddb/ddb.h>
1442 
1443 static int db_show_locked_vnodes(struct mount *mp, void *data);
1444 
1445 /*
1446  * List all of the locked vnodes in the system.
1447  * Called when debugging the kernel.
1448  */
1449 DB_SHOW_COMMAND(lockedvnodes, lockedvnodes)
1450 {
1451 	kprintf("Locked vnodes\n");
1452 	mountlist_scan(db_show_locked_vnodes, NULL,
1453 			MNTSCAN_FORWARD|MNTSCAN_NOBUSY);
1454 }
1455 
1456 static int
1457 db_show_locked_vnodes(struct mount *mp, void *data __unused)
1458 {
1459 	struct vnode *vp;
1460 
1461 	TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
1462 		if (vn_islocked(vp))
1463 			vprint((char *)0, vp);
1464 	}
1465 	return(0);
1466 }
1467 #endif
1468 
1469 /*
1470  * Top level filesystem related information gathering.
1471  */
1472 static int	sysctl_ovfs_conf (SYSCTL_HANDLER_ARGS);
1473 
1474 static int
1475 vfs_sysctl(SYSCTL_HANDLER_ARGS)
1476 {
1477 	int *name = (int *)arg1 - 1;	/* XXX */
1478 	u_int namelen = arg2 + 1;	/* XXX */
1479 	struct vfsconf *vfsp;
1480 
1481 #if 1 || defined(COMPAT_PRELITE2)
1482 	/* Resolve ambiguity between VFS_VFSCONF and VFS_GENERIC. */
1483 	if (namelen == 1)
1484 		return (sysctl_ovfs_conf(oidp, arg1, arg2, req));
1485 #endif
1486 
1487 #ifdef notyet
1488 	/* all sysctl names at this level are at least name and field */
1489 	if (namelen < 2)
1490 		return (ENOTDIR);		/* overloaded */
1491 	if (name[0] != VFS_GENERIC) {
1492 		for (vfsp = vfsconf; vfsp; vfsp = vfsp->vfc_next)
1493 			if (vfsp->vfc_typenum == name[0])
1494 				break;
1495 		if (vfsp == NULL)
1496 			return (EOPNOTSUPP);
1497 		return ((*vfsp->vfc_vfsops->vfs_sysctl)(&name[1], namelen - 1,
1498 		    oldp, oldlenp, newp, newlen, p));
1499 	}
1500 #endif
1501 	switch (name[1]) {
1502 	case VFS_MAXTYPENUM:
1503 		if (namelen != 2)
1504 			return (ENOTDIR);
1505 		return (SYSCTL_OUT(req, &maxvfsconf, sizeof(int)));
1506 	case VFS_CONF:
1507 		if (namelen != 3)
1508 			return (ENOTDIR);	/* overloaded */
1509 		for (vfsp = vfsconf; vfsp; vfsp = vfsp->vfc_next)
1510 			if (vfsp->vfc_typenum == name[2])
1511 				break;
1512 		if (vfsp == NULL)
1513 			return (EOPNOTSUPP);
1514 		return (SYSCTL_OUT(req, vfsp, sizeof *vfsp));
1515 	}
1516 	return (EOPNOTSUPP);
1517 }
1518 
1519 SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RD, vfs_sysctl,
1520 	"Generic filesystem");
1521 
1522 #if 1 || defined(COMPAT_PRELITE2)
1523 
1524 static int
1525 sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS)
1526 {
1527 	int error;
1528 	struct vfsconf *vfsp;
1529 	struct ovfsconf ovfs;
1530 
1531 	for (vfsp = vfsconf; vfsp; vfsp = vfsp->vfc_next) {
1532 		bzero(&ovfs, sizeof(ovfs));
1533 		ovfs.vfc_vfsops = vfsp->vfc_vfsops;	/* XXX used as flag */
1534 		strcpy(ovfs.vfc_name, vfsp->vfc_name);
1535 		ovfs.vfc_index = vfsp->vfc_typenum;
1536 		ovfs.vfc_refcount = vfsp->vfc_refcount;
1537 		ovfs.vfc_flags = vfsp->vfc_flags;
1538 		error = SYSCTL_OUT(req, &ovfs, sizeof ovfs);
1539 		if (error)
1540 			return error;
1541 	}
1542 	return 0;
1543 }
1544 
1545 #endif /* 1 || COMPAT_PRELITE2 */
1546 
1547 /*
1548  * Check to see if a filesystem is mounted on a block device.
1549  */
1550 int
1551 vfs_mountedon(struct vnode *vp)
1552 {
1553 	cdev_t dev;
1554 
1555 	if ((dev = vp->v_rdev) == NULL) {
1556 		if (vp->v_type != VBLK)
1557 			dev = get_dev(vp->v_uminor, vp->v_umajor);
1558 	}
1559 	if (dev != NULL && dev->si_mountpoint)
1560 		return (EBUSY);
1561 	return (0);
1562 }
1563 
1564 /*
1565  * Unmount all filesystems. The list is traversed in reverse order
1566  * of mounting to avoid dependencies.
1567  */
1568 
1569 static int vfs_umountall_callback(struct mount *mp, void *data);
1570 
1571 void
1572 vfs_unmountall(void)
1573 {
1574 	int count;
1575 
1576 	do {
1577 		count = mountlist_scan(vfs_umountall_callback,
1578 					NULL, MNTSCAN_REVERSE|MNTSCAN_NOBUSY);
1579 	} while (count);
1580 }
1581 
1582 static
1583 int
1584 vfs_umountall_callback(struct mount *mp, void *data)
1585 {
1586 	int error;
1587 
1588 	error = dounmount(mp, MNT_FORCE);
1589 	if (error) {
1590 		mountlist_remove(mp);
1591 		kprintf("unmount of filesystem mounted from %s failed (",
1592 			mp->mnt_stat.f_mntfromname);
1593 		if (error == EBUSY)
1594 			kprintf("BUSY)\n");
1595 		else
1596 			kprintf("%d)\n", error);
1597 	}
1598 	return(1);
1599 }
1600 
1601 /*
1602  * Build hash lists of net addresses and hang them off the mount point.
1603  * Called by ufs_mount() to set up the lists of export addresses.
1604  */
1605 static int
1606 vfs_hang_addrlist(struct mount *mp, struct netexport *nep,
1607 		const struct export_args *argp)
1608 {
1609 	struct netcred *np;
1610 	struct radix_node_head *rnh;
1611 	int i;
1612 	struct radix_node *rn;
1613 	struct sockaddr *saddr, *smask = 0;
1614 	struct domain *dom;
1615 	int error;
1616 
1617 	if (argp->ex_addrlen == 0) {
1618 		if (mp->mnt_flag & MNT_DEFEXPORTED)
1619 			return (EPERM);
1620 		np = &nep->ne_defexported;
1621 		np->netc_exflags = argp->ex_flags;
1622 		np->netc_anon = argp->ex_anon;
1623 		np->netc_anon.cr_ref = 1;
1624 		mp->mnt_flag |= MNT_DEFEXPORTED;
1625 		return (0);
1626 	}
1627 
1628 	if (argp->ex_addrlen < 0 || argp->ex_addrlen > MLEN)
1629 		return (EINVAL);
1630 	if (argp->ex_masklen < 0 || argp->ex_masklen > MLEN)
1631 		return (EINVAL);
1632 
1633 	i = sizeof(struct netcred) + argp->ex_addrlen + argp->ex_masklen;
1634 	np = (struct netcred *) kmalloc(i, M_NETADDR, M_WAITOK | M_ZERO);
1635 	saddr = (struct sockaddr *) (np + 1);
1636 	if ((error = copyin(argp->ex_addr, (caddr_t) saddr, argp->ex_addrlen)))
1637 		goto out;
1638 	if (saddr->sa_len > argp->ex_addrlen)
1639 		saddr->sa_len = argp->ex_addrlen;
1640 	if (argp->ex_masklen) {
1641 		smask = (struct sockaddr *)((caddr_t)saddr + argp->ex_addrlen);
1642 		error = copyin(argp->ex_mask, (caddr_t)smask, argp->ex_masklen);
1643 		if (error)
1644 			goto out;
1645 		if (smask->sa_len > argp->ex_masklen)
1646 			smask->sa_len = argp->ex_masklen;
1647 	}
1648 	i = saddr->sa_family;
1649 	if ((rnh = nep->ne_rtable[i]) == 0) {
1650 		/*
1651 		 * Seems silly to initialize every AF when most are not used,
1652 		 * do so on demand here
1653 		 */
1654 		SLIST_FOREACH(dom, &domains, dom_next)
1655 			if (dom->dom_family == i && dom->dom_rtattach) {
1656 				dom->dom_rtattach((void **) &nep->ne_rtable[i],
1657 				    dom->dom_rtoffset);
1658 				break;
1659 			}
1660 		if ((rnh = nep->ne_rtable[i]) == 0) {
1661 			error = ENOBUFS;
1662 			goto out;
1663 		}
1664 	}
1665 	rn = (*rnh->rnh_addaddr) ((char *) saddr, (char *) smask, rnh,
1666 	    np->netc_rnodes);
1667 	if (rn == 0 || np != (struct netcred *) rn) {	/* already exists */
1668 		error = EPERM;
1669 		goto out;
1670 	}
1671 	np->netc_exflags = argp->ex_flags;
1672 	np->netc_anon = argp->ex_anon;
1673 	np->netc_anon.cr_ref = 1;
1674 	return (0);
1675 out:
1676 	kfree(np, M_NETADDR);
1677 	return (error);
1678 }
1679 
1680 /* ARGSUSED */
1681 static int
1682 vfs_free_netcred(struct radix_node *rn, void *w)
1683 {
1684 	struct radix_node_head *rnh = (struct radix_node_head *) w;
1685 
1686 	(*rnh->rnh_deladdr) (rn->rn_key, rn->rn_mask, rnh);
1687 	kfree((caddr_t) rn, M_NETADDR);
1688 	return (0);
1689 }
1690 
1691 /*
1692  * Free the net address hash lists that are hanging off the mount points.
1693  */
1694 static void
1695 vfs_free_addrlist(struct netexport *nep)
1696 {
1697 	int i;
1698 	struct radix_node_head *rnh;
1699 
1700 	for (i = 0; i <= AF_MAX; i++)
1701 		if ((rnh = nep->ne_rtable[i])) {
1702 			(*rnh->rnh_walktree) (rnh, vfs_free_netcred,
1703 			    (caddr_t) rnh);
1704 			kfree((caddr_t) rnh, M_RTABLE);
1705 			nep->ne_rtable[i] = 0;
1706 		}
1707 }
1708 
1709 int
1710 vfs_export(struct mount *mp, struct netexport *nep,
1711 	   const struct export_args *argp)
1712 {
1713 	int error;
1714 
1715 	if (argp->ex_flags & MNT_DELEXPORT) {
1716 		if (mp->mnt_flag & MNT_EXPUBLIC) {
1717 			vfs_setpublicfs(NULL, NULL, NULL);
1718 			mp->mnt_flag &= ~MNT_EXPUBLIC;
1719 		}
1720 		vfs_free_addrlist(nep);
1721 		mp->mnt_flag &= ~(MNT_EXPORTED | MNT_DEFEXPORTED);
1722 	}
1723 	if (argp->ex_flags & MNT_EXPORTED) {
1724 		if (argp->ex_flags & MNT_EXPUBLIC) {
1725 			if ((error = vfs_setpublicfs(mp, nep, argp)) != 0)
1726 				return (error);
1727 			mp->mnt_flag |= MNT_EXPUBLIC;
1728 		}
1729 		if ((error = vfs_hang_addrlist(mp, nep, argp)))
1730 			return (error);
1731 		mp->mnt_flag |= MNT_EXPORTED;
1732 	}
1733 	return (0);
1734 }
1735 
1736 
1737 /*
1738  * Set the publicly exported filesystem (WebNFS). Currently, only
1739  * one public filesystem is possible in the spec (RFC 2054 and 2055)
1740  */
1741 int
1742 vfs_setpublicfs(struct mount *mp, struct netexport *nep,
1743 		const struct export_args *argp)
1744 {
1745 	int error;
1746 	struct vnode *rvp;
1747 	char *cp;
1748 
1749 	/*
1750 	 * mp == NULL -> invalidate the current info, the FS is
1751 	 * no longer exported. May be called from either vfs_export
1752 	 * or unmount, so check if it hasn't already been done.
1753 	 */
1754 	if (mp == NULL) {
1755 		if (nfs_pub.np_valid) {
1756 			nfs_pub.np_valid = 0;
1757 			if (nfs_pub.np_index != NULL) {
1758 				FREE(nfs_pub.np_index, M_TEMP);
1759 				nfs_pub.np_index = NULL;
1760 			}
1761 		}
1762 		return (0);
1763 	}
1764 
1765 	/*
1766 	 * Only one allowed at a time.
1767 	 */
1768 	if (nfs_pub.np_valid != 0 && mp != nfs_pub.np_mount)
1769 		return (EBUSY);
1770 
1771 	/*
1772 	 * Get real filehandle for root of exported FS.
1773 	 */
1774 	bzero((caddr_t)&nfs_pub.np_handle, sizeof(nfs_pub.np_handle));
1775 	nfs_pub.np_handle.fh_fsid = mp->mnt_stat.f_fsid;
1776 
1777 	if ((error = VFS_ROOT(mp, &rvp)))
1778 		return (error);
1779 
1780 	if ((error = VFS_VPTOFH(rvp, &nfs_pub.np_handle.fh_fid)))
1781 		return (error);
1782 
1783 	vput(rvp);
1784 
1785 	/*
1786 	 * If an indexfile was specified, pull it in.
1787 	 */
1788 	if (argp->ex_indexfile != NULL) {
1789 		int namelen;
1790 
1791 		error = vn_get_namelen(rvp, &namelen);
1792 		if (error)
1793 			return (error);
1794 		MALLOC(nfs_pub.np_index, char *, namelen, M_TEMP,
1795 		    M_WAITOK);
1796 		error = copyinstr(argp->ex_indexfile, nfs_pub.np_index,
1797 		    namelen, (size_t *)0);
1798 		if (!error) {
1799 			/*
1800 			 * Check for illegal filenames.
1801 			 */
1802 			for (cp = nfs_pub.np_index; *cp; cp++) {
1803 				if (*cp == '/') {
1804 					error = EINVAL;
1805 					break;
1806 				}
1807 			}
1808 		}
1809 		if (error) {
1810 			FREE(nfs_pub.np_index, M_TEMP);
1811 			return (error);
1812 		}
1813 	}
1814 
1815 	nfs_pub.np_mount = mp;
1816 	nfs_pub.np_valid = 1;
1817 	return (0);
1818 }
1819 
1820 struct netcred *
1821 vfs_export_lookup(struct mount *mp, struct netexport *nep,
1822 		struct sockaddr *nam)
1823 {
1824 	struct netcred *np;
1825 	struct radix_node_head *rnh;
1826 	struct sockaddr *saddr;
1827 
1828 	np = NULL;
1829 	if (mp->mnt_flag & MNT_EXPORTED) {
1830 		/*
1831 		 * Lookup in the export list first.
1832 		 */
1833 		if (nam != NULL) {
1834 			saddr = nam;
1835 			rnh = nep->ne_rtable[saddr->sa_family];
1836 			if (rnh != NULL) {
1837 				np = (struct netcred *)
1838 					(*rnh->rnh_matchaddr)((char *)saddr,
1839 							      rnh);
1840 				if (np && np->netc_rnodes->rn_flags & RNF_ROOT)
1841 					np = NULL;
1842 			}
1843 		}
1844 		/*
1845 		 * If no address match, use the default if it exists.
1846 		 */
1847 		if (np == NULL && mp->mnt_flag & MNT_DEFEXPORTED)
1848 			np = &nep->ne_defexported;
1849 	}
1850 	return (np);
1851 }
1852 
1853 /*
1854  * perform msync on all vnodes under a mount point.  The mount point must
1855  * be locked.  This code is also responsible for lazy-freeing unreferenced
1856  * vnodes whos VM objects no longer contain pages.
1857  *
1858  * NOTE: MNT_WAIT still skips vnodes in the VXLOCK state.
1859  *
1860  * NOTE: XXX VOP_PUTPAGES and friends requires that the vnode be locked,
1861  * but vnode_pager_putpages() doesn't lock the vnode.  We have to do it
1862  * way up in this high level function.
1863  */
1864 static int vfs_msync_scan1(struct mount *mp, struct vnode *vp, void *data);
1865 static int vfs_msync_scan2(struct mount *mp, struct vnode *vp, void *data);
1866 
1867 void
1868 vfs_msync(struct mount *mp, int flags)
1869 {
1870 	int vmsc_flags;
1871 
1872 	vmsc_flags = VMSC_GETVP;
1873 	if (flags != MNT_WAIT)
1874 		vmsc_flags |= VMSC_NOWAIT;
1875 	vmntvnodescan(mp, vmsc_flags, vfs_msync_scan1, vfs_msync_scan2,
1876 			(void *)flags);
1877 }
1878 
1879 /*
1880  * scan1 is a fast pre-check.  There could be hundreds of thousands of
1881  * vnodes, we cannot afford to do anything heavy weight until we have a
1882  * fairly good indication that there is work to do.
1883  */
1884 static
1885 int
1886 vfs_msync_scan1(struct mount *mp, struct vnode *vp, void *data)
1887 {
1888 	int flags = (int)data;
1889 
1890 	if ((vp->v_flag & VRECLAIMED) == 0) {
1891 		if (vshouldmsync(vp))
1892 			return(0);	/* call scan2 */
1893 		if ((mp->mnt_flag & MNT_RDONLY) == 0 &&
1894 		    (vp->v_flag & VOBJDIRTY) &&
1895 		    (flags == MNT_WAIT || vn_islocked(vp) == 0)) {
1896 			return(0);	/* call scan2 */
1897 		}
1898 	}
1899 
1900 	/*
1901 	 * do not call scan2, continue the loop
1902 	 */
1903 	return(-1);
1904 }
1905 
1906 /*
1907  * This callback is handed a locked vnode.
1908  */
1909 static
1910 int
1911 vfs_msync_scan2(struct mount *mp, struct vnode *vp, void *data)
1912 {
1913 	vm_object_t obj;
1914 	int flags = (int)data;
1915 
1916 	if (vp->v_flag & VRECLAIMED)
1917 		return(0);
1918 
1919 	if ((mp->mnt_flag & MNT_RDONLY) == 0 && (vp->v_flag & VOBJDIRTY)) {
1920 		if ((obj = vp->v_object) != NULL) {
1921 			vm_object_page_clean(obj, 0, 0,
1922 			 flags == MNT_WAIT ? OBJPC_SYNC : OBJPC_NOSYNC);
1923 		}
1924 	}
1925 	return(0);
1926 }
1927 
1928 /*
1929  * Record a process's interest in events which might happen to
1930  * a vnode.  Because poll uses the historic select-style interface
1931  * internally, this routine serves as both the ``check for any
1932  * pending events'' and the ``record my interest in future events''
1933  * functions.  (These are done together, while the lock is held,
1934  * to avoid race conditions.)
1935  */
1936 int
1937 vn_pollrecord(struct vnode *vp, int events)
1938 {
1939 	lwkt_tokref ilock;
1940 
1941 	KKASSERT(curthread->td_proc != NULL);
1942 
1943 	lwkt_gettoken(&ilock, &vp->v_pollinfo.vpi_token);
1944 	if (vp->v_pollinfo.vpi_revents & events) {
1945 		/*
1946 		 * This leaves events we are not interested
1947 		 * in available for the other process which
1948 		 * which presumably had requested them
1949 		 * (otherwise they would never have been
1950 		 * recorded).
1951 		 */
1952 		events &= vp->v_pollinfo.vpi_revents;
1953 		vp->v_pollinfo.vpi_revents &= ~events;
1954 
1955 		lwkt_reltoken(&ilock);
1956 		return events;
1957 	}
1958 	vp->v_pollinfo.vpi_events |= events;
1959 	selrecord(curthread, &vp->v_pollinfo.vpi_selinfo);
1960 	lwkt_reltoken(&ilock);
1961 	return 0;
1962 }
1963 
1964 /*
1965  * Note the occurrence of an event.  If the VN_POLLEVENT macro is used,
1966  * it is possible for us to miss an event due to race conditions, but
1967  * that condition is expected to be rare, so for the moment it is the
1968  * preferred interface.
1969  */
1970 void
1971 vn_pollevent(struct vnode *vp, int events)
1972 {
1973 	lwkt_tokref ilock;
1974 
1975 	lwkt_gettoken(&ilock, &vp->v_pollinfo.vpi_token);
1976 	if (vp->v_pollinfo.vpi_events & events) {
1977 		/*
1978 		 * We clear vpi_events so that we don't
1979 		 * call selwakeup() twice if two events are
1980 		 * posted before the polling process(es) is
1981 		 * awakened.  This also ensures that we take at
1982 		 * most one selwakeup() if the polling process
1983 		 * is no longer interested.  However, it does
1984 		 * mean that only one event can be noticed at
1985 		 * a time.  (Perhaps we should only clear those
1986 		 * event bits which we note?) XXX
1987 		 */
1988 		vp->v_pollinfo.vpi_events = 0;	/* &= ~events ??? */
1989 		vp->v_pollinfo.vpi_revents |= events;
1990 		selwakeup(&vp->v_pollinfo.vpi_selinfo);
1991 	}
1992 	lwkt_reltoken(&ilock);
1993 }
1994 
1995 /*
1996  * Wake up anyone polling on vp because it is being revoked.
1997  * This depends on dead_poll() returning POLLHUP for correct
1998  * behavior.
1999  */
2000 void
2001 vn_pollgone(struct vnode *vp)
2002 {
2003 	lwkt_tokref ilock;
2004 
2005 	lwkt_gettoken(&ilock, &vp->v_pollinfo.vpi_token);
2006 	if (vp->v_pollinfo.vpi_events) {
2007 		vp->v_pollinfo.vpi_events = 0;
2008 		selwakeup(&vp->v_pollinfo.vpi_selinfo);
2009 	}
2010 	lwkt_reltoken(&ilock);
2011 }
2012 
2013 /*
2014  * extract the cdev_t from a VBLK or VCHR.  The vnode must have been opened
2015  * (or v_rdev might be NULL).
2016  */
2017 cdev_t
2018 vn_todev(struct vnode *vp)
2019 {
2020 	if (vp->v_type != VBLK && vp->v_type != VCHR)
2021 		return (NULL);
2022 	KKASSERT(vp->v_rdev != NULL);
2023 	return (vp->v_rdev);
2024 }
2025 
2026 /*
2027  * Check if vnode represents a disk device.  The vnode does not need to be
2028  * opened.
2029  */
2030 int
2031 vn_isdisk(struct vnode *vp, int *errp)
2032 {
2033 	cdev_t dev;
2034 
2035 	if (vp->v_type != VCHR) {
2036 		if (errp != NULL)
2037 			*errp = ENOTBLK;
2038 		return (0);
2039 	}
2040 
2041 	if ((dev = vp->v_rdev) == NULL)
2042 		dev = get_dev(vp->v_umajor, vp->v_uminor);
2043 
2044 	if (dev == NULL) {
2045 		if (errp != NULL)
2046 			*errp = ENXIO;
2047 		return (0);
2048 	}
2049 	if (dev_is_good(dev) == 0) {
2050 		if (errp != NULL)
2051 			*errp = ENXIO;
2052 		return (0);
2053 	}
2054 	if ((dev_dflags(dev) & D_DISK) == 0) {
2055 		if (errp != NULL)
2056 			*errp = ENOTBLK;
2057 		return (0);
2058 	}
2059 	if (errp != NULL)
2060 		*errp = 0;
2061 	return (1);
2062 }
2063 
2064 int
2065 vn_get_namelen(struct vnode *vp, int *namelen)
2066 {
2067 	int error, retval[2];
2068 
2069 	error = VOP_PATHCONF(vp, _PC_NAME_MAX, retval);
2070 	if (error)
2071 		return (error);
2072 	*namelen = *retval;
2073 	return (0);
2074 }
2075 
2076 int
2077 vop_write_dirent(int *error, struct uio *uio, ino_t d_ino, uint8_t d_type,
2078 		uint16_t d_namlen, const char *d_name)
2079 {
2080 	struct dirent *dp;
2081 	size_t len;
2082 
2083 	len = _DIRENT_RECLEN(d_namlen);
2084 	if (len > uio->uio_resid)
2085 		return(1);
2086 
2087 	dp = kmalloc(len, M_TEMP, M_WAITOK | M_ZERO);
2088 
2089 	dp->d_ino = d_ino;
2090 	dp->d_namlen = d_namlen;
2091 	dp->d_type = d_type;
2092 	bcopy(d_name, dp->d_name, d_namlen);
2093 
2094 	*error = uiomove((caddr_t)dp, len, uio);
2095 
2096 	kfree(dp, M_TEMP);
2097 
2098 	return(0);
2099 }
2100 
2101