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