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