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