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