hammer2 - Add directive to destroy bad directory entries
[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 #include <vm/vm_page2.h>
87
88 #include <netinet/in.h>
89
90 static MALLOC_DEFINE(M_NETCRED, "Export Host", "Export host address structure");
91
92 int numvnodes;
93 SYSCTL_INT(_debug, OID_AUTO, numvnodes, CTLFLAG_RD, &numvnodes, 0,
94     "Number of vnodes allocated");
95 int verbose_reclaims;
96 SYSCTL_INT(_debug, OID_AUTO, verbose_reclaims, CTLFLAG_RD, &verbose_reclaims, 0,
97     "Output filename of reclaimed vnode(s)");
98
99 enum vtype iftovt_tab[16] = {
100         VNON, VFIFO, VCHR, VNON, VDIR, VNON, VBLK, VNON,
101         VREG, VNON, VLNK, VNON, VSOCK, VNON, VNON, VBAD,
102 };
103 int vttoif_tab[9] = {
104         0, S_IFREG, S_IFDIR, S_IFBLK, S_IFCHR, S_IFLNK,
105         S_IFSOCK, S_IFIFO, S_IFMT,
106 };
107
108 static int reassignbufcalls;
109 SYSCTL_INT(_vfs, OID_AUTO, reassignbufcalls, CTLFLAG_RW, &reassignbufcalls,
110     0, "Number of times buffers have been reassigned to the proper list");
111
112 static int check_buf_overlap = 2;       /* invasive check */
113 SYSCTL_INT(_vfs, OID_AUTO, check_buf_overlap, CTLFLAG_RW, &check_buf_overlap,
114     0, "Enable overlapping buffer checks");
115
116 int     nfs_mount_type = -1;
117 static struct lwkt_token spechash_token;
118 struct nfs_public nfs_pub;      /* publicly exported FS */
119
120 int maxvnodes;
121 SYSCTL_INT(_kern, KERN_MAXVNODES, maxvnodes, CTLFLAG_RW, 
122            &maxvnodes, 0, "Maximum number of vnodes");
123
124 static struct radix_node_head *vfs_create_addrlist_af(int af,
125                     struct netexport *nep);
126 static void     vfs_free_addrlist (struct netexport *nep);
127 static int      vfs_free_netcred (struct radix_node *rn, void *w);
128 static void     vfs_free_addrlist_af (struct radix_node_head **prnh);
129 static int      vfs_hang_addrlist (struct mount *mp, struct netexport *nep,
130                     const struct export_args *argp);
131
132 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 void
157 vfs_subr_init(void)
158 {
159         int factor1;
160         int factor2;
161
162         /*
163          * Desiredvnodes is kern.maxvnodes.  We want to scale it 
164          * according to available system memory but we may also have
165          * to limit it based on available KVM, which is capped on 32 bit
166          * systems, to ~80K vnodes or so.
167          *
168          * WARNING!  For machines with 64-256M of ram we have to be sure
169          *           that the default limit scales down well due to HAMMER
170          *           taking up significantly more memory per-vnode vs UFS.
171          *           We want around ~5800 on a 128M machine.
172          */
173         factor1 = 25 * (sizeof(struct vm_object) + sizeof(struct vnode));
174         factor2 = 30 * (sizeof(struct vm_object) + sizeof(struct vnode));
175         maxvnodes = imin((int64_t)vmstats.v_page_count * PAGE_SIZE / factor1,
176                          KvaSize / factor2);
177         maxvnodes = imax(maxvnodes, 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 fastpass;
628         int synchronous;
629         int syncdeps;
630         int lazycount;
631         int lazylimit;
632         int skippedbufs;
633         int (*checkdef)(struct buf *);
634         int (*cmpfunc)(struct buf *, void *);
635 };
636
637 int
638 vfsync(struct vnode *vp, int waitfor, int passes,
639         int (*checkdef)(struct buf *),
640         int (*waitoutput)(struct vnode *, struct thread *))
641 {
642         struct vfsync_info info;
643         int error;
644
645         bzero(&info, sizeof(info));
646         info.vp = vp;
647         if ((info.checkdef = checkdef) == NULL)
648                 info.syncdeps = 1;
649
650         lwkt_gettoken(&vp->v_token);
651
652         switch(waitfor) {
653         case MNT_LAZY | MNT_NOWAIT:
654         case MNT_LAZY:
655                 /*
656                  * Lazy (filesystem syncer typ) Asynchronous plus limit the
657                  * number of data (not meta) pages we try to flush to 1MB.
658                  * A non-zero return means that lazy limit was reached.
659                  */
660                 info.lazylimit = 1024 * 1024;
661                 info.syncdeps = 1;
662                 info.cmpfunc = vfsync_lazy_range_cmp;
663                 error = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, 
664                                 vfsync_lazy_range_cmp, vfsync_bp, &info);
665                 info.cmpfunc = vfsync_meta_only_cmp;
666                 RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, 
667                         vfsync_meta_only_cmp, vfsync_bp, &info);
668                 if (error == 0)
669                         vp->v_lazyw = 0;
670                 else if (!RB_EMPTY(&vp->v_rbdirty_tree))
671                         vn_syncer_add(vp, 1);
672                 error = 0;
673                 break;
674         case MNT_NOWAIT:
675                 /*
676                  * Asynchronous.  Do a data-only pass and a meta-only pass.
677                  */
678                 info.syncdeps = 1;
679                 info.cmpfunc = vfsync_data_only_cmp;
680                 RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, vfsync_data_only_cmp, 
681                         vfsync_bp, &info);
682                 info.cmpfunc = vfsync_meta_only_cmp;
683                 RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, vfsync_meta_only_cmp, 
684                         vfsync_bp, &info);
685                 error = 0;
686                 break;
687         default:
688                 /*
689                  * Synchronous.  Do a data-only pass, then a meta-data+data
690                  * pass, then additional integrated passes to try to get
691                  * all the dependancies flushed.
692                  */
693                 info.cmpfunc = vfsync_data_only_cmp;
694                 info.fastpass = 1;
695                 RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, vfsync_data_only_cmp,
696                         vfsync_bp, &info);
697                 info.fastpass = 0;
698                 error = vfsync_wait_output(vp, waitoutput);
699                 if (error == 0) {
700                         info.skippedbufs = 0;
701                         info.cmpfunc = vfsync_dummy_cmp;
702                         RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, NULL,
703                                 vfsync_bp, &info);
704                         error = vfsync_wait_output(vp, waitoutput);
705                         if (info.skippedbufs) {
706                                 kprintf("Warning: vfsync skipped %d dirty "
707                                         "buf%s in pass2!\n",
708                                         info.skippedbufs,
709                                         ((info.skippedbufs > 1) ? "s" : ""));
710                         }
711                 }
712                 while (error == 0 && passes > 0 &&
713                        !RB_EMPTY(&vp->v_rbdirty_tree)
714                 ) {
715                         info.skippedbufs = 0;
716                         if (--passes == 0) {
717                                 info.synchronous = 1;
718                                 info.syncdeps = 1;
719                         }
720                         info.cmpfunc = vfsync_dummy_cmp;
721                         error = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, NULL,
722                                         vfsync_bp, &info);
723                         if (error < 0)
724                                 error = -error;
725                         info.syncdeps = 1;
726                         if (error == 0)
727                                 error = vfsync_wait_output(vp, waitoutput);
728                         if (info.skippedbufs && passes == 0) {
729                                 kprintf("Warning: vfsync skipped %d dirty "
730                                         "buf%s in final pass!\n",
731                                         info.skippedbufs,
732                                         ((info.skippedbufs > 1) ? "s" : ""));
733                         }
734                 }
735 #if 0
736                 /*
737                  * This case can occur normally because vnode lock might
738                  * not be held.
739                  */
740                 if (!RB_EMPTY(&vp->v_rbdirty_tree))
741                         kprintf("dirty bufs left after final pass\n");
742 #endif
743                 break;
744         }
745         lwkt_reltoken(&vp->v_token);
746
747         return(error);
748 }
749
750 static int
751 vfsync_wait_output(struct vnode *vp,
752                    int (*waitoutput)(struct vnode *, struct thread *))
753 {
754         int error;
755
756         error = bio_track_wait(&vp->v_track_write, 0, 0);
757         if (waitoutput)
758                 error = waitoutput(vp, curthread);
759         return(error);
760 }
761
762 static int
763 vfsync_dummy_cmp(struct buf *bp __unused, void *data __unused)
764 {
765         return(0);
766 }
767
768 static int
769 vfsync_data_only_cmp(struct buf *bp, void *data)
770 {
771         if (bp->b_loffset < 0)
772                 return(-1);
773         return(0);
774 }
775
776 static int
777 vfsync_meta_only_cmp(struct buf *bp, void *data)
778 {
779         if (bp->b_loffset < 0)
780                 return(0);
781         return(1);
782 }
783
784 static int
785 vfsync_lazy_range_cmp(struct buf *bp, void *data)
786 {
787         struct vfsync_info *info = data;
788
789         if (bp->b_loffset < info->vp->v_lazyw)
790                 return(-1);
791         return(0);
792 }
793
794 static int
795 vfsync_bp(struct buf *bp, void *data)
796 {
797         struct vfsync_info *info = data;
798         struct vnode *vp = info->vp;
799         int error;
800
801         if (info->fastpass) {
802                 /*
803                  * Ignore buffers that we cannot immediately lock.
804                  */
805                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
806                         if (BUF_TIMELOCK(bp, LK_EXCLUSIVE, "bflst1", 1)) {
807                                 ++info->skippedbufs;
808                                 return(0);
809                         }
810                 }
811         } else if (info->synchronous == 0) {
812                 /*
813                  * Normal pass, give the buffer a little time to become
814                  * available to us.
815                  */
816                 if (BUF_TIMELOCK(bp, LK_EXCLUSIVE, "bflst2", hz / 10)) {
817                         ++info->skippedbufs;
818                         return(0);
819                 }
820         } else {
821                 /*
822                  * Synchronous pass, give the buffer a lot of time before
823                  * giving up.
824                  */
825                 if (BUF_TIMELOCK(bp, LK_EXCLUSIVE, "bflst3", hz * 10)) {
826                         ++info->skippedbufs;
827                         return(0);
828                 }
829         }
830
831         /*
832          * We must revalidate the buffer after locking.
833          */
834         if ((bp->b_flags & B_DELWRI) == 0 ||
835             bp->b_vp != info->vp ||
836             info->cmpfunc(bp, data)) {
837                 BUF_UNLOCK(bp);
838                 return(0);
839         }
840
841         /*
842          * If syncdeps is not set we do not try to write buffers which have
843          * dependancies.
844          */
845         if (!info->synchronous && info->syncdeps == 0 && info->checkdef(bp)) {
846                 BUF_UNLOCK(bp);
847                 return(0);
848         }
849
850         /*
851          * B_NEEDCOMMIT (primarily used by NFS) is a state where the buffer
852          * has been written but an additional handshake with the device
853          * is required before we can dispose of the buffer.  We have no idea
854          * how to do this so we have to skip these buffers.
855          */
856         if (bp->b_flags & B_NEEDCOMMIT) {
857                 BUF_UNLOCK(bp);
858                 return(0);
859         }
860
861         /*
862          * Ask bioops if it is ok to sync.  If not the VFS may have
863          * set B_LOCKED so we have to cycle the buffer.
864          */
865         if (LIST_FIRST(&bp->b_dep) != NULL && buf_checkwrite(bp)) {
866                 bremfree(bp);
867                 brelse(bp);
868                 return(0);
869         }
870
871         if (info->synchronous) {
872                 /*
873                  * Synchronous flush.  An error may be returned and will
874                  * stop the scan.
875                  */
876                 bremfree(bp);
877                 error = bwrite(bp);
878         } else {
879                 /*
880                  * Asynchronous flush.  We use the error return to support
881                  * MNT_LAZY flushes.
882                  *
883                  * In low-memory situations we revert to synchronous
884                  * operation.  This should theoretically prevent the I/O
885                  * path from exhausting memory in a non-recoverable way.
886                  */
887                 vp->v_lazyw = bp->b_loffset;
888                 bremfree(bp);
889                 if (vm_page_count_min(0)) {
890                         /* low memory */
891                         info->lazycount += bp->b_bufsize;
892                         bwrite(bp);
893                 } else {
894                         /* normal */
895                         info->lazycount += cluster_awrite(bp);
896                         waitrunningbufspace();
897                         /*vm_wait_nominal();*/
898                 }
899                 if (info->lazylimit && info->lazycount >= info->lazylimit)
900                         error = 1;
901                 else
902                         error = 0;
903         }
904         return(-error);
905 }
906
907 /*
908  * Associate a buffer with a vnode.
909  *
910  * MPSAFE
911  */
912 int
913 bgetvp(struct vnode *vp, struct buf *bp, int testsize)
914 {
915         KASSERT(bp->b_vp == NULL, ("bgetvp: not free"));
916         KKASSERT((bp->b_flags & (B_HASHED|B_DELWRI|B_VNCLEAN|B_VNDIRTY)) == 0);
917
918         /*
919          * Insert onto list for new vnode.
920          */
921         lwkt_gettoken(&vp->v_token);
922
923         if (buf_rb_hash_RB_INSERT(&vp->v_rbhash_tree, bp)) {
924                 lwkt_reltoken(&vp->v_token);
925                 return (EEXIST);
926         }
927
928         /*
929          * Diagnostics (mainly for HAMMER debugging).  Check for
930          * overlapping buffers.
931          */
932         if (check_buf_overlap) {
933                 struct buf *bx;
934                 bx = buf_rb_hash_RB_PREV(bp);
935                 if (bx) {
936                         if (bx->b_loffset + bx->b_bufsize > bp->b_loffset) {
937                                 kprintf("bgetvp: overlapl %016jx/%d %016jx "
938                                         "bx %p bp %p\n",
939                                         (intmax_t)bx->b_loffset,
940                                         bx->b_bufsize,
941                                         (intmax_t)bp->b_loffset,
942                                         bx, bp);
943                                 if (check_buf_overlap > 1)
944                                         panic("bgetvp - overlapping buffer");
945                         }
946                 }
947                 bx = buf_rb_hash_RB_NEXT(bp);
948                 if (bx) {
949                         if (bp->b_loffset + testsize > bx->b_loffset) {
950                                 kprintf("bgetvp: overlapr %016jx/%d %016jx "
951                                         "bp %p bx %p\n",
952                                         (intmax_t)bp->b_loffset,
953                                         testsize,
954                                         (intmax_t)bx->b_loffset,
955                                         bp, bx);
956                                 if (check_buf_overlap > 1)
957                                         panic("bgetvp - overlapping buffer");
958                         }
959                 }
960         }
961         bp->b_vp = vp;
962         bp->b_flags |= B_HASHED;
963         bp->b_flags |= B_VNCLEAN;
964         if (buf_rb_tree_RB_INSERT(&vp->v_rbclean_tree, bp))
965                 panic("reassignbuf: dup lblk/clean vp %p bp %p", vp, bp);
966         /*vhold(vp);*/
967         lwkt_reltoken(&vp->v_token);
968         return(0);
969 }
970
971 /*
972  * Disassociate a buffer from a vnode.
973  *
974  * MPSAFE
975  */
976 void
977 brelvp(struct buf *bp)
978 {
979         struct vnode *vp;
980
981         KASSERT(bp->b_vp != NULL, ("brelvp: NULL"));
982
983         /*
984          * Delete from old vnode list, if on one.
985          */
986         vp = bp->b_vp;
987         lwkt_gettoken(&vp->v_token);
988         if (bp->b_flags & (B_VNDIRTY | B_VNCLEAN)) {
989                 if (bp->b_flags & B_VNDIRTY)
990                         buf_rb_tree_RB_REMOVE(&vp->v_rbdirty_tree, bp);
991                 else
992                         buf_rb_tree_RB_REMOVE(&vp->v_rbclean_tree, bp);
993                 bp->b_flags &= ~(B_VNDIRTY | B_VNCLEAN);
994         }
995         if (bp->b_flags & B_HASHED) {
996                 buf_rb_hash_RB_REMOVE(&vp->v_rbhash_tree, bp);
997                 bp->b_flags &= ~B_HASHED;
998         }
999
1000         /*
1001          * Only remove from synclist when no dirty buffers are left AND
1002          * the VFS has not flagged the vnode's inode as being dirty.
1003          */
1004         if ((vp->v_flag & (VONWORKLST | VISDIRTY | VOBJDIRTY)) == VONWORKLST &&
1005             RB_EMPTY(&vp->v_rbdirty_tree)) {
1006                 vn_syncer_remove(vp, 0);
1007         }
1008         bp->b_vp = NULL;
1009
1010         lwkt_reltoken(&vp->v_token);
1011
1012         /*vdrop(vp);*/
1013 }
1014
1015 /*
1016  * Reassign the buffer to the proper clean/dirty list based on B_DELWRI.
1017  * This routine is called when the state of the B_DELWRI bit is changed.
1018  *
1019  * Must be called with vp->v_token held.
1020  * MPSAFE
1021  */
1022 void
1023 reassignbuf(struct buf *bp)
1024 {
1025         struct vnode *vp = bp->b_vp;
1026         int delay;
1027
1028         ASSERT_LWKT_TOKEN_HELD(&vp->v_token);
1029         ++reassignbufcalls;
1030
1031         /*
1032          * B_PAGING flagged buffers cannot be reassigned because their vp
1033          * is not fully linked in.
1034          */
1035         if (bp->b_flags & B_PAGING)
1036                 panic("cannot reassign paging buffer");
1037
1038         if (bp->b_flags & B_DELWRI) {
1039                 /*
1040                  * Move to the dirty list, add the vnode to the worklist
1041                  */
1042                 if (bp->b_flags & B_VNCLEAN) {
1043                         buf_rb_tree_RB_REMOVE(&vp->v_rbclean_tree, bp);
1044                         bp->b_flags &= ~B_VNCLEAN;
1045                 }
1046                 if ((bp->b_flags & B_VNDIRTY) == 0) {
1047                         if (buf_rb_tree_RB_INSERT(&vp->v_rbdirty_tree, bp)) {
1048                                 panic("reassignbuf: dup lblk vp %p bp %p",
1049                                       vp, bp);
1050                         }
1051                         bp->b_flags |= B_VNDIRTY;
1052                 }
1053                 if ((vp->v_flag & VONWORKLST) == 0) {
1054                         switch (vp->v_type) {
1055                         case VDIR:
1056                                 delay = dirdelay;
1057                                 break;
1058                         case VCHR:
1059                         case VBLK:
1060                                 if (vp->v_rdev && 
1061                                     vp->v_rdev->si_mountpoint != NULL) {
1062                                         delay = metadelay;
1063                                         break;
1064                                 }
1065                                 /* fall through */
1066                         default:
1067                                 delay = filedelay;
1068                         }
1069                         vn_syncer_add(vp, delay);
1070                 }
1071         } else {
1072                 /*
1073                  * Move to the clean list, remove the vnode from the worklist
1074                  * if no dirty blocks remain.
1075                  */
1076                 if (bp->b_flags & B_VNDIRTY) {
1077                         buf_rb_tree_RB_REMOVE(&vp->v_rbdirty_tree, bp);
1078                         bp->b_flags &= ~B_VNDIRTY;
1079                 }
1080                 if ((bp->b_flags & B_VNCLEAN) == 0) {
1081                         if (buf_rb_tree_RB_INSERT(&vp->v_rbclean_tree, bp)) {
1082                                 panic("reassignbuf: dup lblk vp %p bp %p",
1083                                       vp, bp);
1084                         }
1085                         bp->b_flags |= B_VNCLEAN;
1086                 }
1087
1088                 /*
1089                  * Only remove from synclist when no dirty buffers are left
1090                  * AND the VFS has not flagged the vnode's inode as being
1091                  * dirty.
1092                  */
1093                 if ((vp->v_flag & (VONWORKLST | VISDIRTY | VOBJDIRTY)) ==
1094                      VONWORKLST &&
1095                     RB_EMPTY(&vp->v_rbdirty_tree)) {
1096                         vn_syncer_remove(vp, 0);
1097                 }
1098         }
1099 }
1100
1101 /*
1102  * Create a vnode for a block device.  Used for mounting the root file
1103  * system.
1104  *
1105  * A vref()'d vnode is returned.
1106  */
1107 extern struct vop_ops *devfs_vnode_dev_vops_p;
1108 int
1109 bdevvp(cdev_t dev, struct vnode **vpp)
1110 {
1111         struct vnode *vp;
1112         struct vnode *nvp;
1113         int error;
1114
1115         if (dev == NULL) {
1116                 *vpp = NULLVP;
1117                 return (ENXIO);
1118         }
1119         error = getspecialvnode(VT_NON, NULL, &devfs_vnode_dev_vops_p,
1120                                 &nvp, 0, 0);
1121         if (error) {
1122                 *vpp = NULLVP;
1123                 return (error);
1124         }
1125         vp = nvp;
1126         vp->v_type = VCHR;
1127 #if 0
1128         vp->v_rdev = dev;
1129 #endif
1130         v_associate_rdev(vp, dev);
1131         vp->v_umajor = dev->si_umajor;
1132         vp->v_uminor = dev->si_uminor;
1133         vx_unlock(vp);
1134         *vpp = vp;
1135         return (0);
1136 }
1137
1138 int
1139 v_associate_rdev(struct vnode *vp, cdev_t dev)
1140 {
1141         if (dev == NULL)
1142                 return(ENXIO);
1143         if (dev_is_good(dev) == 0)
1144                 return(ENXIO);
1145         KKASSERT(vp->v_rdev == NULL);
1146         vp->v_rdev = reference_dev(dev);
1147         lwkt_gettoken(&spechash_token);
1148         SLIST_INSERT_HEAD(&dev->si_hlist, vp, v_cdevnext);
1149         lwkt_reltoken(&spechash_token);
1150         return(0);
1151 }
1152
1153 void
1154 v_release_rdev(struct vnode *vp)
1155 {
1156         cdev_t dev;
1157
1158         if ((dev = vp->v_rdev) != NULL) {
1159                 lwkt_gettoken(&spechash_token);
1160                 SLIST_REMOVE(&dev->si_hlist, vp, vnode, v_cdevnext);
1161                 vp->v_rdev = NULL;
1162                 release_dev(dev);
1163                 lwkt_reltoken(&spechash_token);
1164         }
1165 }
1166
1167 /*
1168  * Add a vnode to the alias list hung off the cdev_t.  We only associate
1169  * the device number with the vnode.  The actual device is not associated
1170  * until the vnode is opened (usually in spec_open()), and will be 
1171  * disassociated on last close.
1172  */
1173 void
1174 addaliasu(struct vnode *nvp, int x, int y)
1175 {
1176         if (nvp->v_type != VBLK && nvp->v_type != VCHR)
1177                 panic("addaliasu on non-special vnode");
1178         nvp->v_umajor = x;
1179         nvp->v_uminor = y;
1180 }
1181
1182 /*
1183  * Simple call that a filesystem can make to try to get rid of a
1184  * vnode.  It will fail if anyone is referencing the vnode (including
1185  * the caller).
1186  *
1187  * The filesystem can check whether its in-memory inode structure still
1188  * references the vp on return.
1189  *
1190  * May only be called if the vnode is in a known state (i.e. being prevented
1191  * from being deallocated by some other condition such as a vfs inode hold).
1192  */
1193 void
1194 vclean_unlocked(struct vnode *vp)
1195 {
1196         vx_get(vp);
1197         if (VREFCNT(vp) <= 1)
1198                 vgone_vxlocked(vp);
1199         vx_put(vp);
1200 }
1201
1202 /*
1203  * Disassociate a vnode from its underlying filesystem. 
1204  *
1205  * The vnode must be VX locked and referenced.  In all normal situations
1206  * there are no active references.  If vclean_vxlocked() is called while
1207  * there are active references, the vnode is being ripped out and we have
1208  * to call VOP_CLOSE() as appropriate before we can reclaim it.
1209  */
1210 void
1211 vclean_vxlocked(struct vnode *vp, int flags)
1212 {
1213         int active;
1214         int n;
1215         vm_object_t object;
1216         struct namecache *ncp;
1217
1218         /*
1219          * If the vnode has already been reclaimed we have nothing to do.
1220          */
1221         if (vp->v_flag & VRECLAIMED)
1222                 return;
1223
1224         /*
1225          * Set flag to interlock operation, flag finalization to ensure
1226          * that the vnode winds up on the inactive list, and set v_act to 0.
1227          */
1228         vsetflags(vp, VRECLAIMED);
1229         atomic_set_int(&vp->v_refcnt, VREF_FINALIZE);
1230         vp->v_act = 0;
1231
1232         if (verbose_reclaims) {
1233                 if ((ncp = TAILQ_FIRST(&vp->v_namecache)) != NULL)
1234                         kprintf("Debug: reclaim %p %s\n", vp, ncp->nc_name);
1235         }
1236
1237         /*
1238          * Scrap the vfs cache
1239          */
1240         while (cache_inval_vp(vp, 0) != 0) {
1241                 kprintf("Warning: vnode %p clean/cache_resolution "
1242                         "race detected\n", vp);
1243                 tsleep(vp, 0, "vclninv", 2);
1244         }
1245
1246         /*
1247          * Check to see if the vnode is in use. If so we have to reference it
1248          * before we clean it out so that its count cannot fall to zero and
1249          * generate a race against ourselves to recycle it.
1250          */
1251         active = (VREFCNT(vp) > 0);
1252
1253         /*
1254          * Clean out any buffers associated with the vnode and destroy its
1255          * object, if it has one. 
1256          */
1257         vinvalbuf(vp, V_SAVE, 0, 0);
1258         KKASSERT(lockcountnb(&vp->v_lock) == 1);
1259
1260         /*
1261          * If purging an active vnode (typically during a forced unmount
1262          * or reboot), it must be closed and deactivated before being
1263          * reclaimed.  This isn't really all that safe, but what can
1264          * we do? XXX.
1265          *
1266          * Note that neither of these routines unlocks the vnode.
1267          */
1268         if (active && (flags & DOCLOSE)) {
1269                 while ((n = vp->v_opencount) != 0) {
1270                         if (vp->v_writecount)
1271                                 VOP_CLOSE(vp, FWRITE|FNONBLOCK, NULL);
1272                         else
1273                                 VOP_CLOSE(vp, FNONBLOCK, NULL);
1274                         if (vp->v_opencount == n) {
1275                                 kprintf("Warning: unable to force-close"
1276                                        " vnode %p\n", vp);
1277                                 break;
1278                         }
1279                 }
1280         }
1281
1282         /*
1283          * If the vnode has not been deactivated, deactivated it.  Deactivation
1284          * can create new buffers and VM pages so we have to call vinvalbuf()
1285          * again to make sure they all get flushed.
1286          *
1287          * This can occur if a file with a link count of 0 needs to be
1288          * truncated.
1289          *
1290          * If the vnode is already dead don't try to deactivate it.
1291          */
1292         if ((vp->v_flag & VINACTIVE) == 0) {
1293                 vsetflags(vp, VINACTIVE);
1294                 if (vp->v_mount)
1295                         VOP_INACTIVE(vp);
1296                 vinvalbuf(vp, V_SAVE, 0, 0);
1297         }
1298         KKASSERT(lockcountnb(&vp->v_lock) == 1);
1299
1300         /*
1301          * If the vnode has an object, destroy it.
1302          */
1303         while ((object = vp->v_object) != NULL) {
1304                 vm_object_hold(object);
1305                 if (object == vp->v_object)
1306                         break;
1307                 vm_object_drop(object);
1308         }
1309
1310         if (object != NULL) {
1311                 if (object->ref_count == 0) {
1312                         if ((object->flags & OBJ_DEAD) == 0)
1313                                 vm_object_terminate(object);
1314                         vm_object_drop(object);
1315                         vclrflags(vp, VOBJBUF);
1316                 } else {
1317                         vm_pager_deallocate(object);
1318                         vclrflags(vp, VOBJBUF);
1319                         vm_object_drop(object);
1320                 }
1321         }
1322         KKASSERT((vp->v_flag & VOBJBUF) == 0);
1323
1324         /*
1325          * Reclaim the vnode if not already dead.
1326          */
1327         if (vp->v_mount && VOP_RECLAIM(vp))
1328                 panic("vclean: cannot reclaim");
1329
1330         /*
1331          * Done with purge, notify sleepers of the grim news.
1332          */
1333         vp->v_ops = &dead_vnode_vops_p;
1334         vn_gone(vp);
1335         vp->v_tag = VT_NON;
1336
1337         /*
1338          * If we are destroying an active vnode, reactivate it now that
1339          * we have reassociated it with deadfs.  This prevents the system
1340          * from crashing on the vnode due to it being unexpectedly marked
1341          * as inactive or reclaimed.
1342          */
1343         if (active && (flags & DOCLOSE)) {
1344                 vclrflags(vp, VINACTIVE | VRECLAIMED);
1345         }
1346 }
1347
1348 /*
1349  * Eliminate all activity associated with the requested vnode
1350  * and with all vnodes aliased to the requested vnode.
1351  *
1352  * The vnode must be referenced but should not be locked.
1353  */
1354 int
1355 vrevoke(struct vnode *vp, struct ucred *cred)
1356 {
1357         struct vnode *vq;
1358         struct vnode *vqn;
1359         cdev_t dev;
1360         int error;
1361
1362         /*
1363          * If the vnode has a device association, scrap all vnodes associated
1364          * with the device.  Don't let the device disappear on us while we
1365          * are scrapping the vnodes.
1366          *
1367          * The passed vp will probably show up in the list, do not VX lock
1368          * it twice!
1369          *
1370          * Releasing the vnode's rdev here can mess up specfs's call to
1371          * device close, so don't do it.  The vnode has been disassociated
1372          * and the device will be closed after the last ref on the related
1373          * fp goes away (if not still open by e.g. the kernel).
1374          */
1375         if (vp->v_type != VCHR) {
1376                 error = fdrevoke(vp, DTYPE_VNODE, cred);
1377                 return (error);
1378         }
1379         if ((dev = vp->v_rdev) == NULL) {
1380                 return(0);
1381         }
1382         reference_dev(dev);
1383         lwkt_gettoken(&spechash_token);
1384
1385 restart:
1386         vqn = SLIST_FIRST(&dev->si_hlist);
1387         if (vqn)
1388                 vhold(vqn);
1389         while ((vq = vqn) != NULL) {
1390                 if (VREFCNT(vq) > 0) {
1391                         vref(vq);
1392                         fdrevoke(vq, DTYPE_VNODE, cred);
1393                         /*v_release_rdev(vq);*/
1394                         vrele(vq);
1395                         if (vq->v_rdev != dev) {
1396                                 vdrop(vq);
1397                                 goto restart;
1398                         }
1399                 }
1400                 vqn = SLIST_NEXT(vq, v_cdevnext);
1401                 if (vqn)
1402                         vhold(vqn);
1403                 vdrop(vq);
1404         }
1405         lwkt_reltoken(&spechash_token);
1406         dev_drevoke(dev);
1407         release_dev(dev);
1408         return (0);
1409 }
1410
1411 /*
1412  * This is called when the object underlying a vnode is being destroyed,
1413  * such as in a remove().  Try to recycle the vnode immediately if the
1414  * only active reference is our reference.
1415  *
1416  * Directory vnodes in the namecache with children cannot be immediately
1417  * recycled because numerous VOP_N*() ops require them to be stable.
1418  *
1419  * To avoid recursive recycling from VOP_INACTIVE implemenetations this
1420  * function is a NOP if VRECLAIMED is already set.
1421  */
1422 int
1423 vrecycle(struct vnode *vp)
1424 {
1425         if (VREFCNT(vp) <= 1 && (vp->v_flag & VRECLAIMED) == 0) {
1426                 if (cache_inval_vp_nonblock(vp))
1427                         return(0);
1428                 vgone_vxlocked(vp);
1429                 return (1);
1430         }
1431         return (0);
1432 }
1433
1434 /*
1435  * Return the maximum I/O size allowed for strategy calls on VP.
1436  *
1437  * If vp is VCHR or VBLK we dive the device, otherwise we use
1438  * the vp's mount info.
1439  *
1440  * The returned value is clamped at MAXPHYS as most callers cannot use
1441  * buffers larger than that size.
1442  */
1443 int
1444 vmaxiosize(struct vnode *vp)
1445 {
1446         int maxiosize;
1447
1448         if (vp->v_type == VBLK || vp->v_type == VCHR)
1449                 maxiosize = vp->v_rdev->si_iosize_max;
1450         else
1451                 maxiosize = vp->v_mount->mnt_iosize_max;
1452
1453         if (maxiosize > MAXPHYS)
1454                 maxiosize = MAXPHYS;
1455         return (maxiosize);
1456 }
1457
1458 /*
1459  * Eliminate all activity associated with a vnode in preparation for
1460  * destruction.
1461  *
1462  * The vnode must be VX locked and refd and will remain VX locked and refd
1463  * on return.  This routine may be called with the vnode in any state, as
1464  * long as it is VX locked.  The vnode will be cleaned out and marked
1465  * VRECLAIMED but will not actually be reused until all existing refs and
1466  * holds go away.
1467  *
1468  * NOTE: This routine may be called on a vnode which has not yet been
1469  * already been deactivated (VOP_INACTIVE), or on a vnode which has
1470  * already been reclaimed.
1471  *
1472  * This routine is not responsible for placing us back on the freelist. 
1473  * Instead, it happens automatically when the caller releases the VX lock
1474  * (assuming there aren't any other references).
1475  */
1476 void
1477 vgone_vxlocked(struct vnode *vp)
1478 {
1479         /*
1480          * assert that the VX lock is held.  This is an absolute requirement
1481          * now for vgone_vxlocked() to be called.
1482          */
1483         KKASSERT(lockcountnb(&vp->v_lock) == 1);
1484
1485         /*
1486          * Clean out the filesystem specific data and set the VRECLAIMED
1487          * bit.  Also deactivate the vnode if necessary. 
1488          *
1489          * The vnode should have automatically been removed from the syncer
1490          * list as syncer/dirty flags cleared during the cleaning.
1491          */
1492         vclean_vxlocked(vp, DOCLOSE);
1493
1494         /*
1495          * Normally panic if the vnode is still dirty, unless we are doing
1496          * a forced unmount (tmpfs typically).
1497          */
1498         if (vp->v_flag & VONWORKLST) {
1499                 if (vp->v_mount->mnt_kern_flag & MNTK_UNMOUNTF) {
1500                         /* force removal */
1501                         vn_syncer_remove(vp, 1);
1502                 } else {
1503                         panic("vp %p still dirty in vgone after flush", vp);
1504                 }
1505         }
1506
1507         /*
1508          * Delete from old mount point vnode list, if on one.
1509          */
1510         if (vp->v_mount != NULL) {
1511                 KKASSERT(vp->v_data == NULL);
1512                 insmntque(vp, NULL);
1513         }
1514
1515         /*
1516          * If special device, remove it from special device alias list
1517          * if it is on one.  This should normally only occur if a vnode is
1518          * being revoked as the device should otherwise have been released
1519          * naturally.
1520          */
1521         if ((vp->v_type == VBLK || vp->v_type == VCHR) && vp->v_rdev != NULL) {
1522                 v_release_rdev(vp);
1523         }
1524
1525         /*
1526          * Set us to VBAD
1527          */
1528         vp->v_type = VBAD;
1529 }
1530
1531 /*
1532  * Lookup a vnode by device number.
1533  *
1534  * Returns non-zero and *vpp set to a vref'd vnode on success.
1535  * Returns zero on failure.
1536  */
1537 int
1538 vfinddev(cdev_t dev, enum vtype type, struct vnode **vpp)
1539 {
1540         struct vnode *vp;
1541
1542         lwkt_gettoken(&spechash_token);
1543         SLIST_FOREACH(vp, &dev->si_hlist, v_cdevnext) {
1544                 if (type == vp->v_type) {
1545                         *vpp = vp;
1546                         vref(vp);
1547                         lwkt_reltoken(&spechash_token);
1548                         return (1);
1549                 }
1550         }
1551         lwkt_reltoken(&spechash_token);
1552         return (0);
1553 }
1554
1555 /*
1556  * Calculate the total number of references to a special device.  This
1557  * routine may only be called for VBLK and VCHR vnodes since v_rdev is
1558  * an overloaded field.  Since udev2dev can now return NULL, we have
1559  * to check for a NULL v_rdev.
1560  */
1561 int
1562 count_dev(cdev_t dev)
1563 {
1564         struct vnode *vp;
1565         int count = 0;
1566
1567         if (SLIST_FIRST(&dev->si_hlist)) {
1568                 lwkt_gettoken(&spechash_token);
1569                 SLIST_FOREACH(vp, &dev->si_hlist, v_cdevnext) {
1570                         count += vp->v_opencount;
1571                 }
1572                 lwkt_reltoken(&spechash_token);
1573         }
1574         return(count);
1575 }
1576
1577 int
1578 vcount(struct vnode *vp)
1579 {
1580         if (vp->v_rdev == NULL)
1581                 return(0);
1582         return(count_dev(vp->v_rdev));
1583 }
1584
1585 /*
1586  * Initialize VMIO for a vnode.  This routine MUST be called before a
1587  * VFS can issue buffer cache ops on a vnode.  It is typically called
1588  * when a vnode is initialized from its inode.
1589  */
1590 int
1591 vinitvmio(struct vnode *vp, off_t filesize, int blksize, int boff)
1592 {
1593         vm_object_t object;
1594         int error = 0;
1595
1596         object = vp->v_object;
1597         if (object) {
1598                 vm_object_hold(object);
1599                 KKASSERT(vp->v_object == object);
1600         }
1601
1602         if (object == NULL) {
1603                 object = vnode_pager_alloc(vp, filesize, 0, 0, blksize, boff);
1604
1605                 /*
1606                  * Dereference the reference we just created.  This assumes
1607                  * that the object is associated with the vp.  Allow it to
1608                  * have zero refs.  It cannot be destroyed as long as it
1609                  * is associated with the vnode.
1610                  */
1611                 vm_object_hold(object);
1612                 atomic_add_int(&object->ref_count, -1);
1613                 vrele(vp);
1614         } else {
1615                 KKASSERT((object->flags & OBJ_DEAD) == 0);
1616         }
1617         KASSERT(vp->v_object != NULL, ("vinitvmio: NULL object"));
1618         vsetflags(vp, VOBJBUF);
1619         vm_object_drop(object);
1620
1621         return (error);
1622 }
1623
1624
1625 /*
1626  * Print out a description of a vnode.
1627  */
1628 static char *typename[] =
1629 {"VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD"};
1630
1631 void
1632 vprint(char *label, struct vnode *vp)
1633 {
1634         char buf[96];
1635
1636         if (label != NULL)
1637                 kprintf("%s: %p: ", label, (void *)vp);
1638         else
1639                 kprintf("%p: ", (void *)vp);
1640         kprintf("type %s, refcnt %08x, writecount %d, holdcnt %d,",
1641                 typename[vp->v_type],
1642                 vp->v_refcnt, vp->v_writecount, vp->v_auxrefs);
1643         buf[0] = '\0';
1644         if (vp->v_flag & VROOT)
1645                 strcat(buf, "|VROOT");
1646         if (vp->v_flag & VPFSROOT)
1647                 strcat(buf, "|VPFSROOT");
1648         if (vp->v_flag & VTEXT)
1649                 strcat(buf, "|VTEXT");
1650         if (vp->v_flag & VSYSTEM)
1651                 strcat(buf, "|VSYSTEM");
1652         if (vp->v_flag & VOBJBUF)
1653                 strcat(buf, "|VOBJBUF");
1654         if (buf[0] != '\0')
1655                 kprintf(" flags (%s)", &buf[1]);
1656         if (vp->v_data == NULL) {
1657                 kprintf("\n");
1658         } else {
1659                 kprintf("\n\t");
1660                 VOP_PRINT(vp);
1661         }
1662 }
1663
1664 /*
1665  * Do the usual access checking.
1666  * file_mode, uid and gid are from the vnode in question,
1667  * while acc_mode and cred are from the VOP_ACCESS parameter list
1668  */
1669 int
1670 vaccess(enum vtype type, mode_t file_mode, uid_t uid, gid_t gid,
1671     mode_t acc_mode, struct ucred *cred)
1672 {
1673         mode_t mask;
1674         int ismember;
1675
1676         /*
1677          * Super-user always gets read/write access, but execute access depends
1678          * on at least one execute bit being set.
1679          */
1680         if (priv_check_cred(cred, PRIV_ROOT, 0) == 0) {
1681                 if ((acc_mode & VEXEC) && type != VDIR &&
1682                     (file_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0)
1683                         return (EACCES);
1684                 return (0);
1685         }
1686
1687         mask = 0;
1688
1689         /* Otherwise, check the owner. */
1690         if (cred->cr_uid == uid) {
1691                 if (acc_mode & VEXEC)
1692                         mask |= S_IXUSR;
1693                 if (acc_mode & VREAD)
1694                         mask |= S_IRUSR;
1695                 if (acc_mode & VWRITE)
1696                         mask |= S_IWUSR;
1697                 return ((file_mode & mask) == mask ? 0 : EACCES);
1698         }
1699
1700         /* Otherwise, check the groups. */
1701         ismember = groupmember(gid, cred);
1702         if (cred->cr_svgid == gid || ismember) {
1703                 if (acc_mode & VEXEC)
1704                         mask |= S_IXGRP;
1705                 if (acc_mode & VREAD)
1706                         mask |= S_IRGRP;
1707                 if (acc_mode & VWRITE)
1708                         mask |= S_IWGRP;
1709                 return ((file_mode & mask) == mask ? 0 : EACCES);
1710         }
1711
1712         /* Otherwise, check everyone else. */
1713         if (acc_mode & VEXEC)
1714                 mask |= S_IXOTH;
1715         if (acc_mode & VREAD)
1716                 mask |= S_IROTH;
1717         if (acc_mode & VWRITE)
1718                 mask |= S_IWOTH;
1719         return ((file_mode & mask) == mask ? 0 : EACCES);
1720 }
1721
1722 #ifdef DDB
1723 #include <ddb/ddb.h>
1724
1725 static int db_show_locked_vnodes(struct mount *mp, void *data);
1726
1727 /*
1728  * List all of the locked vnodes in the system.
1729  * Called when debugging the kernel.
1730  */
1731 DB_SHOW_COMMAND(lockedvnodes, lockedvnodes)
1732 {
1733         kprintf("Locked vnodes\n");
1734         mountlist_scan(db_show_locked_vnodes, NULL, 
1735                         MNTSCAN_FORWARD|MNTSCAN_NOBUSY);
1736 }
1737
1738 static int
1739 db_show_locked_vnodes(struct mount *mp, void *data __unused)
1740 {
1741         struct vnode *vp;
1742
1743         TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
1744                 if (vn_islocked(vp))
1745                         vprint(NULL, vp);
1746         }
1747         return(0);
1748 }
1749 #endif
1750
1751 /*
1752  * Top level filesystem related information gathering.
1753  */
1754 static int      sysctl_ovfs_conf (SYSCTL_HANDLER_ARGS);
1755
1756 static int
1757 vfs_sysctl(SYSCTL_HANDLER_ARGS)
1758 {
1759         int *name = (int *)arg1 - 1;    /* XXX */
1760         u_int namelen = arg2 + 1;       /* XXX */
1761         struct vfsconf *vfsp;
1762         int maxtypenum;
1763
1764 #if 1 || defined(COMPAT_PRELITE2)
1765         /* Resolve ambiguity between VFS_VFSCONF and VFS_GENERIC. */
1766         if (namelen == 1)
1767                 return (sysctl_ovfs_conf(oidp, arg1, arg2, req));
1768 #endif
1769
1770 #ifdef notyet
1771         /* all sysctl names at this level are at least name and field */
1772         if (namelen < 2)
1773                 return (ENOTDIR);               /* overloaded */
1774         if (name[0] != VFS_GENERIC) {
1775                 vfsp = vfsconf_find_by_typenum(name[0]);
1776                 if (vfsp == NULL)
1777                         return (EOPNOTSUPP);
1778                 return ((*vfsp->vfc_vfsops->vfs_sysctl)(&name[1], namelen - 1,
1779                     oldp, oldlenp, newp, newlen, p));
1780         }
1781 #endif
1782         switch (name[1]) {
1783         case VFS_MAXTYPENUM:
1784                 if (namelen != 2)
1785                         return (ENOTDIR);
1786                 maxtypenum = vfsconf_get_maxtypenum();
1787                 return (SYSCTL_OUT(req, &maxtypenum, sizeof(maxtypenum)));
1788         case VFS_CONF:
1789                 if (namelen != 3)
1790                         return (ENOTDIR);       /* overloaded */
1791                 vfsp = vfsconf_find_by_typenum(name[2]);
1792                 if (vfsp == NULL)
1793                         return (EOPNOTSUPP);
1794                 return (SYSCTL_OUT(req, vfsp, sizeof *vfsp));
1795         }
1796         return (EOPNOTSUPP);
1797 }
1798
1799 SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RD, vfs_sysctl,
1800         "Generic filesystem");
1801
1802 #if 1 || defined(COMPAT_PRELITE2)
1803
1804 static int
1805 sysctl_ovfs_conf_iter(struct vfsconf *vfsp, void *data)
1806 {
1807         int error;
1808         struct ovfsconf ovfs;
1809         struct sysctl_req *req = (struct sysctl_req*) data;
1810
1811         bzero(&ovfs, sizeof(ovfs));
1812         ovfs.vfc_vfsops = vfsp->vfc_vfsops;     /* XXX used as flag */
1813         strcpy(ovfs.vfc_name, vfsp->vfc_name);
1814         ovfs.vfc_index = vfsp->vfc_typenum;
1815         ovfs.vfc_refcount = vfsp->vfc_refcount;
1816         ovfs.vfc_flags = vfsp->vfc_flags;
1817         error = SYSCTL_OUT(req, &ovfs, sizeof ovfs);
1818         if (error)
1819                 return error; /* abort iteration with error code */
1820         else
1821                 return 0; /* continue iterating with next element */
1822 }
1823
1824 static int
1825 sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS)
1826 {
1827         return vfsconf_each(sysctl_ovfs_conf_iter, (void*)req);
1828 }
1829
1830 #endif /* 1 || COMPAT_PRELITE2 */
1831
1832 /*
1833  * Check to see if a filesystem is mounted on a block device.
1834  */
1835 int
1836 vfs_mountedon(struct vnode *vp)
1837 {
1838         cdev_t dev;
1839
1840         if ((dev = vp->v_rdev) == NULL) {
1841 /*              if (vp->v_type != VBLK)
1842                         dev = get_dev(vp->v_uminor, vp->v_umajor); */
1843         }
1844         if (dev != NULL && dev->si_mountpoint)
1845                 return (EBUSY);
1846         return (0);
1847 }
1848
1849 /*
1850  * Unmount all filesystems. The list is traversed in reverse order
1851  * of mounting to avoid dependencies.
1852  *
1853  * We want the umountall to be able to break out of its loop if a
1854  * failure occurs, after scanning all possible mounts, so the callback
1855  * returns 0 on error.
1856  *
1857  * NOTE: Do not call mountlist_remove(mp) on error any more, this will
1858  *       confuse mountlist_scan()'s unbusy check.
1859  */
1860 static int vfs_umountall_callback(struct mount *mp, void *data);
1861
1862 void
1863 vfs_unmountall(void)
1864 {
1865         int count;
1866
1867         do {
1868                 count = mountlist_scan(vfs_umountall_callback, 
1869                                         NULL, MNTSCAN_REVERSE|MNTSCAN_NOBUSY);
1870         } while (count);
1871 }
1872
1873 static
1874 int
1875 vfs_umountall_callback(struct mount *mp, void *data)
1876 {
1877         int error;
1878
1879         error = dounmount(mp, MNT_FORCE);
1880         if (error) {
1881                 kprintf("unmount of filesystem mounted from %s failed (", 
1882                         mp->mnt_stat.f_mntfromname);
1883                 if (error == EBUSY)
1884                         kprintf("BUSY)\n");
1885                 else
1886                         kprintf("%d)\n", error);
1887                 return 0;
1888         } else {
1889                 return 1;
1890         }
1891 }
1892
1893 /*
1894  * Checks the mount flags for parameter mp and put the names comma-separated
1895  * into a string buffer buf with a size limit specified by len.
1896  *
1897  * It returns the number of bytes written into buf, and (*errorp) will be
1898  * set to 0, EINVAL (if passed length is 0), or ENOSPC (supplied buffer was
1899  * not large enough).  The buffer will be 0-terminated if len was not 0.
1900  */
1901 size_t
1902 vfs_flagstostr(int flags, const struct mountctl_opt *optp,
1903                char *buf, size_t len, int *errorp)
1904 {
1905         static const struct mountctl_opt optnames[] = {
1906                 { MNT_RDONLY,           "read-only" },
1907                 { MNT_SYNCHRONOUS,      "synchronous" },
1908                 { MNT_NOEXEC,           "noexec" },
1909                 { MNT_NOSUID,           "nosuid" },
1910                 { MNT_NODEV,            "nodev" },
1911                 { MNT_AUTOMOUNTED,      "automounted" },
1912                 { MNT_ASYNC,            "asynchronous" },
1913                 { MNT_SUIDDIR,          "suiddir" },
1914                 { MNT_SOFTDEP,          "soft-updates" },
1915                 { MNT_NOSYMFOLLOW,      "nosymfollow" },
1916                 { MNT_TRIM,             "trim" },
1917                 { MNT_NOATIME,          "noatime" },
1918                 { MNT_NOCLUSTERR,       "noclusterr" },
1919                 { MNT_NOCLUSTERW,       "noclusterw" },
1920                 { MNT_EXRDONLY,         "NFS read-only" },
1921                 { MNT_EXPORTED,         "NFS exported" },
1922                 /* Remaining NFS flags could come here */
1923                 { MNT_LOCAL,            "local" },
1924                 { MNT_QUOTA,            "with-quotas" },
1925                 /* { MNT_ROOTFS,           "rootfs" }, */
1926                 /* { MNT_IGNORE,           "ignore" }, */
1927                 { 0,                    NULL}
1928         };
1929         int bwritten;
1930         int bleft;
1931         int optlen;
1932         int actsize;
1933
1934         *errorp = 0;
1935         bwritten = 0;
1936         bleft = len - 1;        /* leave room for trailing \0 */
1937
1938         /*
1939          * Checks the size of the string. If it contains
1940          * any data, then we will append the new flags to
1941          * it.
1942          */
1943         actsize = strlen(buf);
1944         if (actsize > 0)
1945                 buf += actsize;
1946
1947         /* Default flags if no flags passed */
1948         if (optp == NULL)
1949                 optp = optnames;
1950
1951         if (bleft < 0) {        /* degenerate case, 0-length buffer */
1952                 *errorp = EINVAL;
1953                 return(0);
1954         }
1955
1956         for (; flags && optp->o_opt; ++optp) {
1957                 if ((flags & optp->o_opt) == 0)
1958                         continue;
1959                 optlen = strlen(optp->o_name);
1960                 if (bwritten || actsize > 0) {
1961                         if (bleft < 2) {
1962                                 *errorp = ENOSPC;
1963                                 break;
1964                         }
1965                         buf[bwritten++] = ',';
1966                         buf[bwritten++] = ' ';
1967                         bleft -= 2;
1968                 }
1969                 if (bleft < optlen) {
1970                         *errorp = ENOSPC;
1971                         break;
1972                 }
1973                 bcopy(optp->o_name, buf + bwritten, optlen);
1974                 bwritten += optlen;
1975                 bleft -= optlen;
1976                 flags &= ~optp->o_opt;
1977         }
1978
1979         /*
1980          * Space already reserved for trailing \0
1981          */
1982         buf[bwritten] = 0;
1983         return (bwritten);
1984 }
1985
1986 /*
1987  * Build hash lists of net addresses and hang them off the mount point.
1988  * Called by ufs_mount() to set up the lists of export addresses.
1989  */
1990 static int
1991 vfs_hang_addrlist(struct mount *mp, struct netexport *nep,
1992                 const struct export_args *argp)
1993 {
1994         struct netcred *np;
1995         struct radix_node_head *rnh;
1996         int i;
1997         struct radix_node *rn;
1998         struct sockaddr *saddr, *smask = NULL;
1999         int error;
2000
2001         if (argp->ex_addrlen == 0) {
2002                 if (mp->mnt_flag & MNT_DEFEXPORTED)
2003                         return (EPERM);
2004                 np = &nep->ne_defexported;
2005                 np->netc_exflags = argp->ex_flags;
2006                 np->netc_anon = argp->ex_anon;
2007                 np->netc_anon.cr_ref = 1;
2008                 mp->mnt_flag |= MNT_DEFEXPORTED;
2009                 return (0);
2010         }
2011
2012         if (argp->ex_addrlen < 0 || argp->ex_addrlen > MLEN)
2013                 return (EINVAL);
2014         if (argp->ex_masklen < 0 || argp->ex_masklen > MLEN)
2015                 return (EINVAL);
2016
2017         i = sizeof(struct netcred) + argp->ex_addrlen + argp->ex_masklen;
2018         np = (struct netcred *)kmalloc(i, M_NETCRED, M_WAITOK | M_ZERO);
2019         saddr = (struct sockaddr *) (np + 1);
2020         if ((error = copyin(argp->ex_addr, (caddr_t) saddr, argp->ex_addrlen)))
2021                 goto out;
2022         if (saddr->sa_len > argp->ex_addrlen)
2023                 saddr->sa_len = argp->ex_addrlen;
2024         if (argp->ex_masklen) {
2025                 smask = (struct sockaddr *)((caddr_t)saddr + argp->ex_addrlen);
2026                 error = copyin(argp->ex_mask, (caddr_t)smask, argp->ex_masklen);
2027                 if (error)
2028                         goto out;
2029                 if (smask->sa_len > argp->ex_masklen)
2030                         smask->sa_len = argp->ex_masklen;
2031         }
2032         NE_LOCK(nep);
2033         if (nep->ne_maskhead == NULL) {
2034                 if (!rn_inithead((void **)&nep->ne_maskhead, NULL, 0)) {
2035                         error = ENOBUFS;
2036                         goto out;
2037                 }
2038         }
2039         if ((rnh = vfs_create_addrlist_af(saddr->sa_family, nep)) == NULL) {
2040                 error = ENOBUFS;
2041                 goto out;
2042         }
2043         rn = (*rnh->rnh_addaddr)((char *)saddr, (char *)smask, rnh,
2044                                  np->netc_rnodes);
2045         NE_UNLOCK(nep);
2046         if (rn == NULL || np != (struct netcred *)rn) { /* already exists */
2047                 error = EPERM;
2048                 goto out;
2049         }
2050         np->netc_exflags = argp->ex_flags;
2051         np->netc_anon = argp->ex_anon;
2052         np->netc_anon.cr_ref = 1;
2053         return (0);
2054
2055 out:
2056         kfree(np, M_NETCRED);
2057         return (error);
2058 }
2059
2060 /*
2061  * Free netcred structures installed in the netexport
2062  */
2063 static int
2064 vfs_free_netcred(struct radix_node *rn, void *w)
2065 {
2066         struct radix_node_head *rnh = (struct radix_node_head *)w;
2067
2068         (*rnh->rnh_deladdr) (rn->rn_key, rn->rn_mask, rnh);
2069         kfree(rn, M_NETCRED);
2070
2071         return (0);
2072 }
2073
2074 /*
2075  * callback to free an element of the mask table installed in the
2076  * netexport.  These may be created indirectly and are not netcred
2077  * structures.
2078  */
2079 static int
2080 vfs_free_netcred_mask(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_RTABLE);
2086
2087         return (0);
2088 }
2089
2090 static struct radix_node_head *
2091 vfs_create_addrlist_af(int af, struct netexport *nep)
2092 {
2093         struct radix_node_head *rnh = NULL;
2094 #if defined(INET) || defined(INET6)
2095         struct radix_node_head *maskhead = nep->ne_maskhead;
2096         int off;
2097 #endif
2098
2099         NE_ASSERT_LOCKED(nep);
2100         KKASSERT(maskhead != NULL);
2101         switch (af) {
2102 #ifdef INET
2103         case AF_INET:
2104                 if ((rnh = nep->ne_inethead) == NULL) {
2105                         off = offsetof(struct sockaddr_in, sin_addr) << 3;
2106                         if (!rn_inithead((void **)&rnh, maskhead, off))
2107                                 return (NULL);
2108                         nep->ne_inethead = rnh;
2109                 }
2110                 break;
2111 #endif
2112 #ifdef INET6
2113         case AF_INET6:
2114                 if ((rnh = nep->ne_inet6head) == NULL) {
2115                         off = offsetof(struct sockaddr_in6, sin6_addr) << 3;
2116                         if (!rn_inithead((void **)&rnh, maskhead, off))
2117                                 return (NULL);
2118                         nep->ne_inet6head = rnh;
2119                 }
2120                 break;
2121 #endif
2122         }
2123         return (rnh);
2124 }
2125
2126 /*
2127  * helper function for freeing netcred elements
2128  */
2129 static void
2130 vfs_free_addrlist_af(struct radix_node_head **prnh)
2131 {
2132         struct radix_node_head *rnh = *prnh;
2133
2134         (*rnh->rnh_walktree) (rnh, vfs_free_netcred, rnh);
2135         kfree(rnh, M_RTABLE);
2136         *prnh = NULL;
2137 }
2138
2139 /*
2140  * helper function for freeing mask elements
2141  */
2142 static void
2143 vfs_free_addrlist_masks(struct radix_node_head **prnh)
2144 {
2145         struct radix_node_head *rnh = *prnh;
2146
2147         (*rnh->rnh_walktree) (rnh, vfs_free_netcred_mask, rnh);
2148         kfree(rnh, M_RTABLE);
2149         *prnh = NULL;
2150 }
2151
2152 /*
2153  * Free the net address hash lists that are hanging off the mount points.
2154  */
2155 static void
2156 vfs_free_addrlist(struct netexport *nep)
2157 {
2158         NE_LOCK(nep);
2159         if (nep->ne_inethead != NULL)
2160                 vfs_free_addrlist_af(&nep->ne_inethead);
2161         if (nep->ne_inet6head != NULL)
2162                 vfs_free_addrlist_af(&nep->ne_inet6head);
2163         if (nep->ne_maskhead)
2164                 vfs_free_addrlist_masks(&nep->ne_maskhead);
2165         NE_UNLOCK(nep);
2166 }
2167
2168 int
2169 vfs_export(struct mount *mp, struct netexport *nep,
2170            const struct export_args *argp)
2171 {
2172         int error;
2173
2174         if (argp->ex_flags & MNT_DELEXPORT) {
2175                 if (mp->mnt_flag & MNT_EXPUBLIC) {
2176                         vfs_setpublicfs(NULL, NULL, NULL);
2177                         mp->mnt_flag &= ~MNT_EXPUBLIC;
2178                 }
2179                 vfs_free_addrlist(nep);
2180                 mp->mnt_flag &= ~(MNT_EXPORTED | MNT_DEFEXPORTED);
2181         }
2182         if (argp->ex_flags & MNT_EXPORTED) {
2183                 if (argp->ex_flags & MNT_EXPUBLIC) {
2184                         if ((error = vfs_setpublicfs(mp, nep, argp)) != 0)
2185                                 return (error);
2186                         mp->mnt_flag |= MNT_EXPUBLIC;
2187                 }
2188                 if ((error = vfs_hang_addrlist(mp, nep, argp)))
2189                         return (error);
2190                 mp->mnt_flag |= MNT_EXPORTED;
2191         }
2192         return (0);
2193 }
2194
2195
2196 /*
2197  * Set the publicly exported filesystem (WebNFS). Currently, only
2198  * one public filesystem is possible in the spec (RFC 2054 and 2055)
2199  */
2200 int
2201 vfs_setpublicfs(struct mount *mp, struct netexport *nep,
2202                 const struct export_args *argp)
2203 {
2204         int error;
2205         struct vnode *rvp;
2206         char *cp;
2207
2208         /*
2209          * mp == NULL -> invalidate the current info, the FS is
2210          * no longer exported. May be called from either vfs_export
2211          * or unmount, so check if it hasn't already been done.
2212          */
2213         if (mp == NULL) {
2214                 if (nfs_pub.np_valid) {
2215                         nfs_pub.np_valid = 0;
2216                         if (nfs_pub.np_index != NULL) {
2217                                 kfree(nfs_pub.np_index, M_TEMP);
2218                                 nfs_pub.np_index = NULL;
2219                         }
2220                 }
2221                 return (0);
2222         }
2223
2224         /*
2225          * Only one allowed at a time.
2226          */
2227         if (nfs_pub.np_valid != 0 && mp != nfs_pub.np_mount)
2228                 return (EBUSY);
2229
2230         /*
2231          * Get real filehandle for root of exported FS.
2232          */
2233         bzero((caddr_t)&nfs_pub.np_handle, sizeof(nfs_pub.np_handle));
2234         nfs_pub.np_handle.fh_fsid = mp->mnt_stat.f_fsid;
2235
2236         if ((error = VFS_ROOT(mp, &rvp)))
2237                 return (error);
2238
2239         if ((error = VFS_VPTOFH(rvp, &nfs_pub.np_handle.fh_fid)))
2240                 return (error);
2241
2242         vput(rvp);
2243
2244         /*
2245          * If an indexfile was specified, pull it in.
2246          */
2247         if (argp->ex_indexfile != NULL) {
2248                 int namelen;
2249
2250                 error = vn_get_namelen(rvp, &namelen);
2251                 if (error)
2252                         return (error);
2253                 nfs_pub.np_index = kmalloc(namelen, M_TEMP, M_WAITOK);
2254                 error = copyinstr(argp->ex_indexfile, nfs_pub.np_index,
2255                     namelen, NULL);
2256                 if (!error) {
2257                         /*
2258                          * Check for illegal filenames.
2259                          */
2260                         for (cp = nfs_pub.np_index; *cp; cp++) {
2261                                 if (*cp == '/') {
2262                                         error = EINVAL;
2263                                         break;
2264                                 }
2265                         }
2266                 }
2267                 if (error) {
2268                         kfree(nfs_pub.np_index, M_TEMP);
2269                         return (error);
2270                 }
2271         }
2272
2273         nfs_pub.np_mount = mp;
2274         nfs_pub.np_valid = 1;
2275         return (0);
2276 }
2277
2278 struct netcred *
2279 vfs_export_lookup(struct mount *mp, struct netexport *nep,
2280                 struct sockaddr *nam)
2281 {
2282         struct netcred *np;
2283         struct radix_node_head *rnh;
2284         struct sockaddr *saddr;
2285
2286         np = NULL;
2287         if (mp->mnt_flag & MNT_EXPORTED) {
2288                 /*
2289                  * Lookup in the export list first.
2290                  */
2291                 NE_LOCK(nep);
2292                 if (nam != NULL) {
2293                         saddr = nam;
2294                         switch (saddr->sa_family) {
2295 #ifdef INET
2296                         case AF_INET:
2297                                 rnh = nep->ne_inethead;
2298                                 break;
2299 #endif
2300 #ifdef INET6
2301                         case AF_INET6:
2302                                 rnh = nep->ne_inet6head;
2303                                 break;
2304 #endif
2305                         default:
2306                                 rnh = NULL;
2307                         }
2308                         if (rnh != NULL) {
2309                                 np = (struct netcred *)
2310                                         (*rnh->rnh_matchaddr)((char *)saddr,
2311                                                               rnh);
2312                                 if (np && np->netc_rnodes->rn_flags & RNF_ROOT)
2313                                         np = NULL;
2314                         }
2315                 }
2316                 NE_UNLOCK(nep);
2317                 /*
2318                  * If no address match, use the default if it exists.
2319                  */
2320                 if (np == NULL && mp->mnt_flag & MNT_DEFEXPORTED)
2321                         np = &nep->ne_defexported;
2322         }
2323         return (np);
2324 }
2325
2326 /*
2327  * perform msync on all vnodes under a mount point.  The mount point must
2328  * be locked.  This code is also responsible for lazy-freeing unreferenced
2329  * vnodes whos VM objects no longer contain pages.
2330  *
2331  * NOTE: MNT_WAIT still skips vnodes in the VXLOCK state.
2332  *
2333  * NOTE: XXX VOP_PUTPAGES and friends requires that the vnode be locked,
2334  * but vnode_pager_putpages() doesn't lock the vnode.  We have to do it
2335  * way up in this high level function.
2336  */
2337 static int vfs_msync_scan1(struct mount *mp, struct vnode *vp, void *data);
2338 static int vfs_msync_scan2(struct mount *mp, struct vnode *vp, void *data);
2339
2340 void
2341 vfs_msync(struct mount *mp, int flags) 
2342 {
2343         int vmsc_flags;
2344
2345         /*
2346          * tmpfs sets this flag to prevent msync(), sync, and the
2347          * filesystem periodic syncer from trying to flush VM pages
2348          * to swap.  Only pure memory pressure flushes tmpfs VM pages
2349          * to swap.
2350          */
2351         if (mp->mnt_kern_flag & MNTK_NOMSYNC)
2352                 return;
2353
2354         /*
2355          * Ok, scan the vnodes for work.  If the filesystem is using the
2356          * syncer thread feature we can use vsyncscan() instead of
2357          * vmntvnodescan(), which is much faster.
2358          */
2359         vmsc_flags = VMSC_GETVP;
2360         if (flags != MNT_WAIT)
2361                 vmsc_flags |= VMSC_NOWAIT;
2362
2363         if (mp->mnt_kern_flag & MNTK_THR_SYNC) {
2364                 vsyncscan(mp, vmsc_flags, vfs_msync_scan2,
2365                           (void *)(intptr_t)flags);
2366         } else {
2367                 vmntvnodescan(mp, vmsc_flags,
2368                               vfs_msync_scan1, vfs_msync_scan2,
2369                               (void *)(intptr_t)flags);
2370         }
2371 }
2372
2373 /*
2374  * scan1 is a fast pre-check.  There could be hundreds of thousands of
2375  * vnodes, we cannot afford to do anything heavy weight until we have a
2376  * fairly good indication that there is work to do.
2377  */
2378 static
2379 int
2380 vfs_msync_scan1(struct mount *mp, struct vnode *vp, void *data)
2381 {
2382         int flags = (int)(intptr_t)data;
2383
2384         if ((vp->v_flag & VRECLAIMED) == 0) {
2385                 if (vp->v_auxrefs == 0 && VREFCNT(vp) <= 0 &&
2386                     vp->v_object) {
2387                         return(0);      /* call scan2 */
2388                 }
2389                 if ((mp->mnt_flag & MNT_RDONLY) == 0 &&
2390                     (vp->v_flag & VOBJDIRTY) &&
2391                     (flags == MNT_WAIT || vn_islocked(vp) == 0)) {
2392                         return(0);      /* call scan2 */
2393                 }
2394         }
2395
2396         /*
2397          * do not call scan2, continue the loop
2398          */
2399         return(-1);
2400 }
2401
2402 /*
2403  * This callback is handed a locked vnode.
2404  */
2405 static
2406 int
2407 vfs_msync_scan2(struct mount *mp, struct vnode *vp, void *data)
2408 {
2409         vm_object_t obj;
2410         int flags = (int)(intptr_t)data;
2411
2412         if (vp->v_flag & VRECLAIMED)
2413                 return(0);
2414
2415         if ((mp->mnt_flag & MNT_RDONLY) == 0 && (vp->v_flag & VOBJDIRTY)) {
2416                 if ((obj = vp->v_object) != NULL) {
2417                         vm_object_page_clean(obj, 0, 0, 
2418                          flags == MNT_WAIT ? OBJPC_SYNC : OBJPC_NOSYNC);
2419                 }
2420         }
2421         return(0);
2422 }
2423
2424 /*
2425  * Wake up anyone interested in vp because it is being revoked.
2426  */
2427 void
2428 vn_gone(struct vnode *vp)
2429 {
2430         lwkt_gettoken(&vp->v_token);
2431         KNOTE(&vp->v_pollinfo.vpi_kqinfo.ki_note, NOTE_REVOKE);
2432         lwkt_reltoken(&vp->v_token);
2433 }
2434
2435 /*
2436  * extract the cdev_t from a VBLK or VCHR.  The vnode must have been opened
2437  * (or v_rdev might be NULL).
2438  */
2439 cdev_t
2440 vn_todev(struct vnode *vp)
2441 {
2442         if (vp->v_type != VBLK && vp->v_type != VCHR)
2443                 return (NULL);
2444         KKASSERT(vp->v_rdev != NULL);
2445         return (vp->v_rdev);
2446 }
2447
2448 /*
2449  * Check if vnode represents a disk device.  The vnode does not need to be
2450  * opened.
2451  *
2452  * MPALMOSTSAFE
2453  */
2454 int
2455 vn_isdisk(struct vnode *vp, int *errp)
2456 {
2457         cdev_t dev;
2458
2459         if (vp->v_type != VCHR) {
2460                 if (errp != NULL)
2461                         *errp = ENOTBLK;
2462                 return (0);
2463         }
2464
2465         dev = vp->v_rdev;
2466
2467         if (dev == NULL) {
2468                 if (errp != NULL)
2469                         *errp = ENXIO;
2470                 return (0);
2471         }
2472         if (dev_is_good(dev) == 0) {
2473                 if (errp != NULL)
2474                         *errp = ENXIO;
2475                 return (0);
2476         }
2477         if ((dev_dflags(dev) & D_DISK) == 0) {
2478                 if (errp != NULL)
2479                         *errp = ENOTBLK;
2480                 return (0);
2481         }
2482         if (errp != NULL)
2483                 *errp = 0;
2484         return (1);
2485 }
2486
2487 int
2488 vn_get_namelen(struct vnode *vp, int *namelen)
2489 {
2490         int error;
2491         register_t retval[2];
2492
2493         error = VOP_PATHCONF(vp, _PC_NAME_MAX, retval);
2494         if (error)
2495                 return (error);
2496         *namelen = (int)retval[0];
2497         return (0);
2498 }
2499
2500 int
2501 vop_write_dirent(int *error, struct uio *uio, ino_t d_ino, uint8_t d_type, 
2502                 uint16_t d_namlen, const char *d_name)
2503 {
2504         struct dirent *dp;
2505         size_t len;
2506
2507         len = _DIRENT_RECLEN(d_namlen);
2508         if (len > uio->uio_resid)
2509                 return(1);
2510
2511         dp = kmalloc(len, M_TEMP, M_WAITOK | M_ZERO);
2512
2513         dp->d_ino = d_ino;
2514         dp->d_namlen = d_namlen;
2515         dp->d_type = d_type;
2516         bcopy(d_name, dp->d_name, d_namlen);
2517
2518         *error = uiomove((caddr_t)dp, len, uio);
2519
2520         kfree(dp, M_TEMP);
2521
2522         return(0);
2523 }
2524
2525 void
2526 vn_mark_atime(struct vnode *vp, struct thread *td)
2527 {
2528         struct proc *p = td->td_proc;
2529         struct ucred *cred = p ? p->p_ucred : proc0.p_ucred;
2530
2531         if ((vp->v_mount->mnt_flag & (MNT_NOATIME | MNT_RDONLY)) == 0) {
2532                 VOP_MARKATIME(vp, cred);
2533         }
2534 }
2535
2536 /*
2537  * Calculate the number of entries in an inode-related chained hash table.
2538  * With today's memory sizes, maxvnodes can wind up being a very large
2539  * number.  There is no reason to waste memory, so tolerate some stacking.
2540  */
2541 int
2542 vfs_inodehashsize(void)
2543 {
2544         int hsize;
2545
2546         hsize = 32;
2547         while (hsize < maxvnodes)
2548                 hsize <<= 1;
2549         while (hsize > maxvnodes * 2)
2550                 hsize >>= 1;            /* nominal 2x stacking */
2551
2552         if (maxvnodes > 1024 * 1024)
2553                 hsize >>= 1;            /* nominal 8x stacking */
2554
2555         if (maxvnodes > 128 * 1024)
2556                 hsize >>= 1;            /* nominal 4x stacking */
2557
2558         if (hsize < 16)
2559                 hsize = 16;
2560
2561         return hsize;
2562 }