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