Merge branch 'devfs' of ssh://alexh@leaf.dragonflybsd.org/~/git/dragonfly
[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         vp->v_rdev = dev;
998         vp->v_umajor = dev->si_umajor;
999         vp->v_uminor = dev->si_uminor;
1000         vx_unlock(vp);
1001         *vpp = vp;
1002         return (0);
1003 }
1004
1005 int
1006 v_associate_rdev(struct vnode *vp, cdev_t dev)
1007 {
1008         lwkt_tokref ilock;
1009
1010         if (dev == NULL)
1011                 return(ENXIO);
1012         if (dev_is_good(dev) == 0)
1013                 return(ENXIO);
1014         KKASSERT(vp->v_rdev == NULL);
1015         vp->v_rdev = reference_dev(dev);
1016         lwkt_gettoken(&ilock, &spechash_token);
1017         SLIST_INSERT_HEAD(&dev->si_hlist, vp, v_cdevnext);
1018         lwkt_reltoken(&ilock);
1019         return(0);
1020 }
1021
1022 void
1023 v_release_rdev(struct vnode *vp)
1024 {
1025         lwkt_tokref ilock;
1026         cdev_t dev;
1027
1028         if ((dev = vp->v_rdev) != NULL) {
1029                 lwkt_gettoken(&ilock, &spechash_token);
1030                 SLIST_REMOVE(&dev->si_hlist, vp, vnode, v_cdevnext);
1031                 vp->v_rdev = NULL;
1032                 release_dev(dev);
1033                 lwkt_reltoken(&ilock);
1034         }
1035 }
1036
1037 /*
1038  * Add a vnode to the alias list hung off the cdev_t.  We only associate
1039  * the device number with the vnode.  The actual device is not associated
1040  * until the vnode is opened (usually in spec_open()), and will be 
1041  * disassociated on last close.
1042  */
1043 void
1044 addaliasu(struct vnode *nvp, int x, int y)
1045 {
1046         if (nvp->v_type != VBLK && nvp->v_type != VCHR)
1047                 panic("addaliasu on non-special vnode");
1048         nvp->v_umajor = x;
1049         nvp->v_uminor = y;
1050 }
1051
1052 /*
1053  * Simple call that a filesystem can make to try to get rid of a
1054  * vnode.  It will fail if anyone is referencing the vnode (including
1055  * the caller).
1056  *
1057  * The filesystem can check whether its in-memory inode structure still
1058  * references the vp on return.
1059  */
1060 void
1061 vclean_unlocked(struct vnode *vp)
1062 {
1063         vx_get(vp);
1064         if (sysref_isactive(&vp->v_sysref) == 0)
1065                 vgone_vxlocked(vp);
1066         vx_put(vp);
1067 }
1068
1069 /*
1070  * Disassociate a vnode from its underlying filesystem. 
1071  *
1072  * The vnode must be VX locked and referenced.  In all normal situations
1073  * there are no active references.  If vclean_vxlocked() is called while
1074  * there are active references, the vnode is being ripped out and we have
1075  * to call VOP_CLOSE() as appropriate before we can reclaim it.
1076  */
1077 void
1078 vclean_vxlocked(struct vnode *vp, int flags)
1079 {
1080         int active;
1081         int n;
1082         vm_object_t object;
1083
1084         /*
1085          * If the vnode has already been reclaimed we have nothing to do.
1086          */
1087         if (vp->v_flag & VRECLAIMED)
1088                 return;
1089         vp->v_flag |= VRECLAIMED;
1090
1091         /*
1092          * Scrap the vfs cache
1093          */
1094         while (cache_inval_vp(vp, 0) != 0) {
1095                 kprintf("Warning: vnode %p clean/cache_resolution race detected\n", vp);
1096                 tsleep(vp, 0, "vclninv", 2);
1097         }
1098
1099         /*
1100          * Check to see if the vnode is in use. If so we have to reference it
1101          * before we clean it out so that its count cannot fall to zero and
1102          * generate a race against ourselves to recycle it.
1103          */
1104         active = sysref_isactive(&vp->v_sysref);
1105
1106         /*
1107          * Clean out any buffers associated with the vnode and destroy its
1108          * object, if it has one. 
1109          */
1110         vinvalbuf(vp, V_SAVE, 0, 0);
1111
1112         /*
1113          * If purging an active vnode (typically during a forced unmount
1114          * or reboot), it must be closed and deactivated before being
1115          * reclaimed.  This isn't really all that safe, but what can
1116          * we do? XXX.
1117          *
1118          * Note that neither of these routines unlocks the vnode.
1119          */
1120         if (active && (flags & DOCLOSE)) {
1121                 while ((n = vp->v_opencount) != 0) {
1122                         if (vp->v_writecount)
1123                                 VOP_CLOSE(vp, FWRITE|FNONBLOCK);
1124                         else
1125                                 VOP_CLOSE(vp, FNONBLOCK);
1126                         if (vp->v_opencount == n) {
1127                                 kprintf("Warning: unable to force-close"
1128                                        " vnode %p\n", vp);
1129                                 break;
1130                         }
1131                 }
1132         }
1133
1134         /*
1135          * If the vnode has not been deactivated, deactivated it.  Deactivation
1136          * can create new buffers and VM pages so we have to call vinvalbuf()
1137          * again to make sure they all get flushed.
1138          *
1139          * This can occur if a file with a link count of 0 needs to be
1140          * truncated.
1141          */
1142         if ((vp->v_flag & VINACTIVE) == 0) {
1143                 vp->v_flag |= VINACTIVE;
1144                 VOP_INACTIVE(vp);
1145                 vinvalbuf(vp, V_SAVE, 0, 0);
1146         }
1147
1148         /*
1149          * If the vnode has an object, destroy it.
1150          */
1151         if ((object = vp->v_object) != NULL) {
1152                 if (object->ref_count == 0) {
1153                         if ((object->flags & OBJ_DEAD) == 0)
1154                                 vm_object_terminate(object);
1155                 } else {
1156                         vm_pager_deallocate(object);
1157                 }
1158                 vp->v_flag &= ~VOBJBUF;
1159         }
1160         KKASSERT((vp->v_flag & VOBJBUF) == 0);
1161
1162         /*
1163          * Reclaim the vnode.
1164          */
1165         if (VOP_RECLAIM(vp))
1166                 panic("vclean: cannot reclaim");
1167
1168         /*
1169          * Done with purge, notify sleepers of the grim news.
1170          */
1171         vp->v_ops = &dead_vnode_vops_p;
1172         vn_pollgone(vp);
1173         vp->v_tag = VT_NON;
1174
1175         /*
1176          * If we are destroying an active vnode, reactivate it now that
1177          * we have reassociated it with deadfs.  This prevents the system
1178          * from crashing on the vnode due to it being unexpectedly marked
1179          * as inactive or reclaimed.
1180          */
1181         if (active && (flags & DOCLOSE)) {
1182                 vp->v_flag &= ~(VINACTIVE|VRECLAIMED);
1183         }
1184 }
1185
1186 /*
1187  * Eliminate all activity associated with the requested vnode
1188  * and with all vnodes aliased to the requested vnode.
1189  *
1190  * The vnode must be referenced but should not be locked.
1191  */
1192 int
1193 vrevoke(struct vnode *vp, struct ucred *cred)
1194 {
1195         struct vnode *vq;
1196         struct vnode *vqn;
1197         lwkt_tokref ilock;
1198         cdev_t dev;
1199         int error;
1200
1201         /*
1202          * If the vnode has a device association, scrap all vnodes associated
1203          * with the device.  Don't let the device disappear on us while we
1204          * are scrapping the vnodes.
1205          *
1206          * The passed vp will probably show up in the list, do not VX lock
1207          * it twice!
1208          *
1209          * Releasing the vnode's rdev here can mess up specfs's call to
1210          * device close, so don't do it.  The vnode has been disassociated
1211          * and the device will be closed after the last ref on the related
1212          * fp goes away (if not still open by e.g. the kernel).
1213          */
1214         if (vp->v_type != VCHR) {
1215                 error = fdrevoke(vp, DTYPE_VNODE, cred);
1216                 return (error);
1217         }
1218         if ((dev = vp->v_rdev) == NULL) {
1219                 return(0);
1220         }
1221         reference_dev(dev);
1222         lwkt_gettoken(&ilock, &spechash_token);
1223
1224         vqn = SLIST_FIRST(&dev->si_hlist);
1225         if (vqn)
1226                 vref(vqn);
1227         while ((vq = vqn) != NULL) {
1228                 vqn = SLIST_NEXT(vqn, v_cdevnext);
1229                 if (vqn)
1230                         vref(vqn);
1231                 fdrevoke(vq, DTYPE_VNODE, cred);
1232                 /*v_release_rdev(vq);*/
1233                 vrele(vq);
1234         }
1235         lwkt_reltoken(&ilock);
1236         dev_drevoke(dev);
1237         //release_dev(dev);
1238         return (0);
1239 }
1240
1241 /*
1242  * This is called when the object underlying a vnode is being destroyed,
1243  * such as in a remove().  Try to recycle the vnode immediately if the
1244  * only active reference is our reference.
1245  *
1246  * Directory vnodes in the namecache with children cannot be immediately
1247  * recycled because numerous VOP_N*() ops require them to be stable.
1248  */
1249 int
1250 vrecycle(struct vnode *vp)
1251 {
1252         if (vp->v_sysref.refcnt <= 1) {
1253                 if (cache_inval_vp_nonblock(vp))
1254                         return(0);
1255                 vgone_vxlocked(vp);
1256                 return (1);
1257         }
1258         return (0);
1259 }
1260
1261 /*
1262  * Return the maximum I/O size allowed for strategy calls on VP.
1263  *
1264  * If vp is VCHR or VBLK we dive the device, otherwise we use
1265  * the vp's mount info.
1266  */
1267 int
1268 vmaxiosize(struct vnode *vp)
1269 {
1270         if (vp->v_type == VBLK || vp->v_type == VCHR) {
1271                 return(vp->v_rdev->si_iosize_max);
1272         } else {
1273                 return(vp->v_mount->mnt_iosize_max);
1274         }
1275 }
1276
1277 /*
1278  * Eliminate all activity associated with a vnode in preparation for reuse.
1279  *
1280  * The vnode must be VX locked and refd and will remain VX locked and refd
1281  * on return.  This routine may be called with the vnode in any state, as
1282  * long as it is VX locked.  The vnode will be cleaned out and marked
1283  * VRECLAIMED but will not actually be reused until all existing refs and
1284  * holds go away.
1285  *
1286  * NOTE: This routine may be called on a vnode which has not yet been
1287  * already been deactivated (VOP_INACTIVE), or on a vnode which has
1288  * already been reclaimed.
1289  *
1290  * This routine is not responsible for placing us back on the freelist. 
1291  * Instead, it happens automatically when the caller releases the VX lock
1292  * (assuming there aren't any other references).
1293  */
1294
1295 void
1296 vgone_vxlocked(struct vnode *vp)
1297 {
1298         /*
1299          * assert that the VX lock is held.  This is an absolute requirement
1300          * now for vgone_vxlocked() to be called.
1301          */
1302         KKASSERT(vp->v_lock.lk_exclusivecount == 1);
1303
1304         /*
1305          * Clean out the filesystem specific data and set the VRECLAIMED
1306          * bit.  Also deactivate the vnode if necessary. 
1307          */
1308         vclean_vxlocked(vp, DOCLOSE);
1309
1310         /*
1311          * Delete from old mount point vnode list, if on one.
1312          */
1313         if (vp->v_mount != NULL)
1314                 insmntque(vp, NULL);
1315
1316         /*
1317          * If special device, remove it from special device alias list
1318          * if it is on one.  This should normally only occur if a vnode is
1319          * being revoked as the device should otherwise have been released
1320          * naturally.
1321          */
1322         if ((vp->v_type == VBLK || vp->v_type == VCHR) && vp->v_rdev != NULL) {
1323                 v_release_rdev(vp);
1324         }
1325
1326         /*
1327          * Set us to VBAD
1328          */
1329         vp->v_type = VBAD;
1330 }
1331
1332 /*
1333  * Lookup a vnode by device number.
1334  *
1335  * Returns non-zero and *vpp set to a vref'd vnode on success.
1336  * Returns zero on failure.
1337  */
1338 int
1339 vfinddev(cdev_t dev, enum vtype type, struct vnode **vpp)
1340 {
1341         lwkt_tokref ilock;
1342         struct vnode *vp;
1343
1344         lwkt_gettoken(&ilock, &spechash_token);
1345         SLIST_FOREACH(vp, &dev->si_hlist, v_cdevnext) {
1346                 if (type == vp->v_type) {
1347                         *vpp = vp;
1348                         vref(vp);
1349                         lwkt_reltoken(&ilock);
1350                         return (1);
1351                 }
1352         }
1353         lwkt_reltoken(&ilock);
1354         return (0);
1355 }
1356
1357 /*
1358  * Calculate the total number of references to a special device.  This
1359  * routine may only be called for VBLK and VCHR vnodes since v_rdev is
1360  * an overloaded field.  Since udev2dev can now return NULL, we have
1361  * to check for a NULL v_rdev.
1362  */
1363 int
1364 count_dev(cdev_t dev)
1365 {
1366         lwkt_tokref ilock;
1367         struct vnode *vp;
1368         int count = 0;
1369
1370         if (SLIST_FIRST(&dev->si_hlist)) {
1371                 lwkt_gettoken(&ilock, &spechash_token);
1372                 SLIST_FOREACH(vp, &dev->si_hlist, v_cdevnext) {
1373                         if (vp->v_sysref.refcnt > 0)
1374                                 count += vp->v_sysref.refcnt;
1375                 }
1376                 lwkt_reltoken(&ilock);
1377         }
1378         return(count);
1379 }
1380
1381 int
1382 vcount(struct vnode *vp)
1383 {
1384         if (vp->v_rdev == NULL)
1385                 return(0);
1386         return(count_dev(vp->v_rdev));
1387 }
1388
1389 /*
1390  * Initialize VMIO for a vnode.  This routine MUST be called before a
1391  * VFS can issue buffer cache ops on a vnode.  It is typically called
1392  * when a vnode is initialized from its inode.
1393  */
1394 int
1395 vinitvmio(struct vnode *vp, off_t filesize)
1396 {
1397         vm_object_t object;
1398         int error = 0;
1399
1400 retry:
1401         if ((object = vp->v_object) == NULL) {
1402                 object = vnode_pager_alloc(vp, filesize, 0, 0);
1403                 /*
1404                  * Dereference the reference we just created.  This assumes
1405                  * that the object is associated with the vp.
1406                  */
1407                 object->ref_count--;
1408                 vrele(vp);
1409         } else {
1410                 if (object->flags & OBJ_DEAD) {
1411                         vn_unlock(vp);
1412                         vm_object_dead_sleep(object, "vodead");
1413                         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1414                         goto retry;
1415                 }
1416         }
1417         KASSERT(vp->v_object != NULL, ("vinitvmio: NULL object"));
1418         vp->v_flag |= VOBJBUF;
1419         return (error);
1420 }
1421
1422
1423 /*
1424  * Print out a description of a vnode.
1425  */
1426 static char *typename[] =
1427 {"VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD"};
1428
1429 void
1430 vprint(char *label, struct vnode *vp)
1431 {
1432         char buf[96];
1433
1434         if (label != NULL)
1435                 kprintf("%s: %p: ", label, (void *)vp);
1436         else
1437                 kprintf("%p: ", (void *)vp);
1438         kprintf("type %s, sysrefs %d, writecount %d, holdcnt %d,",
1439                 typename[vp->v_type],
1440                 vp->v_sysref.refcnt, vp->v_writecount, vp->v_auxrefs);
1441         buf[0] = '\0';
1442         if (vp->v_flag & VROOT)
1443                 strcat(buf, "|VROOT");
1444         if (vp->v_flag & VPFSROOT)
1445                 strcat(buf, "|VPFSROOT");
1446         if (vp->v_flag & VTEXT)
1447                 strcat(buf, "|VTEXT");
1448         if (vp->v_flag & VSYSTEM)
1449                 strcat(buf, "|VSYSTEM");
1450         if (vp->v_flag & VFREE)
1451                 strcat(buf, "|VFREE");
1452         if (vp->v_flag & VOBJBUF)
1453                 strcat(buf, "|VOBJBUF");
1454         if (buf[0] != '\0')
1455                 kprintf(" flags (%s)", &buf[1]);
1456         if (vp->v_data == NULL) {
1457                 kprintf("\n");
1458         } else {
1459                 kprintf("\n\t");
1460                 VOP_PRINT(vp);
1461         }
1462 }
1463
1464 #ifdef DDB
1465 #include <ddb/ddb.h>
1466
1467 static int db_show_locked_vnodes(struct mount *mp, void *data);
1468
1469 /*
1470  * List all of the locked vnodes in the system.
1471  * Called when debugging the kernel.
1472  */
1473 DB_SHOW_COMMAND(lockedvnodes, lockedvnodes)
1474 {
1475         kprintf("Locked vnodes\n");
1476         mountlist_scan(db_show_locked_vnodes, NULL, 
1477                         MNTSCAN_FORWARD|MNTSCAN_NOBUSY);
1478 }
1479
1480 static int
1481 db_show_locked_vnodes(struct mount *mp, void *data __unused)
1482 {
1483         struct vnode *vp;
1484
1485         TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
1486                 if (vn_islocked(vp))
1487                         vprint(NULL, vp);
1488         }
1489         return(0);
1490 }
1491 #endif
1492
1493 /*
1494  * Top level filesystem related information gathering.
1495  */
1496 static int      sysctl_ovfs_conf (SYSCTL_HANDLER_ARGS);
1497
1498 static int
1499 vfs_sysctl(SYSCTL_HANDLER_ARGS)
1500 {
1501         int *name = (int *)arg1 - 1;    /* XXX */
1502         u_int namelen = arg2 + 1;       /* XXX */
1503         struct vfsconf *vfsp;
1504         int maxtypenum;
1505
1506 #if 1 || defined(COMPAT_PRELITE2)
1507         /* Resolve ambiguity between VFS_VFSCONF and VFS_GENERIC. */
1508         if (namelen == 1)
1509                 return (sysctl_ovfs_conf(oidp, arg1, arg2, req));
1510 #endif
1511
1512 #ifdef notyet
1513         /* all sysctl names at this level are at least name and field */
1514         if (namelen < 2)
1515                 return (ENOTDIR);               /* overloaded */
1516         if (name[0] != VFS_GENERIC) {
1517                 vfsp = vfsconf_find_by_typenum(name[0]);
1518                 if (vfsp == NULL)
1519                         return (EOPNOTSUPP);
1520                 return ((*vfsp->vfc_vfsops->vfs_sysctl)(&name[1], namelen - 1,
1521                     oldp, oldlenp, newp, newlen, p));
1522         }
1523 #endif
1524         switch (name[1]) {
1525         case VFS_MAXTYPENUM:
1526                 if (namelen != 2)
1527                         return (ENOTDIR);
1528                 maxtypenum = vfsconf_get_maxtypenum();
1529                 return (SYSCTL_OUT(req, &maxtypenum, sizeof(maxtypenum)));
1530         case VFS_CONF:
1531                 if (namelen != 3)
1532                         return (ENOTDIR);       /* overloaded */
1533                 vfsp = vfsconf_find_by_typenum(name[2]);
1534                 if (vfsp == NULL)
1535                         return (EOPNOTSUPP);
1536                 return (SYSCTL_OUT(req, vfsp, sizeof *vfsp));
1537         }
1538         return (EOPNOTSUPP);
1539 }
1540
1541 SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RD, vfs_sysctl,
1542         "Generic filesystem");
1543
1544 #if 1 || defined(COMPAT_PRELITE2)
1545
1546 static int
1547 sysctl_ovfs_conf_iter(struct vfsconf *vfsp, void *data)
1548 {
1549         int error;
1550         struct ovfsconf ovfs;
1551         struct sysctl_req *req = (struct sysctl_req*) data;
1552
1553         bzero(&ovfs, sizeof(ovfs));
1554         ovfs.vfc_vfsops = vfsp->vfc_vfsops;     /* XXX used as flag */
1555         strcpy(ovfs.vfc_name, vfsp->vfc_name);
1556         ovfs.vfc_index = vfsp->vfc_typenum;
1557         ovfs.vfc_refcount = vfsp->vfc_refcount;
1558         ovfs.vfc_flags = vfsp->vfc_flags;
1559         error = SYSCTL_OUT(req, &ovfs, sizeof ovfs);
1560         if (error)
1561                 return error; /* abort iteration with error code */
1562         else
1563                 return 0; /* continue iterating with next element */
1564 }
1565
1566 static int
1567 sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS)
1568 {
1569         return vfsconf_each(sysctl_ovfs_conf_iter, (void*)req);
1570 }
1571
1572 #endif /* 1 || COMPAT_PRELITE2 */
1573
1574 /*
1575  * Check to see if a filesystem is mounted on a block device.
1576  */
1577 int
1578 vfs_mountedon(struct vnode *vp)
1579 {
1580         cdev_t dev;
1581
1582         if ((dev = vp->v_rdev) == NULL) {
1583 /*              if (vp->v_type != VBLK)
1584                         dev = get_dev(vp->v_uminor, vp->v_umajor); */
1585         }
1586         if (dev != NULL && dev->si_mountpoint)
1587                 return (EBUSY);
1588         return (0);
1589 }
1590
1591 /*
1592  * Unmount all filesystems. The list is traversed in reverse order
1593  * of mounting to avoid dependencies.
1594  */
1595
1596 static int vfs_umountall_callback(struct mount *mp, void *data);
1597
1598 void
1599 vfs_unmountall(void)
1600 {
1601         int count;
1602
1603         do {
1604                 count = mountlist_scan(vfs_umountall_callback, 
1605                                         NULL, MNTSCAN_REVERSE|MNTSCAN_NOBUSY);
1606         } while (count);
1607 }
1608
1609 static
1610 int
1611 vfs_umountall_callback(struct mount *mp, void *data)
1612 {
1613         int error;
1614
1615         error = dounmount(mp, MNT_FORCE);
1616         if (error) {
1617                 mountlist_remove(mp);
1618                 kprintf("unmount of filesystem mounted from %s failed (", 
1619                         mp->mnt_stat.f_mntfromname);
1620                 if (error == EBUSY)
1621                         kprintf("BUSY)\n");
1622                 else
1623                         kprintf("%d)\n", error);
1624         }
1625         return(1);
1626 }
1627
1628 /*
1629  * Checks the mount flags for parameter mp and put the names comma-separated
1630  * into a string buffer buf with a size limit specified by len.
1631  *
1632  * It returns the number of bytes written into buf, and (*errorp) will be
1633  * set to 0, EINVAL (if passed length is 0), or ENOSPC (supplied buffer was
1634  * not large enough).  The buffer will be 0-terminated if len was not 0.
1635  */
1636 #define OPTARYSIZE      (sizeof(optnames) / sizeof(optnames[0]))
1637
1638 size_t
1639 vfs_flagstostr(struct mount *mp, char *buf, size_t len, int *errorp)
1640 {
1641         static const struct mountctl_opt optnames[] = {
1642                 { MNT_ASYNC,            "asynchronous" },
1643                 { MNT_EXPORTED,         "NFS exported" },
1644                 { MNT_LOCAL,            "local" },
1645                 { MNT_NOATIME,          "noatime" },
1646                 { MNT_NODEV,            "nodev" },
1647                 { MNT_NOEXEC,           "noexec" },
1648                 { MNT_NOSUID,           "nosuid" },
1649                 { MNT_NOSYMFOLLOW,      "nosymfollow" },
1650                 { MNT_QUOTA,            "with-quotas" },
1651                 { MNT_RDONLY,           "read-only" },
1652                 { MNT_SYNCHRONOUS,      "synchronous" },
1653                 { MNT_UNION,            "union" },
1654                 { MNT_NOCLUSTERR,       "noclusterr" },
1655                 { MNT_NOCLUSTERW,       "noclusterw" },
1656                 { MNT_SUIDDIR,          "suiddir" },
1657                 { MNT_SOFTDEP,          "soft-updates" },
1658                 { MNT_IGNORE,           "ignore" }
1659         };
1660         const struct mountctl_opt *opt;
1661         int flags;
1662         int bwritten;
1663         int bleft;
1664         int optlen;
1665
1666         *errorp = 0;
1667         flags = mp->mnt_flag & MNT_VISFLAGMASK;
1668         bwritten = 0;
1669         bleft = len - 1;        /* leave room for trailing \0 */
1670         if (bleft < 0) {        /* degenerate case, 0-length buffer */
1671                 *errorp = EINVAL;
1672                 return(0);
1673         }
1674
1675         for (opt = optnames; flags && opt < &optnames[OPTARYSIZE]; ++opt) {
1676                 if ((flags & opt->o_opt) == 0)
1677                         continue;
1678                 optlen = strlen(opt->o_name);
1679                 if (bwritten) {
1680                         if (bleft == 0) {
1681                                 *errorp = ENOSPC;
1682                                 break;
1683                         }
1684                         buf[bwritten++] = ',';
1685                         --bleft;
1686                 }
1687                 if (bleft < optlen) {
1688                         *errorp = ENOSPC;
1689                         break;
1690                 }
1691                 bcopy(opt->o_name, buf + bwritten, optlen);
1692                 bwritten += optlen;
1693                 bleft -= optlen;
1694         }
1695
1696         /*
1697          * Space already reserved for trailing \0
1698          */
1699         buf[bwritten] = 0;
1700         return (bwritten);
1701 }
1702
1703 #undef OPTARYSIZE
1704
1705 /*
1706  * Build hash lists of net addresses and hang them off the mount point.
1707  * Called by ufs_mount() to set up the lists of export addresses.
1708  */
1709 static int
1710 vfs_hang_addrlist(struct mount *mp, struct netexport *nep,
1711                 const struct export_args *argp)
1712 {
1713         struct netcred *np;
1714         struct radix_node_head *rnh;
1715         int i;
1716         struct radix_node *rn;
1717         struct sockaddr *saddr, *smask = 0;
1718         struct domain *dom;
1719         int error;
1720
1721         if (argp->ex_addrlen == 0) {
1722                 if (mp->mnt_flag & MNT_DEFEXPORTED)
1723                         return (EPERM);
1724                 np = &nep->ne_defexported;
1725                 np->netc_exflags = argp->ex_flags;
1726                 np->netc_anon = argp->ex_anon;
1727                 np->netc_anon.cr_ref = 1;
1728                 mp->mnt_flag |= MNT_DEFEXPORTED;
1729                 return (0);
1730         }
1731
1732         if (argp->ex_addrlen < 0 || argp->ex_addrlen > MLEN)
1733                 return (EINVAL);
1734         if (argp->ex_masklen < 0 || argp->ex_masklen > MLEN)
1735                 return (EINVAL);
1736
1737         i = sizeof(struct netcred) + argp->ex_addrlen + argp->ex_masklen;
1738         np = (struct netcred *) kmalloc(i, M_NETADDR, M_WAITOK | M_ZERO);
1739         saddr = (struct sockaddr *) (np + 1);
1740         if ((error = copyin(argp->ex_addr, (caddr_t) saddr, argp->ex_addrlen)))
1741                 goto out;
1742         if (saddr->sa_len > argp->ex_addrlen)
1743                 saddr->sa_len = argp->ex_addrlen;
1744         if (argp->ex_masklen) {
1745                 smask = (struct sockaddr *)((caddr_t)saddr + argp->ex_addrlen);
1746                 error = copyin(argp->ex_mask, (caddr_t)smask, argp->ex_masklen);
1747                 if (error)
1748                         goto out;
1749                 if (smask->sa_len > argp->ex_masklen)
1750                         smask->sa_len = argp->ex_masklen;
1751         }
1752         i = saddr->sa_family;
1753         if ((rnh = nep->ne_rtable[i]) == 0) {
1754                 /*
1755                  * Seems silly to initialize every AF when most are not used,
1756                  * do so on demand here
1757                  */
1758                 SLIST_FOREACH(dom, &domains, dom_next)
1759                         if (dom->dom_family == i && dom->dom_rtattach) {
1760                                 dom->dom_rtattach((void **) &nep->ne_rtable[i],
1761                                     dom->dom_rtoffset);
1762                                 break;
1763                         }
1764                 if ((rnh = nep->ne_rtable[i]) == 0) {
1765                         error = ENOBUFS;
1766                         goto out;
1767                 }
1768         }
1769         rn = (*rnh->rnh_addaddr) ((char *) saddr, (char *) smask, rnh,
1770             np->netc_rnodes);
1771         if (rn == 0 || np != (struct netcred *) rn) {   /* already exists */
1772                 error = EPERM;
1773                 goto out;
1774         }
1775         np->netc_exflags = argp->ex_flags;
1776         np->netc_anon = argp->ex_anon;
1777         np->netc_anon.cr_ref = 1;
1778         return (0);
1779 out:
1780         kfree(np, M_NETADDR);
1781         return (error);
1782 }
1783
1784 /* ARGSUSED */
1785 static int
1786 vfs_free_netcred(struct radix_node *rn, void *w)
1787 {
1788         struct radix_node_head *rnh = (struct radix_node_head *) w;
1789
1790         (*rnh->rnh_deladdr) (rn->rn_key, rn->rn_mask, rnh);
1791         kfree((caddr_t) rn, M_NETADDR);
1792         return (0);
1793 }
1794
1795 /*
1796  * Free the net address hash lists that are hanging off the mount points.
1797  */
1798 static void
1799 vfs_free_addrlist(struct netexport *nep)
1800 {
1801         int i;
1802         struct radix_node_head *rnh;
1803
1804         for (i = 0; i <= AF_MAX; i++)
1805                 if ((rnh = nep->ne_rtable[i])) {
1806                         (*rnh->rnh_walktree) (rnh, vfs_free_netcred,
1807                             (caddr_t) rnh);
1808                         kfree((caddr_t) rnh, M_RTABLE);
1809                         nep->ne_rtable[i] = 0;
1810                 }
1811 }
1812
1813 int
1814 vfs_export(struct mount *mp, struct netexport *nep,
1815            const struct export_args *argp)
1816 {
1817         int error;
1818
1819         if (argp->ex_flags & MNT_DELEXPORT) {
1820                 if (mp->mnt_flag & MNT_EXPUBLIC) {
1821                         vfs_setpublicfs(NULL, NULL, NULL);
1822                         mp->mnt_flag &= ~MNT_EXPUBLIC;
1823                 }
1824                 vfs_free_addrlist(nep);
1825                 mp->mnt_flag &= ~(MNT_EXPORTED | MNT_DEFEXPORTED);
1826         }
1827         if (argp->ex_flags & MNT_EXPORTED) {
1828                 if (argp->ex_flags & MNT_EXPUBLIC) {
1829                         if ((error = vfs_setpublicfs(mp, nep, argp)) != 0)
1830                                 return (error);
1831                         mp->mnt_flag |= MNT_EXPUBLIC;
1832                 }
1833                 if ((error = vfs_hang_addrlist(mp, nep, argp)))
1834                         return (error);
1835                 mp->mnt_flag |= MNT_EXPORTED;
1836         }
1837         return (0);
1838 }
1839
1840
1841 /*
1842  * Set the publicly exported filesystem (WebNFS). Currently, only
1843  * one public filesystem is possible in the spec (RFC 2054 and 2055)
1844  */
1845 int
1846 vfs_setpublicfs(struct mount *mp, struct netexport *nep,
1847                 const struct export_args *argp)
1848 {
1849         int error;
1850         struct vnode *rvp;
1851         char *cp;
1852
1853         /*
1854          * mp == NULL -> invalidate the current info, the FS is
1855          * no longer exported. May be called from either vfs_export
1856          * or unmount, so check if it hasn't already been done.
1857          */
1858         if (mp == NULL) {
1859                 if (nfs_pub.np_valid) {
1860                         nfs_pub.np_valid = 0;
1861                         if (nfs_pub.np_index != NULL) {
1862                                 FREE(nfs_pub.np_index, M_TEMP);
1863                                 nfs_pub.np_index = NULL;
1864                         }
1865                 }
1866                 return (0);
1867         }
1868
1869         /*
1870          * Only one allowed at a time.
1871          */
1872         if (nfs_pub.np_valid != 0 && mp != nfs_pub.np_mount)
1873                 return (EBUSY);
1874
1875         /*
1876          * Get real filehandle for root of exported FS.
1877          */
1878         bzero((caddr_t)&nfs_pub.np_handle, sizeof(nfs_pub.np_handle));
1879         nfs_pub.np_handle.fh_fsid = mp->mnt_stat.f_fsid;
1880
1881         if ((error = VFS_ROOT(mp, &rvp)))
1882                 return (error);
1883
1884         if ((error = VFS_VPTOFH(rvp, &nfs_pub.np_handle.fh_fid)))
1885                 return (error);
1886
1887         vput(rvp);
1888
1889         /*
1890          * If an indexfile was specified, pull it in.
1891          */
1892         if (argp->ex_indexfile != NULL) {
1893                 int namelen;
1894
1895                 error = vn_get_namelen(rvp, &namelen);
1896                 if (error)
1897                         return (error);
1898                 MALLOC(nfs_pub.np_index, char *, namelen, M_TEMP,
1899                     M_WAITOK);
1900                 error = copyinstr(argp->ex_indexfile, nfs_pub.np_index,
1901                     namelen, NULL);
1902                 if (!error) {
1903                         /*
1904                          * Check for illegal filenames.
1905                          */
1906                         for (cp = nfs_pub.np_index; *cp; cp++) {
1907                                 if (*cp == '/') {
1908                                         error = EINVAL;
1909                                         break;
1910                                 }
1911                         }
1912                 }
1913                 if (error) {
1914                         FREE(nfs_pub.np_index, M_TEMP);
1915                         return (error);
1916                 }
1917         }
1918
1919         nfs_pub.np_mount = mp;
1920         nfs_pub.np_valid = 1;
1921         return (0);
1922 }
1923
1924 struct netcred *
1925 vfs_export_lookup(struct mount *mp, struct netexport *nep,
1926                 struct sockaddr *nam)
1927 {
1928         struct netcred *np;
1929         struct radix_node_head *rnh;
1930         struct sockaddr *saddr;
1931
1932         np = NULL;
1933         if (mp->mnt_flag & MNT_EXPORTED) {
1934                 /*
1935                  * Lookup in the export list first.
1936                  */
1937                 if (nam != NULL) {
1938                         saddr = nam;
1939                         rnh = nep->ne_rtable[saddr->sa_family];
1940                         if (rnh != NULL) {
1941                                 np = (struct netcred *)
1942                                         (*rnh->rnh_matchaddr)((char *)saddr,
1943                                                               rnh);
1944                                 if (np && np->netc_rnodes->rn_flags & RNF_ROOT)
1945                                         np = NULL;
1946                         }
1947                 }
1948                 /*
1949                  * If no address match, use the default if it exists.
1950                  */
1951                 if (np == NULL && mp->mnt_flag & MNT_DEFEXPORTED)
1952                         np = &nep->ne_defexported;
1953         }
1954         return (np);
1955 }
1956
1957 /*
1958  * perform msync on all vnodes under a mount point.  The mount point must
1959  * be locked.  This code is also responsible for lazy-freeing unreferenced
1960  * vnodes whos VM objects no longer contain pages.
1961  *
1962  * NOTE: MNT_WAIT still skips vnodes in the VXLOCK state.
1963  *
1964  * NOTE: XXX VOP_PUTPAGES and friends requires that the vnode be locked,
1965  * but vnode_pager_putpages() doesn't lock the vnode.  We have to do it
1966  * way up in this high level function.
1967  */
1968 static int vfs_msync_scan1(struct mount *mp, struct vnode *vp, void *data);
1969 static int vfs_msync_scan2(struct mount *mp, struct vnode *vp, void *data);
1970
1971 void
1972 vfs_msync(struct mount *mp, int flags) 
1973 {
1974         int vmsc_flags;
1975
1976         vmsc_flags = VMSC_GETVP;
1977         if (flags != MNT_WAIT)
1978                 vmsc_flags |= VMSC_NOWAIT;
1979         vmntvnodescan(mp, vmsc_flags, vfs_msync_scan1, vfs_msync_scan2,
1980                         (void *)(intptr_t)flags);
1981 }
1982
1983 /*
1984  * scan1 is a fast pre-check.  There could be hundreds of thousands of
1985  * vnodes, we cannot afford to do anything heavy weight until we have a
1986  * fairly good indication that there is work to do.
1987  */
1988 static
1989 int
1990 vfs_msync_scan1(struct mount *mp, struct vnode *vp, void *data)
1991 {
1992         int flags = (int)(intptr_t)data;
1993
1994         if ((vp->v_flag & VRECLAIMED) == 0) {
1995                 if (vshouldmsync(vp))
1996                         return(0);      /* call scan2 */
1997                 if ((mp->mnt_flag & MNT_RDONLY) == 0 &&
1998                     (vp->v_flag & VOBJDIRTY) &&
1999                     (flags == MNT_WAIT || vn_islocked(vp) == 0)) {
2000                         return(0);      /* call scan2 */
2001                 }
2002         }
2003
2004         /*
2005          * do not call scan2, continue the loop
2006          */
2007         return(-1);
2008 }
2009
2010 /*
2011  * This callback is handed a locked vnode.
2012  */
2013 static
2014 int
2015 vfs_msync_scan2(struct mount *mp, struct vnode *vp, void *data)
2016 {
2017         vm_object_t obj;
2018         int flags = (int)(intptr_t)data;
2019
2020         if (vp->v_flag & VRECLAIMED)
2021                 return(0);
2022
2023         if ((mp->mnt_flag & MNT_RDONLY) == 0 && (vp->v_flag & VOBJDIRTY)) {
2024                 if ((obj = vp->v_object) != NULL) {
2025                         vm_object_page_clean(obj, 0, 0, 
2026                          flags == MNT_WAIT ? OBJPC_SYNC : OBJPC_NOSYNC);
2027                 }
2028         }
2029         return(0);
2030 }
2031
2032 /*
2033  * Record a process's interest in events which might happen to
2034  * a vnode.  Because poll uses the historic select-style interface
2035  * internally, this routine serves as both the ``check for any
2036  * pending events'' and the ``record my interest in future events''
2037  * functions.  (These are done together, while the lock is held,
2038  * to avoid race conditions.)
2039  */
2040 int
2041 vn_pollrecord(struct vnode *vp, int events)
2042 {
2043         lwkt_tokref vlock;
2044
2045         KKASSERT(curthread->td_proc != NULL);
2046
2047         lwkt_gettoken(&vlock, &vp->v_token);
2048         if (vp->v_pollinfo.vpi_revents & events) {
2049                 /*
2050                  * This leaves events we are not interested
2051                  * in available for the other process which
2052                  * which presumably had requested them
2053                  * (otherwise they would never have been
2054                  * recorded).
2055                  */
2056                 events &= vp->v_pollinfo.vpi_revents;
2057                 vp->v_pollinfo.vpi_revents &= ~events;
2058
2059                 lwkt_reltoken(&vlock);
2060                 return events;
2061         }
2062         vp->v_pollinfo.vpi_events |= events;
2063         selrecord(curthread, &vp->v_pollinfo.vpi_selinfo);
2064         lwkt_reltoken(&vlock);
2065         return 0;
2066 }
2067
2068 /*
2069  * Note the occurrence of an event.  If the VN_POLLEVENT macro is used,
2070  * it is possible for us to miss an event due to race conditions, but
2071  * that condition is expected to be rare, so for the moment it is the
2072  * preferred interface.
2073  */
2074 void
2075 vn_pollevent(struct vnode *vp, int events)
2076 {
2077         lwkt_tokref vlock;
2078
2079         lwkt_gettoken(&vlock, &vp->v_token);
2080         if (vp->v_pollinfo.vpi_events & events) {
2081                 /*
2082                  * We clear vpi_events so that we don't
2083                  * call selwakeup() twice if two events are
2084                  * posted before the polling process(es) is
2085                  * awakened.  This also ensures that we take at
2086                  * most one selwakeup() if the polling process
2087                  * is no longer interested.  However, it does
2088                  * mean that only one event can be noticed at
2089                  * a time.  (Perhaps we should only clear those
2090                  * event bits which we note?) XXX
2091                  */
2092                 vp->v_pollinfo.vpi_events = 0;  /* &= ~events ??? */
2093                 vp->v_pollinfo.vpi_revents |= events;
2094                 selwakeup(&vp->v_pollinfo.vpi_selinfo);
2095         }
2096         lwkt_reltoken(&vlock);
2097 }
2098
2099 /*
2100  * Wake up anyone polling on vp because it is being revoked.
2101  * This depends on dead_poll() returning POLLHUP for correct
2102  * behavior.
2103  */
2104 void
2105 vn_pollgone(struct vnode *vp)
2106 {
2107         lwkt_tokref vlock;
2108
2109         lwkt_gettoken(&vlock, &vp->v_token);
2110         if (vp->v_pollinfo.vpi_events) {
2111                 vp->v_pollinfo.vpi_events = 0;
2112                 selwakeup(&vp->v_pollinfo.vpi_selinfo);
2113         }
2114         lwkt_reltoken(&vlock);
2115 }
2116
2117 /*
2118  * extract the cdev_t from a VBLK or VCHR.  The vnode must have been opened
2119  * (or v_rdev might be NULL).
2120  */
2121 cdev_t
2122 vn_todev(struct vnode *vp)
2123 {
2124         if (vp->v_type != VBLK && vp->v_type != VCHR)
2125                 return (NULL);
2126         KKASSERT(vp->v_rdev != NULL);
2127         return (vp->v_rdev);
2128 }
2129
2130 /*
2131  * Check if vnode represents a disk device.  The vnode does not need to be
2132  * opened.
2133  *
2134  * MPALMOSTSAFE
2135  */
2136 int
2137 vn_isdisk(struct vnode *vp, int *errp)
2138 {
2139         cdev_t dev;
2140
2141         if (vp->v_type != VCHR) {
2142                 if (errp != NULL)
2143                         *errp = ENOTBLK;
2144                 return (0);
2145         }
2146
2147         dev = vp->v_rdev;
2148
2149         if (dev == NULL) {
2150                 if (errp != NULL)
2151                         *errp = ENXIO;
2152                 return (0);
2153         }
2154         if (dev_is_good(dev) == 0) {
2155                 if (errp != NULL)
2156                         *errp = ENXIO;
2157                 return (0);
2158         }
2159         if ((dev_dflags(dev) & D_DISK) == 0) {
2160                 if (errp != NULL)
2161                         *errp = ENOTBLK;
2162                 return (0);
2163         }
2164         if (errp != NULL)
2165                 *errp = 0;
2166         return (1);
2167 }
2168
2169 int
2170 vn_get_namelen(struct vnode *vp, int *namelen)
2171 {
2172         int error;
2173         register_t retval[2];
2174
2175         error = VOP_PATHCONF(vp, _PC_NAME_MAX, retval);
2176         if (error)
2177                 return (error);
2178         *namelen = (int)retval[0];
2179         return (0);
2180 }
2181
2182 int
2183 vop_write_dirent(int *error, struct uio *uio, ino_t d_ino, uint8_t d_type, 
2184                 uint16_t d_namlen, const char *d_name)
2185 {
2186         struct dirent *dp;
2187         size_t len;
2188
2189         len = _DIRENT_RECLEN(d_namlen);
2190         if (len > uio->uio_resid)
2191                 return(1);
2192
2193         dp = kmalloc(len, M_TEMP, M_WAITOK | M_ZERO);
2194
2195         dp->d_ino = d_ino;
2196         dp->d_namlen = d_namlen;
2197         dp->d_type = d_type;
2198         bcopy(d_name, dp->d_name, d_namlen);
2199
2200         *error = uiomove((caddr_t)dp, len, uio);
2201
2202         kfree(dp, M_TEMP);
2203
2204         return(0);
2205 }
2206
2207 void
2208 vn_mark_atime(struct vnode *vp, struct thread *td)
2209 {
2210         struct proc *p = td->td_proc;
2211         struct ucred *cred = p ? p->p_ucred : proc0.p_ucred;
2212
2213         if ((vp->v_mount->mnt_flag & (MNT_NOATIME | MNT_RDONLY)) == 0) {
2214                 VOP_MARKATIME(vp, cred);
2215         }
2216 }