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