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