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