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