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