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.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
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.
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
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 $
39 * External virtual filesystem routines
43 #include "opt_inet6.h"
45 #include <sys/param.h>
46 #include <sys/systm.h>
50 #include <sys/dirent.h>
51 #include <sys/endian.h>
52 #include <sys/eventhandler.h>
53 #include <sys/fcntl.h>
55 #include <sys/kernel.h>
56 #include <sys/kthread.h>
57 #include <sys/malloc.h>
59 #include <sys/mount.h>
62 #include <sys/reboot.h>
63 #include <sys/socket.h>
65 #include <sys/sysctl.h>
66 #include <sys/syslog.h>
67 #include <sys/unistd.h>
68 #include <sys/vmmeter.h>
69 #include <sys/vnode.h>
71 #include <machine/limits.h>
74 #include <vm/vm_object.h>
75 #include <vm/vm_extern.h>
76 #include <vm/vm_kern.h>
78 #include <vm/vm_map.h>
79 #include <vm/vm_page.h>
80 #include <vm/vm_pager.h>
81 #include <vm/vnode_pager.h>
82 #include <vm/vm_zone.h>
85 #include <vm/vm_page2.h>
87 #include <netinet/in.h>
89 static MALLOC_DEFINE(M_NETCRED, "Export Host", "Export host address structure");
91 __read_mostly int numvnodes;
92 SYSCTL_INT(_debug, OID_AUTO, numvnodes, CTLFLAG_RD, &numvnodes, 0,
93 "Number of vnodes allocated");
94 __read_mostly int verbose_reclaims;
95 SYSCTL_INT(_debug, OID_AUTO, verbose_reclaims, CTLFLAG_RD, &verbose_reclaims, 0,
96 "Output filename of reclaimed vnode(s)");
98 __read_mostly enum vtype iftovt_tab[16] = {
99 VNON, VFIFO, VCHR, VNON, VDIR, VNON, VBLK, VNON,
100 VREG, VNON, VLNK, VNON, VSOCK, VNON, VNON, VBAD,
102 __read_mostly int vttoif_tab[9] = {
103 0, S_IFREG, S_IFDIR, S_IFBLK, S_IFCHR, S_IFLNK,
104 S_IFSOCK, S_IFIFO, S_IFMT,
107 static int reassignbufcalls;
108 SYSCTL_INT(_vfs, OID_AUTO, reassignbufcalls, CTLFLAG_RW, &reassignbufcalls,
109 0, "Number of times buffers have been reassigned to the proper list");
111 __read_mostly static int check_buf_overlap = 2; /* invasive check */
112 SYSCTL_INT(_vfs, OID_AUTO, check_buf_overlap, CTLFLAG_RW, &check_buf_overlap,
113 0, "Enable overlapping buffer checks");
115 int nfs_mount_type = -1;
116 static struct lwkt_token spechash_token;
117 struct nfs_public nfs_pub; /* publicly exported FS */
119 __read_mostly int maxvnodes;
120 SYSCTL_INT(_kern, KERN_MAXVNODES, maxvnodes, CTLFLAG_RW,
121 &maxvnodes, 0, "Maximum number of vnodes");
123 static struct radix_node_head *vfs_create_addrlist_af(int af,
124 struct netexport *nep);
125 static void vfs_free_addrlist (struct netexport *nep);
126 static int vfs_free_netcred (struct radix_node *rn, void *w);
127 static void vfs_free_addrlist_af (struct radix_node_head **prnh);
128 static int vfs_hang_addrlist (struct mount *mp, struct netexport *nep,
129 const struct export_args *argp);
130 static void vclean_vxlocked(struct vnode *vp, int flags);
132 __read_mostly int prtactive = 0; /* 1 => print out reclaim of active vnodes */
135 * Red black tree functions
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);
142 rb_buf_compare(struct buf *b1, struct buf *b2)
144 if (b1->b_loffset < b2->b_loffset)
146 if (b1->b_loffset > b2->b_loffset)
152 * Initialize the vnode management data structures.
154 * Called from vfsinit()
156 #define MAXVNBREAKMEM (1L * 1024 * 1024 * 1024)
157 #define MINVNODES 2000
158 #define MAXVNODES 4000000
163 int factor1; /* Limit based on ram (x 2 above 1GB) */
164 int factor2; /* Limit based on available KVM */
168 * Size maxvnodes to available memory. Size significantly
169 * smaller on low-memory systems (calculations for the first
170 * 1GB of ram), and pump it up a bit when free memory is
173 * The general minimum is maxproc * 8 (we want someone pushing
174 * up maxproc a lot to also get more vnodes). Usually maxproc
175 * does not affect this calculation.
177 * There isn't much of a point allowing maxvnodes to exceed a
178 * few million as our modern filesystems cache pages in the
179 * underlying block device and not so much hanging off of VM
182 factor1 = 50 * (sizeof(struct vm_object) + sizeof(struct vnode));
183 factor2 = 30 * (sizeof(struct vm_object) + sizeof(struct vnode));
185 freemem = (int64_t)vmstats.v_page_count * PAGE_SIZE;
187 maxvnodes = freemem / factor1;
188 if (freemem > MAXVNBREAKMEM)
189 maxvnodes += (freemem - MAXVNBREAKMEM) / factor1;
190 maxvnodes = imax(maxvnodes, maxproc * 8);
191 maxvnodes = imin(maxvnodes, KvaSize / factor2);
192 maxvnodes = imin(maxvnodes, MAXVNODES);
193 maxvnodes = imax(maxvnodes, MINVNODES);
195 lwkt_token_init(&spechash_token, "spechash");
199 * Knob to control the precision of file timestamps:
201 * 0 = seconds only; nanoseconds zeroed.
202 * 1 = seconds and nanoseconds, accurate within 1/HZ.
203 * 2 = seconds and nanoseconds, truncated to microseconds.
204 * >=3 = seconds and nanoseconds, maximum precision.
206 * Note that utimes() precision is microseconds because it takes a timeval
207 * structure, so its probably best to default to USEC and not NSEC.
209 enum { TSP_SEC, TSP_HZ, TSP_USEC, TSP_NSEC,
210 TSP_USEC_PRECISE, TSP_NSEC_PRECISE };
212 __read_mostly static int timestamp_precision = TSP_USEC;
213 SYSCTL_INT(_vfs, OID_AUTO, timestamp_precision, CTLFLAG_RW,
214 ×tamp_precision, 0, "Precision of file timestamps");
217 * Get a current timestamp.
222 vfs_timestamp(struct timespec *tsp)
224 switch (timestamp_precision) {
225 case TSP_SEC: /* seconds precision */
230 case TSP_HZ: /* ticks precision (limit to microseconds) */
232 tsp->tv_nsec -= tsp->tv_nsec % 1000;
234 case TSP_USEC: /* microseconds (ticks precision) */
236 tsp->tv_nsec -= tsp->tv_nsec % 1000;
238 case TSP_NSEC: /* nanoseconds (ticks precision) */
241 case TSP_USEC_PRECISE: /* microseconds (high preceision) */
243 tsp->tv_nsec -= tsp->tv_nsec % 1000;
245 case TSP_NSEC_PRECISE: /* nanoseconds (high precision) */
252 * Set vnode attributes to VNOVAL
255 vattr_null(struct vattr *vap)
258 vap->va_size = VNOVAL;
259 vap->va_bytes = VNOVAL;
260 vap->va_mode = VNOVAL;
261 vap->va_nlink = VNOVAL;
262 vap->va_uid = VNOVAL;
263 vap->va_gid = VNOVAL;
264 vap->va_fsid = VNOVAL;
265 vap->va_fileid = VNOVAL;
266 vap->va_blocksize = VNOVAL;
267 vap->va_rmajor = VNOVAL;
268 vap->va_rminor = VNOVAL;
269 vap->va_atime.tv_sec = VNOVAL;
270 vap->va_atime.tv_nsec = VNOVAL;
271 vap->va_mtime.tv_sec = VNOVAL;
272 vap->va_mtime.tv_nsec = VNOVAL;
273 vap->va_ctime.tv_sec = VNOVAL;
274 vap->va_ctime.tv_nsec = VNOVAL;
275 vap->va_flags = VNOVAL;
276 vap->va_gen = VNOVAL;
278 /* va_*_uuid fields are only valid if related flags are set */
282 * Flush out and invalidate all buffers associated with a vnode.
286 static int vinvalbuf_bp(struct buf *bp, void *data);
288 struct vinvalbuf_bp_info {
297 vinvalbuf(struct vnode *vp, int flags, int slpflag, int slptimeo)
299 struct vinvalbuf_bp_info info;
303 lwkt_gettoken(&vp->v_token);
306 * If we are being asked to save, call fsync to ensure that the inode
309 if (flags & V_SAVE) {
310 error = bio_track_wait(&vp->v_track_write, slpflag, slptimeo);
313 if (!RB_EMPTY(&vp->v_rbdirty_tree)) {
314 if ((error = VOP_FSYNC(vp, MNT_WAIT, 0)) != 0)
318 * Dirty bufs may be left or generated via races
319 * in circumstances where vinvalbuf() is called on
320 * a vnode not undergoing reclamation. Only
321 * panic if we are trying to reclaim the vnode.
323 if ((vp->v_flag & VRECLAIMED) &&
324 (bio_track_active(&vp->v_track_write) ||
325 !RB_EMPTY(&vp->v_rbdirty_tree))) {
326 panic("vinvalbuf: dirty bufs");
331 info.slptimeo = slptimeo;
332 info.lkflags = LK_EXCLUSIVE | LK_SLEEPFAIL;
333 if (slpflag & PCATCH)
334 info.lkflags |= LK_PCATCH;
339 * Flush the buffer cache until nothing is left, wait for all I/O
340 * to complete. At least one pass is required. We might block
341 * in the pip code so we have to re-check. Order is important.
347 if (!RB_EMPTY(&vp->v_rbclean_tree)) {
349 error = RB_SCAN(buf_rb_tree, &vp->v_rbclean_tree,
350 NULL, vinvalbuf_bp, &info);
352 if (!RB_EMPTY(&vp->v_rbdirty_tree)) {
354 error = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree,
355 NULL, vinvalbuf_bp, &info);
359 * Wait for I/O completion.
361 bio_track_wait(&vp->v_track_write, 0, 0);
362 if ((object = vp->v_object) != NULL)
363 refcount_wait(&object->paging_in_progress, "vnvlbx");
364 } while (bio_track_active(&vp->v_track_write) ||
365 !RB_EMPTY(&vp->v_rbclean_tree) ||
366 !RB_EMPTY(&vp->v_rbdirty_tree));
369 * Destroy the copy in the VM cache, too.
371 if ((object = vp->v_object) != NULL) {
372 vm_object_page_remove(object, 0, 0,
373 (flags & V_SAVE) ? TRUE : FALSE);
376 if (!RB_EMPTY(&vp->v_rbdirty_tree) || !RB_EMPTY(&vp->v_rbclean_tree))
377 panic("vinvalbuf: flush failed");
378 if (!RB_EMPTY(&vp->v_rbhash_tree))
379 panic("vinvalbuf: flush failed, buffers still present");
382 lwkt_reltoken(&vp->v_token);
387 vinvalbuf_bp(struct buf *bp, void *data)
389 struct vinvalbuf_bp_info *info = data;
392 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
393 atomic_add_int(&bp->b_refs, 1);
394 error = BUF_TIMELOCK(bp, info->lkflags,
395 "vinvalbuf", info->slptimeo);
396 atomic_subtract_int(&bp->b_refs, 1);
405 KKASSERT(bp->b_vp == info->vp);
408 * Must check clean/dirty status after successfully locking as
411 if ((info->clean && (bp->b_flags & B_DELWRI)) ||
412 (info->clean == 0 && (bp->b_flags & B_DELWRI) == 0)) {
418 * NOTE: NO B_LOCKED CHECK. Also no buf_checkwrite()
419 * check. This code will write out the buffer, period.
422 if (((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI) &&
423 (info->flags & V_SAVE)) {
425 } else if (info->flags & V_SAVE) {
427 * Cannot set B_NOCACHE on a clean buffer as this will
428 * destroy the VM backing store which might actually
429 * be dirty (and unsynchronized).
431 bp->b_flags |= (B_INVAL | B_RELBUF);
434 bp->b_flags |= (B_INVAL | B_NOCACHE | B_RELBUF);
441 * Truncate a file's buffer and pages to a specified length. This
442 * is in lieu of the old vinvalbuf mechanism, which performed unneeded
445 * The vnode must be locked.
447 static int vtruncbuf_bp_trunc_cmp(struct buf *bp, void *data);
448 static int vtruncbuf_bp_trunc(struct buf *bp, void *data);
449 static int vtruncbuf_bp_metasync_cmp(struct buf *bp, void *data);
450 static int vtruncbuf_bp_metasync(struct buf *bp, void *data);
452 struct vtruncbuf_info {
459 vtruncbuf(struct vnode *vp, off_t length, int blksize)
461 struct vtruncbuf_info info;
462 const char *filename;
466 * Round up to the *next* block, then destroy the buffers in question.
467 * Since we are only removing some of the buffers we must rely on the
468 * scan count to determine whether a loop is necessary.
470 if ((count = (int)(length % blksize)) != 0)
471 info.truncloffset = length + (blksize - count);
473 info.truncloffset = length;
476 lwkt_gettoken(&vp->v_token);
479 count = RB_SCAN(buf_rb_tree, &vp->v_rbclean_tree,
480 vtruncbuf_bp_trunc_cmp,
481 vtruncbuf_bp_trunc, &info);
483 count += RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree,
484 vtruncbuf_bp_trunc_cmp,
485 vtruncbuf_bp_trunc, &info);
489 * For safety, fsync any remaining metadata if the file is not being
490 * truncated to 0. Since the metadata does not represent the entire
491 * dirty list we have to rely on the hit count to ensure that we get
496 count = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree,
497 vtruncbuf_bp_metasync_cmp,
498 vtruncbuf_bp_metasync, &info);
503 * Clean out any left over VM backing store.
505 * It is possible to have in-progress I/O from buffers that were
506 * not part of the truncation. This should not happen if we
507 * are truncating to 0-length.
509 vnode_pager_setsize(vp, length);
510 bio_track_wait(&vp->v_track_write, 0, 0);
515 spin_lock(&vp->v_spin);
516 filename = TAILQ_FIRST(&vp->v_namecache) ?
517 TAILQ_FIRST(&vp->v_namecache)->nc_name : "?";
518 spin_unlock(&vp->v_spin);
521 * Make sure no buffers were instantiated while we were trying
522 * to clean out the remaining VM pages. This could occur due
523 * to busy dirty VM pages being flushed out to disk.
527 count = RB_SCAN(buf_rb_tree, &vp->v_rbclean_tree,
528 vtruncbuf_bp_trunc_cmp,
529 vtruncbuf_bp_trunc, &info);
531 count += RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree,
532 vtruncbuf_bp_trunc_cmp,
533 vtruncbuf_bp_trunc, &info);
535 kprintf("Warning: vtruncbuf(): Had to re-clean %d "
536 "left over buffers in %s\n", count, filename);
540 lwkt_reltoken(&vp->v_token);
546 * The callback buffer is beyond the new file EOF and must be destroyed.
547 * Note that the compare function must conform to the RB_SCAN's requirements.
551 vtruncbuf_bp_trunc_cmp(struct buf *bp, void *data)
553 struct vtruncbuf_info *info = data;
555 if (bp->b_loffset >= info->truncloffset)
562 vtruncbuf_bp_trunc(struct buf *bp, void *data)
564 struct vtruncbuf_info *info = data;
567 * Do not try to use a buffer we cannot immediately lock, but sleep
568 * anyway to prevent a livelock. The code will loop until all buffers
571 * We must always revalidate the buffer after locking it to deal
574 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
575 atomic_add_int(&bp->b_refs, 1);
576 if (BUF_LOCK(bp, LK_EXCLUSIVE|LK_SLEEPFAIL) == 0)
578 atomic_subtract_int(&bp->b_refs, 1);
579 } else if ((info->clean && (bp->b_flags & B_DELWRI)) ||
580 (info->clean == 0 && (bp->b_flags & B_DELWRI) == 0) ||
581 bp->b_vp != info->vp ||
582 vtruncbuf_bp_trunc_cmp(bp, data)) {
586 bp->b_flags |= (B_INVAL | B_RELBUF | B_NOCACHE);
593 * Fsync all meta-data after truncating a file to be non-zero. Only metadata
594 * blocks (with a negative loffset) are scanned.
595 * Note that the compare function must conform to the RB_SCAN's requirements.
598 vtruncbuf_bp_metasync_cmp(struct buf *bp, void *data __unused)
600 if (bp->b_loffset < 0)
606 vtruncbuf_bp_metasync(struct buf *bp, void *data)
608 struct vtruncbuf_info *info = data;
610 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
611 atomic_add_int(&bp->b_refs, 1);
612 if (BUF_LOCK(bp, LK_EXCLUSIVE|LK_SLEEPFAIL) == 0)
614 atomic_subtract_int(&bp->b_refs, 1);
615 } else if ((bp->b_flags & B_DELWRI) == 0 ||
616 bp->b_vp != info->vp ||
617 vtruncbuf_bp_metasync_cmp(bp, data)) {
621 if (bp->b_vp == info->vp)
630 * vfsync - implements a multipass fsync on a file which understands
631 * dependancies and meta-data. The passed vnode must be locked. The
632 * waitfor argument may be MNT_WAIT or MNT_NOWAIT, or MNT_LAZY.
634 * When fsyncing data asynchronously just do one consolidated pass starting
635 * with the most negative block number. This may not get all the data due
638 * When fsyncing data synchronously do a data pass, then a metadata pass,
639 * then do additional data+metadata passes to try to get all the data out.
641 * Caller must ref the vnode but does not have to lock it.
643 static int vfsync_wait_output(struct vnode *vp,
644 int (*waitoutput)(struct vnode *, struct thread *));
645 static int vfsync_dummy_cmp(struct buf *bp __unused, void *data __unused);
646 static int vfsync_data_only_cmp(struct buf *bp, void *data);
647 static int vfsync_meta_only_cmp(struct buf *bp, void *data);
648 static int vfsync_lazy_range_cmp(struct buf *bp, void *data);
649 static int vfsync_bp(struct buf *bp, void *data);
659 int (*checkdef)(struct buf *);
660 int (*cmpfunc)(struct buf *, void *);
664 vfsync(struct vnode *vp, int waitfor, int passes,
665 int (*checkdef)(struct buf *),
666 int (*waitoutput)(struct vnode *, struct thread *))
668 struct vfsync_info info;
671 bzero(&info, sizeof(info));
673 if ((info.checkdef = checkdef) == NULL)
676 lwkt_gettoken(&vp->v_token);
679 case MNT_LAZY | MNT_NOWAIT:
682 * Lazy (filesystem syncer typ) Asynchronous plus limit the
683 * number of data (not meta) pages we try to flush to 1MB.
684 * A non-zero return means that lazy limit was reached.
686 info.lazylimit = 1024 * 1024;
688 info.cmpfunc = vfsync_lazy_range_cmp;
689 error = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree,
690 vfsync_lazy_range_cmp, vfsync_bp, &info);
691 info.cmpfunc = vfsync_meta_only_cmp;
692 RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree,
693 vfsync_meta_only_cmp, vfsync_bp, &info);
696 else if (!RB_EMPTY(&vp->v_rbdirty_tree))
697 vn_syncer_add(vp, 1);
702 * Asynchronous. Do a data-only pass and a meta-only pass.
705 info.cmpfunc = vfsync_data_only_cmp;
706 RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, vfsync_data_only_cmp,
708 info.cmpfunc = vfsync_meta_only_cmp;
709 RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, vfsync_meta_only_cmp,
715 * Synchronous. Do a data-only pass, then a meta-data+data
716 * pass, then additional integrated passes to try to get
717 * all the dependancies flushed.
719 info.cmpfunc = vfsync_data_only_cmp;
721 RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, vfsync_data_only_cmp,
724 error = vfsync_wait_output(vp, waitoutput);
726 info.skippedbufs = 0;
727 info.cmpfunc = vfsync_dummy_cmp;
728 RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, NULL,
730 error = vfsync_wait_output(vp, waitoutput);
731 if (info.skippedbufs) {
732 kprintf("Warning: vfsync skipped %d dirty "
735 ((info.skippedbufs > 1) ? "s" : ""));
738 while (error == 0 && passes > 0 &&
739 !RB_EMPTY(&vp->v_rbdirty_tree)
741 info.skippedbufs = 0;
743 info.synchronous = 1;
746 info.cmpfunc = vfsync_dummy_cmp;
747 error = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, NULL,
753 error = vfsync_wait_output(vp, waitoutput);
754 if (info.skippedbufs && passes == 0) {
755 kprintf("Warning: vfsync skipped %d dirty "
756 "buf%s in final pass!\n",
758 ((info.skippedbufs > 1) ? "s" : ""));
763 * This case can occur normally because vnode lock might
766 if (!RB_EMPTY(&vp->v_rbdirty_tree))
767 kprintf("dirty bufs left after final pass\n");
771 lwkt_reltoken(&vp->v_token);
777 vfsync_wait_output(struct vnode *vp,
778 int (*waitoutput)(struct vnode *, struct thread *))
782 error = bio_track_wait(&vp->v_track_write, 0, 0);
784 error = waitoutput(vp, curthread);
789 vfsync_dummy_cmp(struct buf *bp __unused, void *data __unused)
795 vfsync_data_only_cmp(struct buf *bp, void *data)
797 if (bp->b_loffset < 0)
803 vfsync_meta_only_cmp(struct buf *bp, void *data)
805 if (bp->b_loffset < 0)
811 vfsync_lazy_range_cmp(struct buf *bp, void *data)
813 struct vfsync_info *info = data;
815 if (bp->b_loffset < info->vp->v_lazyw)
821 vfsync_bp(struct buf *bp, void *data)
823 struct vfsync_info *info = data;
824 struct vnode *vp = info->vp;
827 if (info->fastpass) {
829 * Ignore buffers that we cannot immediately lock.
831 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
833 * Removed BUF_TIMELOCK(..., 1), even a 1-tick
834 * delay can mess up performance
836 * Another reason is that during a dirty-buffer
837 * scan a clustered write can start I/O on buffers
838 * ahead of the scan, causing the scan to not
839 * get a lock here. Usually this means the write
840 * is already in progress so, in fact, we *want*
841 * to skip the buffer.
846 } else if (info->synchronous == 0) {
848 * Normal pass, give the buffer a little time to become
851 if (BUF_TIMELOCK(bp, LK_EXCLUSIVE, "bflst2", hz / 10)) {
857 * Synchronous pass, give the buffer a lot of time before
860 if (BUF_TIMELOCK(bp, LK_EXCLUSIVE, "bflst3", hz * 10)) {
867 * We must revalidate the buffer after locking.
869 if ((bp->b_flags & B_DELWRI) == 0 ||
870 bp->b_vp != info->vp ||
871 info->cmpfunc(bp, data)) {
877 * If syncdeps is not set we do not try to write buffers which have
880 if (!info->synchronous && info->syncdeps == 0 && info->checkdef(bp)) {
886 * B_NEEDCOMMIT (primarily used by NFS) is a state where the buffer
887 * has been written but an additional handshake with the device
888 * is required before we can dispose of the buffer. We have no idea
889 * how to do this so we have to skip these buffers.
891 if (bp->b_flags & B_NEEDCOMMIT) {
897 * Ask bioops if it is ok to sync. If not the VFS may have
898 * set B_LOCKED so we have to cycle the buffer.
900 if (LIST_FIRST(&bp->b_dep) != NULL && buf_checkwrite(bp)) {
906 if (info->synchronous) {
908 * Synchronous flush. An error may be returned and will
915 * Asynchronous flush. We use the error return to support
918 * In low-memory situations we revert to synchronous
919 * operation. This should theoretically prevent the I/O
920 * path from exhausting memory in a non-recoverable way.
922 vp->v_lazyw = bp->b_loffset;
924 if (vm_page_count_min(0)) {
926 info->lazycount += bp->b_bufsize;
930 info->lazycount += cluster_awrite(bp);
931 waitrunningbufspace();
932 /*vm_wait_nominal();*/
934 if (info->lazylimit && info->lazycount >= info->lazylimit)
943 * Associate a buffer with a vnode.
948 bgetvp(struct vnode *vp, struct buf *bp, int testsize)
950 KASSERT(bp->b_vp == NULL, ("bgetvp: not free"));
951 KKASSERT((bp->b_flags & (B_HASHED|B_DELWRI|B_VNCLEAN|B_VNDIRTY)) == 0);
954 * Insert onto list for new vnode.
956 lwkt_gettoken(&vp->v_token);
958 if (buf_rb_hash_RB_INSERT(&vp->v_rbhash_tree, bp)) {
959 lwkt_reltoken(&vp->v_token);
964 * Diagnostics (mainly for HAMMER debugging). Check for
965 * overlapping buffers.
967 if (check_buf_overlap) {
969 bx = buf_rb_hash_RB_PREV(bp);
971 if (bx->b_loffset + bx->b_bufsize > bp->b_loffset) {
972 kprintf("bgetvp: overlapl %016jx/%d %016jx "
974 (intmax_t)bx->b_loffset,
976 (intmax_t)bp->b_loffset,
978 if (check_buf_overlap > 1)
979 panic("bgetvp - overlapping buffer");
982 bx = buf_rb_hash_RB_NEXT(bp);
984 if (bp->b_loffset + testsize > bx->b_loffset) {
985 kprintf("bgetvp: overlapr %016jx/%d %016jx "
987 (intmax_t)bp->b_loffset,
989 (intmax_t)bx->b_loffset,
991 if (check_buf_overlap > 1)
992 panic("bgetvp - overlapping buffer");
997 bp->b_flags |= B_HASHED;
998 bp->b_flags |= B_VNCLEAN;
999 if (buf_rb_tree_RB_INSERT(&vp->v_rbclean_tree, bp))
1000 panic("reassignbuf: dup lblk/clean vp %p bp %p", vp, bp);
1002 lwkt_reltoken(&vp->v_token);
1007 * Disassociate a buffer from a vnode.
1012 brelvp(struct buf *bp)
1016 KASSERT(bp->b_vp != NULL, ("brelvp: NULL"));
1019 * Delete from old vnode list, if on one.
1022 lwkt_gettoken(&vp->v_token);
1023 if (bp->b_flags & (B_VNDIRTY | B_VNCLEAN)) {
1024 if (bp->b_flags & B_VNDIRTY)
1025 buf_rb_tree_RB_REMOVE(&vp->v_rbdirty_tree, bp);
1027 buf_rb_tree_RB_REMOVE(&vp->v_rbclean_tree, bp);
1028 bp->b_flags &= ~(B_VNDIRTY | B_VNCLEAN);
1030 if (bp->b_flags & B_HASHED) {
1031 buf_rb_hash_RB_REMOVE(&vp->v_rbhash_tree, bp);
1032 bp->b_flags &= ~B_HASHED;
1036 * Only remove from synclist when no dirty buffers are left AND
1037 * the VFS has not flagged the vnode's inode as being dirty.
1039 if ((vp->v_flag & (VONWORKLST | VISDIRTY | VOBJDIRTY)) == VONWORKLST &&
1040 RB_EMPTY(&vp->v_rbdirty_tree)) {
1041 vn_syncer_remove(vp, 0);
1045 lwkt_reltoken(&vp->v_token);
1051 * Reassign the buffer to the proper clean/dirty list based on B_DELWRI.
1052 * This routine is called when the state of the B_DELWRI bit is changed.
1054 * Must be called with vp->v_token held.
1058 reassignbuf(struct buf *bp)
1060 struct vnode *vp = bp->b_vp;
1063 ASSERT_LWKT_TOKEN_HELD(&vp->v_token);
1067 * B_PAGING flagged buffers cannot be reassigned because their vp
1068 * is not fully linked in.
1070 if (bp->b_flags & B_PAGING)
1071 panic("cannot reassign paging buffer");
1073 if (bp->b_flags & B_DELWRI) {
1075 * Move to the dirty list, add the vnode to the worklist
1077 if (bp->b_flags & B_VNCLEAN) {
1078 buf_rb_tree_RB_REMOVE(&vp->v_rbclean_tree, bp);
1079 bp->b_flags &= ~B_VNCLEAN;
1081 if ((bp->b_flags & B_VNDIRTY) == 0) {
1082 if (buf_rb_tree_RB_INSERT(&vp->v_rbdirty_tree, bp)) {
1083 panic("reassignbuf: dup lblk vp %p bp %p",
1086 bp->b_flags |= B_VNDIRTY;
1088 if ((vp->v_flag & VONWORKLST) == 0) {
1089 switch (vp->v_type) {
1096 vp->v_rdev->si_mountpoint != NULL) {
1104 vn_syncer_add(vp, delay);
1108 * Move to the clean list, remove the vnode from the worklist
1109 * if no dirty blocks remain.
1111 if (bp->b_flags & B_VNDIRTY) {
1112 buf_rb_tree_RB_REMOVE(&vp->v_rbdirty_tree, bp);
1113 bp->b_flags &= ~B_VNDIRTY;
1115 if ((bp->b_flags & B_VNCLEAN) == 0) {
1116 if (buf_rb_tree_RB_INSERT(&vp->v_rbclean_tree, bp)) {
1117 panic("reassignbuf: dup lblk vp %p bp %p",
1120 bp->b_flags |= B_VNCLEAN;
1124 * Only remove from synclist when no dirty buffers are left
1125 * AND the VFS has not flagged the vnode's inode as being
1128 if ((vp->v_flag & (VONWORKLST | VISDIRTY | VOBJDIRTY)) ==
1130 RB_EMPTY(&vp->v_rbdirty_tree)) {
1131 vn_syncer_remove(vp, 0);
1137 * Create a vnode for a block device. Used for mounting the root file
1140 * A vref()'d vnode is returned.
1142 extern struct vop_ops *devfs_vnode_dev_vops_p;
1144 bdevvp(cdev_t dev, struct vnode **vpp)
1154 error = getspecialvnode(VT_NON, NULL, &devfs_vnode_dev_vops_p,
1165 v_associate_rdev(vp, dev);
1166 vp->v_umajor = dev->si_umajor;
1167 vp->v_uminor = dev->si_uminor;
1174 v_associate_rdev(struct vnode *vp, cdev_t dev)
1178 if (dev_is_good(dev) == 0)
1180 KKASSERT(vp->v_rdev == NULL);
1181 vp->v_rdev = reference_dev(dev);
1182 lwkt_gettoken(&spechash_token);
1183 SLIST_INSERT_HEAD(&dev->si_hlist, vp, v_cdevnext);
1184 lwkt_reltoken(&spechash_token);
1189 v_release_rdev(struct vnode *vp)
1193 if ((dev = vp->v_rdev) != NULL) {
1194 lwkt_gettoken(&spechash_token);
1195 SLIST_REMOVE(&dev->si_hlist, vp, vnode, v_cdevnext);
1198 lwkt_reltoken(&spechash_token);
1203 * Add a vnode to the alias list hung off the cdev_t. We only associate
1204 * the device number with the vnode. The actual device is not associated
1205 * until the vnode is opened (usually in spec_open()), and will be
1206 * disassociated on last close.
1209 addaliasu(struct vnode *nvp, int x, int y)
1211 if (nvp->v_type != VBLK && nvp->v_type != VCHR)
1212 panic("addaliasu on non-special vnode");
1218 * Simple call that a filesystem can make to try to get rid of a
1219 * vnode. It will fail if anyone is referencing the vnode (including
1222 * The filesystem can check whether its in-memory inode structure still
1223 * references the vp on return.
1225 * May only be called if the vnode is in a known state (i.e. being prevented
1226 * from being deallocated by some other condition such as a vfs inode hold).
1228 * This call might not succeed.
1231 vclean_unlocked(struct vnode *vp)
1234 if (VREFCNT(vp) <= 1)
1240 * Disassociate a vnode from its underlying filesystem.
1242 * The vnode must be VX locked and referenced. In all normal situations
1243 * there are no active references. If vclean_vxlocked() is called while
1244 * there are active references, the vnode is being ripped out and we have
1245 * to call VOP_CLOSE() as appropriate before we can reclaim it.
1248 vclean_vxlocked(struct vnode *vp, int flags)
1253 struct namecache *ncp;
1256 * If the vnode has already been reclaimed we have nothing to do.
1258 if (vp->v_flag & VRECLAIMED)
1262 * Set flag to interlock operation, flag finalization to ensure
1263 * that the vnode winds up on the inactive list, and set v_act to 0.
1265 vsetflags(vp, VRECLAIMED);
1266 atomic_set_int(&vp->v_refcnt, VREF_FINALIZE);
1269 if (verbose_reclaims) {
1270 if ((ncp = TAILQ_FIRST(&vp->v_namecache)) != NULL)
1271 kprintf("Debug: reclaim %p %s\n", vp, ncp->nc_name);
1275 * Scrap the vfs cache
1277 while (cache_inval_vp(vp, 0) != 0) {
1278 kprintf("Warning: vnode %p clean/cache_resolution "
1279 "race detected\n", vp);
1280 tsleep(vp, 0, "vclninv", 2);
1284 * Check to see if the vnode is in use. If so we have to reference it
1285 * before we clean it out so that its count cannot fall to zero and
1286 * generate a race against ourselves to recycle it.
1288 active = (VREFCNT(vp) > 0);
1291 * Clean out any buffers associated with the vnode and destroy its
1292 * object, if it has one.
1294 vinvalbuf(vp, V_SAVE, 0, 0);
1297 * If purging an active vnode (typically during a forced unmount
1298 * or reboot), it must be closed and deactivated before being
1299 * reclaimed. This isn't really all that safe, but what can
1302 * Note that neither of these routines unlocks the vnode.
1304 if (active && (flags & DOCLOSE)) {
1305 while ((n = vp->v_opencount) != 0) {
1306 if (vp->v_writecount)
1307 VOP_CLOSE(vp, FWRITE|FNONBLOCK, NULL);
1309 VOP_CLOSE(vp, FNONBLOCK, NULL);
1310 if (vp->v_opencount == n) {
1311 kprintf("Warning: unable to force-close"
1319 * If the vnode has not been deactivated, deactivated it. Deactivation
1320 * can create new buffers and VM pages so we have to call vinvalbuf()
1321 * again to make sure they all get flushed.
1323 * This can occur if a file with a link count of 0 needs to be
1326 * If the vnode is already dead don't try to deactivate it.
1328 if ((vp->v_flag & VINACTIVE) == 0) {
1329 vsetflags(vp, VINACTIVE);
1332 vinvalbuf(vp, V_SAVE, 0, 0);
1336 * If the vnode has an object, destroy it.
1338 while ((object = vp->v_object) != NULL) {
1339 vm_object_hold(object);
1340 if (object == vp->v_object)
1342 vm_object_drop(object);
1345 if (object != NULL) {
1346 if (object->ref_count == 0) {
1347 if ((object->flags & OBJ_DEAD) == 0)
1348 vm_object_terminate(object);
1349 vm_object_drop(object);
1350 vclrflags(vp, VOBJBUF);
1352 vm_pager_deallocate(object);
1353 vclrflags(vp, VOBJBUF);
1354 vm_object_drop(object);
1357 KKASSERT((vp->v_flag & VOBJBUF) == 0);
1359 if (vp->v_flag & VOBJDIRTY)
1363 * Reclaim the vnode if not already dead.
1365 if (vp->v_mount && VOP_RECLAIM(vp))
1366 panic("vclean: cannot reclaim");
1369 * Done with purge, notify sleepers of the grim news.
1371 vp->v_ops = &dead_vnode_vops_p;
1376 * If we are destroying an active vnode, reactivate it now that
1377 * we have reassociated it with deadfs. This prevents the system
1378 * from crashing on the vnode due to it being unexpectedly marked
1379 * as inactive or reclaimed.
1381 if (active && (flags & DOCLOSE)) {
1382 vclrflags(vp, VINACTIVE | VRECLAIMED);
1387 * Eliminate all activity associated with the requested vnode
1388 * and with all vnodes aliased to the requested vnode.
1390 * The vnode must be referenced but should not be locked.
1393 vrevoke(struct vnode *vp, struct ucred *cred)
1401 * If the vnode has a device association, scrap all vnodes associated
1402 * with the device. Don't let the device disappear on us while we
1403 * are scrapping the vnodes.
1405 * The passed vp will probably show up in the list, do not VX lock
1408 * Releasing the vnode's rdev here can mess up specfs's call to
1409 * device close, so don't do it. The vnode has been disassociated
1410 * and the device will be closed after the last ref on the related
1411 * fp goes away (if not still open by e.g. the kernel).
1413 if (vp->v_type != VCHR) {
1414 error = fdrevoke(vp, DTYPE_VNODE, cred);
1417 if ((dev = vp->v_rdev) == NULL) {
1421 lwkt_gettoken(&spechash_token);
1424 vqn = SLIST_FIRST(&dev->si_hlist);
1427 while ((vq = vqn) != NULL) {
1428 if (VREFCNT(vq) > 0) {
1430 fdrevoke(vq, DTYPE_VNODE, cred);
1431 /*v_release_rdev(vq);*/
1433 if (vq->v_rdev != dev) {
1438 vqn = SLIST_NEXT(vq, v_cdevnext);
1443 lwkt_reltoken(&spechash_token);
1450 * This is called when the object underlying a vnode is being destroyed,
1451 * such as in a remove(). Try to recycle the vnode immediately if the
1452 * only active reference is our reference.
1454 * Directory vnodes in the namecache with children cannot be immediately
1455 * recycled because numerous VOP_N*() ops require them to be stable.
1457 * To avoid recursive recycling from VOP_INACTIVE implemenetations this
1458 * function is a NOP if VRECLAIMED is already set.
1461 vrecycle(struct vnode *vp)
1463 if (VREFCNT(vp) <= 1 && (vp->v_flag & VRECLAIMED) == 0) {
1464 if (cache_inval_vp_nonblock(vp))
1473 * Return the maximum I/O size allowed for strategy calls on VP.
1475 * If vp is VCHR or VBLK we dive the device, otherwise we use
1476 * the vp's mount info.
1478 * The returned value is clamped at MAXPHYS as most callers cannot use
1479 * buffers larger than that size.
1482 vmaxiosize(struct vnode *vp)
1486 if (vp->v_type == VBLK || vp->v_type == VCHR)
1487 maxiosize = vp->v_rdev->si_iosize_max;
1489 maxiosize = vp->v_mount->mnt_iosize_max;
1491 if (maxiosize > MAXPHYS)
1492 maxiosize = MAXPHYS;
1497 * Eliminate all activity associated with a vnode in preparation for
1500 * The vnode must be VX locked and refd and will remain VX locked and refd
1501 * on return. This routine may be called with the vnode in any state, as
1502 * long as it is VX locked. The vnode will be cleaned out and marked
1503 * VRECLAIMED but will not actually be reused until all existing refs and
1506 * NOTE: This routine may be called on a vnode which has not yet been
1507 * already been deactivated (VOP_INACTIVE), or on a vnode which has
1508 * already been reclaimed.
1510 * This routine is not responsible for placing us back on the freelist.
1511 * Instead, it happens automatically when the caller releases the VX lock
1512 * (assuming there aren't any other references).
1515 vgone_vxlocked(struct vnode *vp)
1518 * assert that the VX lock is held. This is an absolute requirement
1519 * now for vgone_vxlocked() to be called.
1521 KKASSERT(lockinuse(&vp->v_lock));
1524 * Clean out the filesystem specific data and set the VRECLAIMED
1525 * bit. Also deactivate the vnode if necessary.
1527 * The vnode should have automatically been removed from the syncer
1528 * list as syncer/dirty flags cleared during the cleaning.
1530 vclean_vxlocked(vp, DOCLOSE);
1533 * Normally panic if the vnode is still dirty, unless we are doing
1534 * a forced unmount (tmpfs typically).
1536 if (vp->v_flag & VONWORKLST) {
1537 if (vp->v_mount->mnt_kern_flag & MNTK_UNMOUNTF) {
1539 vn_syncer_remove(vp, 1);
1541 panic("vp %p still dirty in vgone after flush", vp);
1546 * Delete from old mount point vnode list, if on one.
1548 if (vp->v_mount != NULL) {
1549 KKASSERT(vp->v_data == NULL);
1550 insmntque(vp, NULL);
1554 * If special device, remove it from special device alias list
1555 * if it is on one. This should normally only occur if a vnode is
1556 * being revoked as the device should otherwise have been released
1559 if ((vp->v_type == VBLK || vp->v_type == VCHR) && vp->v_rdev != NULL) {
1570 * Calculate the total number of references to a special device. This
1571 * routine may only be called for VBLK and VCHR vnodes since v_rdev is
1572 * an overloaded field. Since dev_from_devid() can now return NULL, we
1573 * have to check for a NULL v_rdev.
1576 count_dev(cdev_t dev)
1581 if (SLIST_FIRST(&dev->si_hlist)) {
1582 lwkt_gettoken(&spechash_token);
1583 SLIST_FOREACH(vp, &dev->si_hlist, v_cdevnext) {
1584 count += vp->v_opencount;
1586 lwkt_reltoken(&spechash_token);
1592 vcount(struct vnode *vp)
1594 if (vp->v_rdev == NULL)
1596 return(count_dev(vp->v_rdev));
1600 * Initialize VMIO for a vnode. This routine MUST be called before a
1601 * VFS can issue buffer cache ops on a vnode. It is typically called
1602 * when a vnode is initialized from its inode.
1605 vinitvmio(struct vnode *vp, off_t filesize, int blksize, int boff)
1610 object = vp->v_object;
1612 vm_object_hold(object);
1613 KKASSERT(vp->v_object == object);
1616 if (object == NULL) {
1617 object = vnode_pager_alloc(vp, filesize, 0, 0, blksize, boff);
1620 * Dereference the reference we just created. This assumes
1621 * that the object is associated with the vp. Allow it to
1622 * have zero refs. It cannot be destroyed as long as it
1623 * is associated with the vnode.
1625 vm_object_hold(object);
1626 atomic_add_int(&object->ref_count, -1);
1629 KKASSERT((object->flags & OBJ_DEAD) == 0);
1631 KASSERT(vp->v_object != NULL, ("vinitvmio: NULL object"));
1632 vsetflags(vp, VOBJBUF);
1633 vm_object_drop(object);
1640 * Print out a description of a vnode.
1642 static char *typename[] =
1643 {"VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD"};
1646 vprint(char *label, struct vnode *vp)
1651 kprintf("%s: %p: ", label, (void *)vp);
1653 kprintf("%p: ", (void *)vp);
1654 kprintf("type %s, refcnt %08x, writecount %d, holdcnt %d,",
1655 typename[vp->v_type],
1656 vp->v_refcnt, vp->v_writecount, vp->v_auxrefs);
1658 if (vp->v_flag & VROOT)
1659 strcat(buf, "|VROOT");
1660 if (vp->v_flag & VPFSROOT)
1661 strcat(buf, "|VPFSROOT");
1662 if (vp->v_flag & VTEXT)
1663 strcat(buf, "|VTEXT");
1664 if (vp->v_flag & VSYSTEM)
1665 strcat(buf, "|VSYSTEM");
1666 if (vp->v_flag & VOBJBUF)
1667 strcat(buf, "|VOBJBUF");
1669 kprintf(" flags (%s)", &buf[1]);
1670 if (vp->v_data == NULL) {
1679 * Do the usual access checking.
1680 * file_mode, uid and gid are from the vnode in question,
1681 * while acc_mode and cred are from the VOP_ACCESS parameter list
1684 vaccess(enum vtype type, mode_t file_mode, uid_t uid, gid_t gid,
1685 mode_t acc_mode, struct ucred *cred)
1691 * Super-user always gets read/write access, but execute access depends
1692 * on at least one execute bit being set.
1694 if (priv_check_cred(cred, PRIV_ROOT, 0) == 0) {
1695 if ((acc_mode & VEXEC) && type != VDIR &&
1696 (file_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0)
1703 /* Otherwise, check the owner. */
1704 if (cred->cr_uid == uid) {
1705 if (acc_mode & VEXEC)
1707 if (acc_mode & VREAD)
1709 if (acc_mode & VWRITE)
1711 return ((file_mode & mask) == mask ? 0 : EACCES);
1714 /* Otherwise, check the groups. */
1715 ismember = groupmember(gid, cred);
1716 if (cred->cr_svgid == gid || ismember) {
1717 if (acc_mode & VEXEC)
1719 if (acc_mode & VREAD)
1721 if (acc_mode & VWRITE)
1723 return ((file_mode & mask) == mask ? 0 : EACCES);
1726 /* Otherwise, check everyone else. */
1727 if (acc_mode & VEXEC)
1729 if (acc_mode & VREAD)
1731 if (acc_mode & VWRITE)
1733 return ((file_mode & mask) == mask ? 0 : EACCES);
1737 #include <ddb/ddb.h>
1739 static int db_show_locked_vnodes(struct mount *mp, void *data);
1742 * List all of the locked vnodes in the system.
1743 * Called when debugging the kernel.
1745 DB_SHOW_COMMAND(lockedvnodes, lockedvnodes)
1747 kprintf("Locked vnodes\n");
1748 mountlist_scan(db_show_locked_vnodes, NULL,
1749 MNTSCAN_FORWARD|MNTSCAN_NOBUSY);
1753 db_show_locked_vnodes(struct mount *mp, void *data __unused)
1757 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
1758 if (vn_islocked(vp))
1766 * Top level filesystem related information gathering.
1768 static int sysctl_ovfs_conf (SYSCTL_HANDLER_ARGS);
1771 vfs_sysctl(SYSCTL_HANDLER_ARGS)
1773 int *name = (int *)arg1 - 1; /* XXX */
1774 u_int namelen = arg2 + 1; /* XXX */
1775 struct vfsconf *vfsp;
1778 #if 1 || defined(COMPAT_PRELITE2)
1779 /* Resolve ambiguity between VFS_VFSCONF and VFS_GENERIC. */
1781 return (sysctl_ovfs_conf(oidp, arg1, arg2, req));
1785 /* all sysctl names at this level are at least name and field */
1787 return (ENOTDIR); /* overloaded */
1788 if (name[0] != VFS_GENERIC) {
1789 vfsp = vfsconf_find_by_typenum(name[0]);
1791 return (EOPNOTSUPP);
1792 return ((*vfsp->vfc_vfsops->vfs_sysctl)(&name[1], namelen - 1,
1793 oldp, oldlenp, newp, newlen, p));
1797 case VFS_MAXTYPENUM:
1800 maxtypenum = vfsconf_get_maxtypenum();
1801 return (SYSCTL_OUT(req, &maxtypenum, sizeof(maxtypenum)));
1804 return (ENOTDIR); /* overloaded */
1805 vfsp = vfsconf_find_by_typenum(name[2]);
1807 return (EOPNOTSUPP);
1808 return (SYSCTL_OUT(req, vfsp, sizeof *vfsp));
1810 return (EOPNOTSUPP);
1813 SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RD, vfs_sysctl,
1814 "Generic filesystem");
1816 #if 1 || defined(COMPAT_PRELITE2)
1819 sysctl_ovfs_conf_iter(struct vfsconf *vfsp, void *data)
1822 struct ovfsconf ovfs;
1823 struct sysctl_req *req = (struct sysctl_req*) data;
1825 bzero(&ovfs, sizeof(ovfs));
1826 ovfs.vfc_vfsops = vfsp->vfc_vfsops; /* XXX used as flag */
1827 strcpy(ovfs.vfc_name, vfsp->vfc_name);
1828 ovfs.vfc_index = vfsp->vfc_typenum;
1829 ovfs.vfc_refcount = vfsp->vfc_refcount;
1830 ovfs.vfc_flags = vfsp->vfc_flags;
1831 error = SYSCTL_OUT(req, &ovfs, sizeof ovfs);
1833 return error; /* abort iteration with error code */
1835 return 0; /* continue iterating with next element */
1839 sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS)
1841 return vfsconf_each(sysctl_ovfs_conf_iter, (void*)req);
1844 #endif /* 1 || COMPAT_PRELITE2 */
1847 * Check to see if a filesystem is mounted on a block device.
1850 vfs_mountedon(struct vnode *vp)
1855 if (dev != NULL && dev->si_mountpoint)
1861 * Unmount all filesystems. The list is traversed in reverse order
1862 * of mounting to avoid dependencies.
1864 * We want the umountall to be able to break out of its loop if a
1865 * failure occurs, after scanning all possible mounts, so the callback
1866 * returns 0 on error.
1868 * NOTE: Do not call mountlist_remove(mp) on error any more, this will
1869 * confuse mountlist_scan()'s unbusy check.
1871 static int vfs_umountall_callback(struct mount *mp, void *data);
1874 vfs_unmountall(int halting)
1879 count = mountlist_scan(vfs_umountall_callback, &halting,
1880 MNTSCAN_REVERSE|MNTSCAN_NOBUSY);
1886 vfs_umountall_callback(struct mount *mp, void *data)
1889 int halting = *(int *)data;
1892 * NOTE: When halting, dounmount will disconnect but leave
1893 * certain mount points intact. e.g. devfs.
1895 error = dounmount(mp, MNT_FORCE, halting);
1897 kprintf("unmount of filesystem mounted from %s failed (",
1898 mp->mnt_stat.f_mntfromname);
1902 kprintf("%d)\n", error);
1910 * Checks the mount flags for parameter mp and put the names comma-separated
1911 * into a string buffer buf with a size limit specified by len.
1913 * It returns the number of bytes written into buf, and (*errorp) will be
1914 * set to 0, EINVAL (if passed length is 0), or ENOSPC (supplied buffer was
1915 * not large enough). The buffer will be 0-terminated if len was not 0.
1918 vfs_flagstostr(int flags, const struct mountctl_opt *optp,
1919 char *buf, size_t len, int *errorp)
1921 static const struct mountctl_opt optnames[] = {
1922 { MNT_RDONLY, "read-only" },
1923 { MNT_SYNCHRONOUS, "synchronous" },
1924 { MNT_NOEXEC, "noexec" },
1925 { MNT_NOSUID, "nosuid" },
1926 { MNT_NODEV, "nodev" },
1927 { MNT_AUTOMOUNTED, "automounted" },
1928 { MNT_ASYNC, "asynchronous" },
1929 { MNT_SUIDDIR, "suiddir" },
1930 { MNT_SOFTDEP, "soft-updates" },
1931 { MNT_NOSYMFOLLOW, "nosymfollow" },
1932 { MNT_TRIM, "trim" },
1933 { MNT_NOATIME, "noatime" },
1934 { MNT_NOCLUSTERR, "noclusterr" },
1935 { MNT_NOCLUSTERW, "noclusterw" },
1936 { MNT_EXRDONLY, "NFS read-only" },
1937 { MNT_EXPORTED, "NFS exported" },
1938 /* Remaining NFS flags could come here */
1939 { MNT_LOCAL, "local" },
1940 { MNT_QUOTA, "with-quotas" },
1941 /* { MNT_ROOTFS, "rootfs" }, */
1942 /* { MNT_IGNORE, "ignore" }, */
1952 bleft = len - 1; /* leave room for trailing \0 */
1955 * Checks the size of the string. If it contains
1956 * any data, then we will append the new flags to
1959 actsize = strlen(buf);
1963 /* Default flags if no flags passed */
1967 if (bleft < 0) { /* degenerate case, 0-length buffer */
1972 for (; flags && optp->o_opt; ++optp) {
1973 if ((flags & optp->o_opt) == 0)
1975 optlen = strlen(optp->o_name);
1976 if (bwritten || actsize > 0) {
1981 buf[bwritten++] = ',';
1982 buf[bwritten++] = ' ';
1985 if (bleft < optlen) {
1989 bcopy(optp->o_name, buf + bwritten, optlen);
1992 flags &= ~optp->o_opt;
1996 * Space already reserved for trailing \0
2003 * Build hash lists of net addresses and hang them off the mount point.
2004 * Called by ufs_mount() to set up the lists of export addresses.
2007 vfs_hang_addrlist(struct mount *mp, struct netexport *nep,
2008 const struct export_args *argp)
2011 struct radix_node_head *rnh;
2013 struct radix_node *rn;
2014 struct sockaddr *saddr, *smask = NULL;
2017 if (argp->ex_addrlen == 0) {
2018 if (mp->mnt_flag & MNT_DEFEXPORTED)
2020 np = &nep->ne_defexported;
2021 np->netc_exflags = argp->ex_flags;
2022 np->netc_anon = argp->ex_anon;
2023 np->netc_anon.cr_ref = 1;
2024 mp->mnt_flag |= MNT_DEFEXPORTED;
2028 if (argp->ex_addrlen < 0 || argp->ex_addrlen > MLEN)
2030 if (argp->ex_masklen < 0 || argp->ex_masklen > MLEN)
2033 i = sizeof(struct netcred) + argp->ex_addrlen + argp->ex_masklen;
2034 np = (struct netcred *)kmalloc(i, M_NETCRED, M_WAITOK | M_ZERO);
2035 saddr = (struct sockaddr *) (np + 1);
2036 if ((error = copyin(argp->ex_addr, (caddr_t) saddr, argp->ex_addrlen)))
2038 if (saddr->sa_len > argp->ex_addrlen)
2039 saddr->sa_len = argp->ex_addrlen;
2040 if (argp->ex_masklen) {
2041 smask = (struct sockaddr *)((caddr_t)saddr + argp->ex_addrlen);
2042 error = copyin(argp->ex_mask, (caddr_t)smask, argp->ex_masklen);
2045 if (smask->sa_len > argp->ex_masklen)
2046 smask->sa_len = argp->ex_masklen;
2049 if (nep->ne_maskhead == NULL) {
2050 if (!rn_inithead((void **)&nep->ne_maskhead, NULL, 0)) {
2055 if ((rnh = vfs_create_addrlist_af(saddr->sa_family, nep)) == NULL) {
2059 rn = (*rnh->rnh_addaddr)((char *)saddr, (char *)smask, rnh,
2062 if (rn == NULL || np != (struct netcred *)rn) { /* already exists */
2066 np->netc_exflags = argp->ex_flags;
2067 np->netc_anon = argp->ex_anon;
2068 np->netc_anon.cr_ref = 1;
2072 kfree(np, M_NETCRED);
2077 * Free netcred structures installed in the netexport
2080 vfs_free_netcred(struct radix_node *rn, void *w)
2082 struct radix_node_head *rnh = (struct radix_node_head *)w;
2084 (*rnh->rnh_deladdr) (rn->rn_key, rn->rn_mask, rnh);
2085 kfree(rn, M_NETCRED);
2091 * callback to free an element of the mask table installed in the
2092 * netexport. These may be created indirectly and are not netcred
2096 vfs_free_netcred_mask(struct radix_node *rn, void *w)
2098 struct radix_node_head *rnh = (struct radix_node_head *)w;
2100 (*rnh->rnh_deladdr) (rn->rn_key, rn->rn_mask, rnh);
2101 kfree(rn, M_RTABLE);
2106 static struct radix_node_head *
2107 vfs_create_addrlist_af(int af, struct netexport *nep)
2109 struct radix_node_head *rnh = NULL;
2110 #if defined(INET) || defined(INET6)
2111 struct radix_node_head *maskhead = nep->ne_maskhead;
2115 NE_ASSERT_LOCKED(nep);
2116 #if defined(INET) || defined(INET6)
2117 KKASSERT(maskhead != NULL);
2122 if ((rnh = nep->ne_inethead) == NULL) {
2123 off = offsetof(struct sockaddr_in, sin_addr) << 3;
2124 if (!rn_inithead((void **)&rnh, maskhead, off))
2126 nep->ne_inethead = rnh;
2132 if ((rnh = nep->ne_inet6head) == NULL) {
2133 off = offsetof(struct sockaddr_in6, sin6_addr) << 3;
2134 if (!rn_inithead((void **)&rnh, maskhead, off))
2136 nep->ne_inet6head = rnh;
2145 * helper function for freeing netcred elements
2148 vfs_free_addrlist_af(struct radix_node_head **prnh)
2150 struct radix_node_head *rnh = *prnh;
2152 (*rnh->rnh_walktree) (rnh, vfs_free_netcred, rnh);
2153 kfree(rnh, M_RTABLE);
2158 * helper function for freeing mask elements
2161 vfs_free_addrlist_masks(struct radix_node_head **prnh)
2163 struct radix_node_head *rnh = *prnh;
2165 (*rnh->rnh_walktree) (rnh, vfs_free_netcred_mask, rnh);
2166 kfree(rnh, M_RTABLE);
2171 * Free the net address hash lists that are hanging off the mount points.
2174 vfs_free_addrlist(struct netexport *nep)
2177 if (nep->ne_inethead != NULL)
2178 vfs_free_addrlist_af(&nep->ne_inethead);
2179 if (nep->ne_inet6head != NULL)
2180 vfs_free_addrlist_af(&nep->ne_inet6head);
2181 if (nep->ne_maskhead)
2182 vfs_free_addrlist_masks(&nep->ne_maskhead);
2187 vfs_export(struct mount *mp, struct netexport *nep,
2188 const struct export_args *argp)
2192 if (argp->ex_flags & MNT_DELEXPORT) {
2193 if (mp->mnt_flag & MNT_EXPUBLIC) {
2194 vfs_setpublicfs(NULL, NULL, NULL);
2195 mp->mnt_flag &= ~MNT_EXPUBLIC;
2197 vfs_free_addrlist(nep);
2198 mp->mnt_flag &= ~(MNT_EXPORTED | MNT_DEFEXPORTED);
2200 if (argp->ex_flags & MNT_EXPORTED) {
2201 if (argp->ex_flags & MNT_EXPUBLIC) {
2202 if ((error = vfs_setpublicfs(mp, nep, argp)) != 0)
2204 mp->mnt_flag |= MNT_EXPUBLIC;
2206 if ((error = vfs_hang_addrlist(mp, nep, argp)))
2208 mp->mnt_flag |= MNT_EXPORTED;
2215 * Set the publicly exported filesystem (WebNFS). Currently, only
2216 * one public filesystem is possible in the spec (RFC 2054 and 2055)
2219 vfs_setpublicfs(struct mount *mp, struct netexport *nep,
2220 const struct export_args *argp)
2227 * mp == NULL -> invalidate the current info, the FS is
2228 * no longer exported. May be called from either vfs_export
2229 * or unmount, so check if it hasn't already been done.
2232 if (nfs_pub.np_valid) {
2233 nfs_pub.np_valid = 0;
2234 if (nfs_pub.np_index != NULL) {
2235 kfree(nfs_pub.np_index, M_TEMP);
2236 nfs_pub.np_index = NULL;
2243 * Only one allowed at a time.
2245 if (nfs_pub.np_valid != 0 && mp != nfs_pub.np_mount)
2249 * Get real filehandle for root of exported FS.
2251 bzero((caddr_t)&nfs_pub.np_handle, sizeof(nfs_pub.np_handle));
2252 nfs_pub.np_handle.fh_fsid = mp->mnt_stat.f_fsid;
2254 if ((error = VFS_ROOT(mp, &rvp)))
2257 if ((error = VFS_VPTOFH(rvp, &nfs_pub.np_handle.fh_fid)))
2263 * If an indexfile was specified, pull it in.
2265 if (argp->ex_indexfile != NULL) {
2268 error = vn_get_namelen(rvp, &namelen);
2271 nfs_pub.np_index = kmalloc(namelen, M_TEMP, M_WAITOK);
2272 error = copyinstr(argp->ex_indexfile, nfs_pub.np_index,
2276 * Check for illegal filenames.
2278 for (cp = nfs_pub.np_index; *cp; cp++) {
2286 kfree(nfs_pub.np_index, M_TEMP);
2291 nfs_pub.np_mount = mp;
2292 nfs_pub.np_valid = 1;
2297 vfs_export_lookup(struct mount *mp, struct netexport *nep,
2298 struct sockaddr *nam)
2301 struct radix_node_head *rnh;
2302 struct sockaddr *saddr;
2305 if (mp->mnt_flag & MNT_EXPORTED) {
2307 * Lookup in the export list first.
2312 switch (saddr->sa_family) {
2315 rnh = nep->ne_inethead;
2320 rnh = nep->ne_inet6head;
2327 np = (struct netcred *)
2328 (*rnh->rnh_matchaddr)((char *)saddr,
2330 if (np && np->netc_rnodes->rn_flags & RNF_ROOT)
2336 * If no address match, use the default if it exists.
2338 if (np == NULL && mp->mnt_flag & MNT_DEFEXPORTED)
2339 np = &nep->ne_defexported;
2345 * perform msync on all vnodes under a mount point. The mount point must
2346 * be locked. This code is also responsible for lazy-freeing unreferenced
2347 * vnodes whos VM objects no longer contain pages.
2349 * NOTE: MNT_WAIT still skips vnodes in the VXLOCK state.
2351 * NOTE: XXX VOP_PUTPAGES and friends requires that the vnode be locked,
2352 * but vnode_pager_putpages() doesn't lock the vnode. We have to do it
2353 * way up in this high level function.
2355 static int vfs_msync_scan1(struct mount *mp, struct vnode *vp, void *data);
2356 static int vfs_msync_scan2(struct mount *mp, struct vnode *vp, void *data);
2359 vfs_msync(struct mount *mp, int flags)
2364 * tmpfs sets this flag to prevent msync(), sync, and the
2365 * filesystem periodic syncer from trying to flush VM pages
2366 * to swap. Only pure memory pressure flushes tmpfs VM pages
2369 if (mp->mnt_kern_flag & MNTK_NOMSYNC)
2373 * Ok, scan the vnodes for work. If the filesystem is using the
2374 * syncer thread feature we can use vsyncscan() instead of
2375 * vmntvnodescan(), which is much faster.
2377 vmsc_flags = VMSC_GETVP;
2378 if (flags != MNT_WAIT)
2379 vmsc_flags |= VMSC_NOWAIT;
2381 if (mp->mnt_kern_flag & MNTK_THR_SYNC) {
2382 vsyncscan(mp, vmsc_flags, vfs_msync_scan2,
2383 (void *)(intptr_t)flags);
2385 vmntvnodescan(mp, vmsc_flags,
2386 vfs_msync_scan1, vfs_msync_scan2,
2387 (void *)(intptr_t)flags);
2392 * scan1 is a fast pre-check. There could be hundreds of thousands of
2393 * vnodes, we cannot afford to do anything heavy weight until we have a
2394 * fairly good indication that there is work to do.
2396 * The new namecache holds the vnode for each v_namecache association
2397 * so allow these refs.
2401 vfs_msync_scan1(struct mount *mp, struct vnode *vp, void *data)
2403 int flags = (int)(intptr_t)data;
2405 if ((vp->v_flag & VRECLAIMED) == 0) {
2406 if (vp->v_auxrefs == vp->v_namecache_count &&
2407 VREFCNT(vp) <= 0 && vp->v_object) {
2408 return(0); /* call scan2 */
2410 if ((mp->mnt_flag & MNT_RDONLY) == 0 &&
2411 (vp->v_flag & VOBJDIRTY) &&
2412 (flags == MNT_WAIT || vn_islocked(vp) == 0)) {
2413 return(0); /* call scan2 */
2418 * do not call scan2, continue the loop
2424 * This callback is handed a locked vnode.
2428 vfs_msync_scan2(struct mount *mp, struct vnode *vp, void *data)
2431 int flags = (int)(intptr_t)data;
2434 if (vp->v_flag & VRECLAIMED)
2437 if ((mp->mnt_flag & MNT_RDONLY) == 0 && (vp->v_flag & VOBJDIRTY)) {
2438 if ((obj = vp->v_object) != NULL) {
2439 if (flags == MNT_WAIT) {
2441 * VFS_MSYNC is called with MNT_WAIT when
2444 opcflags = OBJPC_SYNC;
2445 } else if (vp->v_writecount || obj->ref_count) {
2447 * VFS_MSYNC is otherwise called via the
2448 * periodic filesystem sync or the 'sync'
2449 * command. Honor MADV_NOSYNC / MAP_NOSYNC
2450 * if the file is open for writing or memory
2451 * mapped. Pages flagged PG_NOSYNC will not
2452 * be automatically flushed at this time.
2454 * The obj->ref_count test is not perfect
2455 * since temporary refs may be present, but
2456 * the periodic filesystem sync will ultimately
2457 * catch it if the file is not open and not
2460 opcflags = OBJPC_NOSYNC;
2463 * If the file is no longer open for writing
2464 * and also no longer mapped, do not honor
2465 * MAP_NOSYNC. That is, fully synchronize
2468 * This still occurs on the periodic fs sync,
2469 * so frontend programs which turn the file
2470 * over quickly enough can still avoid the
2471 * sync, but ultimately we do want to flush
2472 * even MADV_NOSYNC pages once it is no longer
2473 * mapped or open for writing.
2477 vm_object_page_clean(obj, 0, 0, opcflags);
2484 * Wake up anyone interested in vp because it is being revoked.
2487 vn_gone(struct vnode *vp)
2489 lwkt_gettoken(&vp->v_token);
2490 KNOTE(&vp->v_pollinfo.vpi_kqinfo.ki_note, NOTE_REVOKE);
2491 lwkt_reltoken(&vp->v_token);
2495 * extract the cdev_t from a VBLK or VCHR. The vnode must have been opened
2496 * (or v_rdev might be NULL).
2499 vn_todev(struct vnode *vp)
2501 if (vp->v_type != VBLK && vp->v_type != VCHR)
2503 KKASSERT(vp->v_rdev != NULL);
2504 return (vp->v_rdev);
2508 * Check if vnode represents a disk device. The vnode does not need to be
2514 vn_isdisk(struct vnode *vp, int *errp)
2518 if (vp->v_type != VCHR) {
2531 if (dev_is_good(dev) == 0) {
2536 if ((dev_dflags(dev) & D_DISK) == 0) {
2547 vn_get_namelen(struct vnode *vp, int *namelen)
2550 register_t retval[2];
2552 error = VOP_PATHCONF(vp, _PC_NAME_MAX, retval);
2555 *namelen = (int)retval[0];
2560 vop_write_dirent(int *error, struct uio *uio, ino_t d_ino, uint8_t d_type,
2561 uint16_t d_namlen, const char *d_name)
2566 len = _DIRENT_RECLEN(d_namlen);
2567 if (len > uio->uio_resid)
2570 dp = kmalloc(len, M_TEMP, M_WAITOK | M_ZERO);
2573 dp->d_namlen = d_namlen;
2574 dp->d_type = d_type;
2575 bcopy(d_name, dp->d_name, d_namlen);
2577 *error = uiomove((caddr_t)dp, len, uio);
2585 vn_mark_atime(struct vnode *vp, struct thread *td)
2587 struct proc *p = td->td_proc;
2588 struct ucred *cred = p ? p->p_ucred : proc0.p_ucred;
2590 if ((vp->v_mount->mnt_flag & (MNT_NOATIME | MNT_RDONLY)) == 0) {
2591 VOP_MARKATIME(vp, cred);
2596 * Calculate the number of entries in an inode-related chained hash table.
2597 * With today's memory sizes, maxvnodes can wind up being a very large
2598 * number. There is no reason to waste memory, so tolerate some stacking.
2601 vfs_inodehashsize(void)
2606 while (hsize < maxvnodes)
2608 while (hsize > maxvnodes * 2)
2609 hsize >>= 1; /* nominal 2x stacking */
2611 if (maxvnodes > 1024 * 1024)
2612 hsize >>= 1; /* nominal 8x stacking */
2614 if (maxvnodes > 128 * 1024)
2615 hsize >>= 1; /* nominal 4x stacking */
2628 #define SETHIGH(q, h) { \
2631 tmp.val[_QUAD_HIGHWORD] = (h); \
2634 #define SETLOW(q, l) { \
2637 tmp.val[_QUAD_LOWWORD] = (l); \
2642 init_va_filerev(void)
2647 getmicrouptime(&tv);
2648 SETHIGH(ret, tv.tv_sec);
2649 SETLOW(ret, tv.tv_usec * 4294);