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/eventhandler.h>
52 #include <sys/fcntl.h>
54 #include <sys/kernel.h>
55 #include <sys/kthread.h>
56 #include <sys/malloc.h>
58 #include <sys/mount.h>
61 #include <sys/reboot.h>
62 #include <sys/socket.h>
64 #include <sys/sysctl.h>
65 #include <sys/syslog.h>
66 #include <sys/unistd.h>
67 #include <sys/vmmeter.h>
68 #include <sys/vnode.h>
70 #include <machine/limits.h>
73 #include <vm/vm_object.h>
74 #include <vm/vm_extern.h>
75 #include <vm/vm_kern.h>
77 #include <vm/vm_map.h>
78 #include <vm/vm_page.h>
79 #include <vm/vm_pager.h>
80 #include <vm/vnode_pager.h>
81 #include <vm/vm_zone.h>
84 #include <sys/mplock2.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);
131 __read_mostly int prtactive = 0; /* 1 => print out reclaim of active vnodes */
134 * Red black tree functions
136 static int rb_buf_compare(struct buf *b1, struct buf *b2);
137 RB_GENERATE2(buf_rb_tree, buf, b_rbnode, rb_buf_compare, off_t, b_loffset);
138 RB_GENERATE2(buf_rb_hash, buf, b_rbhash, rb_buf_compare, off_t, b_loffset);
141 rb_buf_compare(struct buf *b1, struct buf *b2)
143 if (b1->b_loffset < b2->b_loffset)
145 if (b1->b_loffset > b2->b_loffset)
151 * Initialize the vnode management data structures.
153 * Called from vfsinit()
155 #define MAXVNBREAKMEM (1L * 1024 * 1024 * 1024)
156 #define MINVNODES 2000
157 #define MAXVNODES 4000000
162 int factor1; /* Limit based on ram (x 2 above 1GB) */
163 int factor2; /* Limit based on available KVM */
167 * Size maxvnodes to available memory. Size significantly
168 * smaller on low-memory systems (calculations for the first
169 * 1GB of ram), and pump it up a bit when free memory is
172 * The general minimum is maxproc * 8 (we want someone pushing
173 * up maxproc a lot to also get more vnodes). Usually maxproc
174 * does not affect this calculation.
176 * There isn't much of a point allowing maxvnodes to exceed a
177 * few million as our modern filesystems cache pages in the
178 * underlying block device and not so much hanging off of VM
181 factor1 = 50 * (sizeof(struct vm_object) + sizeof(struct vnode));
182 factor2 = 30 * (sizeof(struct vm_object) + sizeof(struct vnode));
184 freemem = (int64_t)vmstats.v_page_count * PAGE_SIZE;
186 maxvnodes = freemem / factor1;
187 if (freemem > MAXVNBREAKMEM)
188 maxvnodes += (freemem - MAXVNBREAKMEM) / factor1;
189 maxvnodes = imax(maxvnodes, maxproc * 8);
190 maxvnodes = imin(maxvnodes, KvaSize / factor2);
191 maxvnodes = imin(maxvnodes, MAXVNODES);
192 maxvnodes = imax(maxvnodes, MINVNODES);
194 lwkt_token_init(&spechash_token, "spechash");
198 * Knob to control the precision of file timestamps:
200 * 0 = seconds only; nanoseconds zeroed.
201 * 1 = seconds and nanoseconds, accurate within 1/HZ.
202 * 2 = seconds and nanoseconds, truncated to microseconds.
203 * >=3 = seconds and nanoseconds, maximum precision.
205 * Note that utimes() precision is microseconds because it takes a timeval
206 * structure, so its probably best to default to USEC and not NSEC.
208 enum { TSP_SEC, TSP_HZ, TSP_USEC, TSP_NSEC };
210 __read_mostly static int timestamp_precision = TSP_USEC;
211 SYSCTL_INT(_vfs, OID_AUTO, timestamp_precision, CTLFLAG_RW,
212 ×tamp_precision, 0, "Precision of file timestamps");
215 * Get a current timestamp.
220 vfs_timestamp(struct timespec *tsp)
224 switch (timestamp_precision) {
226 tsp->tv_sec = time_second;
234 TIMEVAL_TO_TIMESPEC(&tv, tsp);
244 * Set vnode attributes to VNOVAL
247 vattr_null(struct vattr *vap)
250 vap->va_size = VNOVAL;
251 vap->va_bytes = VNOVAL;
252 vap->va_mode = VNOVAL;
253 vap->va_nlink = VNOVAL;
254 vap->va_uid = VNOVAL;
255 vap->va_gid = VNOVAL;
256 vap->va_fsid = VNOVAL;
257 vap->va_fileid = VNOVAL;
258 vap->va_blocksize = VNOVAL;
259 vap->va_rmajor = VNOVAL;
260 vap->va_rminor = VNOVAL;
261 vap->va_atime.tv_sec = VNOVAL;
262 vap->va_atime.tv_nsec = VNOVAL;
263 vap->va_mtime.tv_sec = VNOVAL;
264 vap->va_mtime.tv_nsec = VNOVAL;
265 vap->va_ctime.tv_sec = VNOVAL;
266 vap->va_ctime.tv_nsec = VNOVAL;
267 vap->va_flags = VNOVAL;
268 vap->va_gen = VNOVAL;
270 /* va_*_uuid fields are only valid if related flags are set */
274 * Flush out and invalidate all buffers associated with a vnode.
278 static int vinvalbuf_bp(struct buf *bp, void *data);
280 struct vinvalbuf_bp_info {
289 vinvalbuf(struct vnode *vp, int flags, int slpflag, int slptimeo)
291 struct vinvalbuf_bp_info info;
295 lwkt_gettoken(&vp->v_token);
298 * If we are being asked to save, call fsync to ensure that the inode
301 if (flags & V_SAVE) {
302 error = bio_track_wait(&vp->v_track_write, slpflag, slptimeo);
305 if (!RB_EMPTY(&vp->v_rbdirty_tree)) {
306 if ((error = VOP_FSYNC(vp, MNT_WAIT, 0)) != 0)
310 * Dirty bufs may be left or generated via races
311 * in circumstances where vinvalbuf() is called on
312 * a vnode not undergoing reclamation. Only
313 * panic if we are trying to reclaim the vnode.
315 if ((vp->v_flag & VRECLAIMED) &&
316 (bio_track_active(&vp->v_track_write) ||
317 !RB_EMPTY(&vp->v_rbdirty_tree))) {
318 panic("vinvalbuf: dirty bufs");
323 info.slptimeo = slptimeo;
324 info.lkflags = LK_EXCLUSIVE | LK_SLEEPFAIL;
325 if (slpflag & PCATCH)
326 info.lkflags |= LK_PCATCH;
331 * Flush the buffer cache until nothing is left, wait for all I/O
332 * to complete. At least one pass is required. We might block
333 * in the pip code so we have to re-check. Order is important.
339 if (!RB_EMPTY(&vp->v_rbclean_tree)) {
341 error = RB_SCAN(buf_rb_tree, &vp->v_rbclean_tree,
342 NULL, vinvalbuf_bp, &info);
344 if (!RB_EMPTY(&vp->v_rbdirty_tree)) {
346 error = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree,
347 NULL, vinvalbuf_bp, &info);
351 * Wait for I/O completion.
353 bio_track_wait(&vp->v_track_write, 0, 0);
354 if ((object = vp->v_object) != NULL)
355 refcount_wait(&object->paging_in_progress, "vnvlbx");
356 } while (bio_track_active(&vp->v_track_write) ||
357 !RB_EMPTY(&vp->v_rbclean_tree) ||
358 !RB_EMPTY(&vp->v_rbdirty_tree));
361 * Destroy the copy in the VM cache, too.
363 if ((object = vp->v_object) != NULL) {
364 vm_object_page_remove(object, 0, 0,
365 (flags & V_SAVE) ? TRUE : FALSE);
368 if (!RB_EMPTY(&vp->v_rbdirty_tree) || !RB_EMPTY(&vp->v_rbclean_tree))
369 panic("vinvalbuf: flush failed");
370 if (!RB_EMPTY(&vp->v_rbhash_tree))
371 panic("vinvalbuf: flush failed, buffers still present");
374 lwkt_reltoken(&vp->v_token);
379 vinvalbuf_bp(struct buf *bp, void *data)
381 struct vinvalbuf_bp_info *info = data;
384 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
385 atomic_add_int(&bp->b_refs, 1);
386 error = BUF_TIMELOCK(bp, info->lkflags,
387 "vinvalbuf", info->slptimeo);
388 atomic_subtract_int(&bp->b_refs, 1);
397 KKASSERT(bp->b_vp == info->vp);
400 * Must check clean/dirty status after successfully locking as
403 if ((info->clean && (bp->b_flags & B_DELWRI)) ||
404 (info->clean == 0 && (bp->b_flags & B_DELWRI) == 0)) {
410 * NOTE: NO B_LOCKED CHECK. Also no buf_checkwrite()
411 * check. This code will write out the buffer, period.
414 if (((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI) &&
415 (info->flags & V_SAVE)) {
417 } else if (info->flags & V_SAVE) {
419 * Cannot set B_NOCACHE on a clean buffer as this will
420 * destroy the VM backing store which might actually
421 * be dirty (and unsynchronized).
423 bp->b_flags |= (B_INVAL | B_RELBUF);
426 bp->b_flags |= (B_INVAL | B_NOCACHE | B_RELBUF);
433 * Truncate a file's buffer and pages to a specified length. This
434 * is in lieu of the old vinvalbuf mechanism, which performed unneeded
437 * The vnode must be locked.
439 static int vtruncbuf_bp_trunc_cmp(struct buf *bp, void *data);
440 static int vtruncbuf_bp_trunc(struct buf *bp, void *data);
441 static int vtruncbuf_bp_metasync_cmp(struct buf *bp, void *data);
442 static int vtruncbuf_bp_metasync(struct buf *bp, void *data);
444 struct vtruncbuf_info {
451 vtruncbuf(struct vnode *vp, off_t length, int blksize)
453 struct vtruncbuf_info info;
454 const char *filename;
458 * Round up to the *next* block, then destroy the buffers in question.
459 * Since we are only removing some of the buffers we must rely on the
460 * scan count to determine whether a loop is necessary.
462 if ((count = (int)(length % blksize)) != 0)
463 info.truncloffset = length + (blksize - count);
465 info.truncloffset = length;
468 lwkt_gettoken(&vp->v_token);
471 count = RB_SCAN(buf_rb_tree, &vp->v_rbclean_tree,
472 vtruncbuf_bp_trunc_cmp,
473 vtruncbuf_bp_trunc, &info);
475 count += RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree,
476 vtruncbuf_bp_trunc_cmp,
477 vtruncbuf_bp_trunc, &info);
481 * For safety, fsync any remaining metadata if the file is not being
482 * truncated to 0. Since the metadata does not represent the entire
483 * dirty list we have to rely on the hit count to ensure that we get
488 count = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree,
489 vtruncbuf_bp_metasync_cmp,
490 vtruncbuf_bp_metasync, &info);
495 * Clean out any left over VM backing store.
497 * It is possible to have in-progress I/O from buffers that were
498 * not part of the truncation. This should not happen if we
499 * are truncating to 0-length.
501 vnode_pager_setsize(vp, length);
502 bio_track_wait(&vp->v_track_write, 0, 0);
507 spin_lock(&vp->v_spin);
508 filename = TAILQ_FIRST(&vp->v_namecache) ?
509 TAILQ_FIRST(&vp->v_namecache)->nc_name : "?";
510 spin_unlock(&vp->v_spin);
513 * Make sure no buffers were instantiated while we were trying
514 * to clean out the remaining VM pages. This could occur due
515 * to busy dirty VM pages being flushed out to disk.
519 count = RB_SCAN(buf_rb_tree, &vp->v_rbclean_tree,
520 vtruncbuf_bp_trunc_cmp,
521 vtruncbuf_bp_trunc, &info);
523 count += RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree,
524 vtruncbuf_bp_trunc_cmp,
525 vtruncbuf_bp_trunc, &info);
527 kprintf("Warning: vtruncbuf(): Had to re-clean %d "
528 "left over buffers in %s\n", count, filename);
532 lwkt_reltoken(&vp->v_token);
538 * The callback buffer is beyond the new file EOF and must be destroyed.
539 * Note that the compare function must conform to the RB_SCAN's requirements.
543 vtruncbuf_bp_trunc_cmp(struct buf *bp, void *data)
545 struct vtruncbuf_info *info = data;
547 if (bp->b_loffset >= info->truncloffset)
554 vtruncbuf_bp_trunc(struct buf *bp, void *data)
556 struct vtruncbuf_info *info = data;
559 * Do not try to use a buffer we cannot immediately lock, but sleep
560 * anyway to prevent a livelock. The code will loop until all buffers
563 * We must always revalidate the buffer after locking it to deal
566 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
567 atomic_add_int(&bp->b_refs, 1);
568 if (BUF_LOCK(bp, LK_EXCLUSIVE|LK_SLEEPFAIL) == 0)
570 atomic_subtract_int(&bp->b_refs, 1);
571 } else if ((info->clean && (bp->b_flags & B_DELWRI)) ||
572 (info->clean == 0 && (bp->b_flags & B_DELWRI) == 0) ||
573 bp->b_vp != info->vp ||
574 vtruncbuf_bp_trunc_cmp(bp, data)) {
578 bp->b_flags |= (B_INVAL | B_RELBUF | B_NOCACHE);
585 * Fsync all meta-data after truncating a file to be non-zero. Only metadata
586 * blocks (with a negative loffset) are scanned.
587 * Note that the compare function must conform to the RB_SCAN's requirements.
590 vtruncbuf_bp_metasync_cmp(struct buf *bp, void *data __unused)
592 if (bp->b_loffset < 0)
598 vtruncbuf_bp_metasync(struct buf *bp, void *data)
600 struct vtruncbuf_info *info = data;
602 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
603 atomic_add_int(&bp->b_refs, 1);
604 if (BUF_LOCK(bp, LK_EXCLUSIVE|LK_SLEEPFAIL) == 0)
606 atomic_subtract_int(&bp->b_refs, 1);
607 } else if ((bp->b_flags & B_DELWRI) == 0 ||
608 bp->b_vp != info->vp ||
609 vtruncbuf_bp_metasync_cmp(bp, data)) {
613 if (bp->b_vp == info->vp)
622 * vfsync - implements a multipass fsync on a file which understands
623 * dependancies and meta-data. The passed vnode must be locked. The
624 * waitfor argument may be MNT_WAIT or MNT_NOWAIT, or MNT_LAZY.
626 * When fsyncing data asynchronously just do one consolidated pass starting
627 * with the most negative block number. This may not get all the data due
630 * When fsyncing data synchronously do a data pass, then a metadata pass,
631 * then do additional data+metadata passes to try to get all the data out.
633 * Caller must ref the vnode but does not have to lock it.
635 static int vfsync_wait_output(struct vnode *vp,
636 int (*waitoutput)(struct vnode *, struct thread *));
637 static int vfsync_dummy_cmp(struct buf *bp __unused, void *data __unused);
638 static int vfsync_data_only_cmp(struct buf *bp, void *data);
639 static int vfsync_meta_only_cmp(struct buf *bp, void *data);
640 static int vfsync_lazy_range_cmp(struct buf *bp, void *data);
641 static int vfsync_bp(struct buf *bp, void *data);
651 int (*checkdef)(struct buf *);
652 int (*cmpfunc)(struct buf *, void *);
656 vfsync(struct vnode *vp, int waitfor, int passes,
657 int (*checkdef)(struct buf *),
658 int (*waitoutput)(struct vnode *, struct thread *))
660 struct vfsync_info info;
663 bzero(&info, sizeof(info));
665 if ((info.checkdef = checkdef) == NULL)
668 lwkt_gettoken(&vp->v_token);
671 case MNT_LAZY | MNT_NOWAIT:
674 * Lazy (filesystem syncer typ) Asynchronous plus limit the
675 * number of data (not meta) pages we try to flush to 1MB.
676 * A non-zero return means that lazy limit was reached.
678 info.lazylimit = 1024 * 1024;
680 info.cmpfunc = vfsync_lazy_range_cmp;
681 error = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree,
682 vfsync_lazy_range_cmp, vfsync_bp, &info);
683 info.cmpfunc = vfsync_meta_only_cmp;
684 RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree,
685 vfsync_meta_only_cmp, vfsync_bp, &info);
688 else if (!RB_EMPTY(&vp->v_rbdirty_tree))
689 vn_syncer_add(vp, 1);
694 * Asynchronous. Do a data-only pass and a meta-only pass.
697 info.cmpfunc = vfsync_data_only_cmp;
698 RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, vfsync_data_only_cmp,
700 info.cmpfunc = vfsync_meta_only_cmp;
701 RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, vfsync_meta_only_cmp,
707 * Synchronous. Do a data-only pass, then a meta-data+data
708 * pass, then additional integrated passes to try to get
709 * all the dependancies flushed.
711 info.cmpfunc = vfsync_data_only_cmp;
713 RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, vfsync_data_only_cmp,
716 error = vfsync_wait_output(vp, waitoutput);
718 info.skippedbufs = 0;
719 info.cmpfunc = vfsync_dummy_cmp;
720 RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, NULL,
722 error = vfsync_wait_output(vp, waitoutput);
723 if (info.skippedbufs) {
724 kprintf("Warning: vfsync skipped %d dirty "
727 ((info.skippedbufs > 1) ? "s" : ""));
730 while (error == 0 && passes > 0 &&
731 !RB_EMPTY(&vp->v_rbdirty_tree)
733 info.skippedbufs = 0;
735 info.synchronous = 1;
738 info.cmpfunc = vfsync_dummy_cmp;
739 error = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, NULL,
745 error = vfsync_wait_output(vp, waitoutput);
746 if (info.skippedbufs && passes == 0) {
747 kprintf("Warning: vfsync skipped %d dirty "
748 "buf%s in final pass!\n",
750 ((info.skippedbufs > 1) ? "s" : ""));
755 * This case can occur normally because vnode lock might
758 if (!RB_EMPTY(&vp->v_rbdirty_tree))
759 kprintf("dirty bufs left after final pass\n");
763 lwkt_reltoken(&vp->v_token);
769 vfsync_wait_output(struct vnode *vp,
770 int (*waitoutput)(struct vnode *, struct thread *))
774 error = bio_track_wait(&vp->v_track_write, 0, 0);
776 error = waitoutput(vp, curthread);
781 vfsync_dummy_cmp(struct buf *bp __unused, void *data __unused)
787 vfsync_data_only_cmp(struct buf *bp, void *data)
789 if (bp->b_loffset < 0)
795 vfsync_meta_only_cmp(struct buf *bp, void *data)
797 if (bp->b_loffset < 0)
803 vfsync_lazy_range_cmp(struct buf *bp, void *data)
805 struct vfsync_info *info = data;
807 if (bp->b_loffset < info->vp->v_lazyw)
813 vfsync_bp(struct buf *bp, void *data)
815 struct vfsync_info *info = data;
816 struct vnode *vp = info->vp;
819 if (info->fastpass) {
821 * Ignore buffers that we cannot immediately lock.
823 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
825 * Removed BUF_TIMELOCK(..., 1), even a 1-tick
826 * delay can mess up performance
828 * Another reason is that during a dirty-buffer
829 * scan a clustered write can start I/O on buffers
830 * ahead of the scan, causing the scan to not
831 * get a lock here. Usually this means the write
832 * is already in progress so, in fact, we *want*
833 * to skip the buffer.
838 } else if (info->synchronous == 0) {
840 * Normal pass, give the buffer a little time to become
843 if (BUF_TIMELOCK(bp, LK_EXCLUSIVE, "bflst2", hz / 10)) {
849 * Synchronous pass, give the buffer a lot of time before
852 if (BUF_TIMELOCK(bp, LK_EXCLUSIVE, "bflst3", hz * 10)) {
859 * We must revalidate the buffer after locking.
861 if ((bp->b_flags & B_DELWRI) == 0 ||
862 bp->b_vp != info->vp ||
863 info->cmpfunc(bp, data)) {
869 * If syncdeps is not set we do not try to write buffers which have
872 if (!info->synchronous && info->syncdeps == 0 && info->checkdef(bp)) {
878 * B_NEEDCOMMIT (primarily used by NFS) is a state where the buffer
879 * has been written but an additional handshake with the device
880 * is required before we can dispose of the buffer. We have no idea
881 * how to do this so we have to skip these buffers.
883 if (bp->b_flags & B_NEEDCOMMIT) {
889 * Ask bioops if it is ok to sync. If not the VFS may have
890 * set B_LOCKED so we have to cycle the buffer.
892 if (LIST_FIRST(&bp->b_dep) != NULL && buf_checkwrite(bp)) {
898 if (info->synchronous) {
900 * Synchronous flush. An error may be returned and will
907 * Asynchronous flush. We use the error return to support
910 * In low-memory situations we revert to synchronous
911 * operation. This should theoretically prevent the I/O
912 * path from exhausting memory in a non-recoverable way.
914 vp->v_lazyw = bp->b_loffset;
916 if (vm_page_count_min(0)) {
918 info->lazycount += bp->b_bufsize;
922 info->lazycount += cluster_awrite(bp);
923 waitrunningbufspace();
924 /*vm_wait_nominal();*/
926 if (info->lazylimit && info->lazycount >= info->lazylimit)
935 * Associate a buffer with a vnode.
940 bgetvp(struct vnode *vp, struct buf *bp, int testsize)
942 KASSERT(bp->b_vp == NULL, ("bgetvp: not free"));
943 KKASSERT((bp->b_flags & (B_HASHED|B_DELWRI|B_VNCLEAN|B_VNDIRTY)) == 0);
946 * Insert onto list for new vnode.
948 lwkt_gettoken(&vp->v_token);
950 if (buf_rb_hash_RB_INSERT(&vp->v_rbhash_tree, bp)) {
951 lwkt_reltoken(&vp->v_token);
956 * Diagnostics (mainly for HAMMER debugging). Check for
957 * overlapping buffers.
959 if (check_buf_overlap) {
961 bx = buf_rb_hash_RB_PREV(bp);
963 if (bx->b_loffset + bx->b_bufsize > bp->b_loffset) {
964 kprintf("bgetvp: overlapl %016jx/%d %016jx "
966 (intmax_t)bx->b_loffset,
968 (intmax_t)bp->b_loffset,
970 if (check_buf_overlap > 1)
971 panic("bgetvp - overlapping buffer");
974 bx = buf_rb_hash_RB_NEXT(bp);
976 if (bp->b_loffset + testsize > bx->b_loffset) {
977 kprintf("bgetvp: overlapr %016jx/%d %016jx "
979 (intmax_t)bp->b_loffset,
981 (intmax_t)bx->b_loffset,
983 if (check_buf_overlap > 1)
984 panic("bgetvp - overlapping buffer");
989 bp->b_flags |= B_HASHED;
990 bp->b_flags |= B_VNCLEAN;
991 if (buf_rb_tree_RB_INSERT(&vp->v_rbclean_tree, bp))
992 panic("reassignbuf: dup lblk/clean vp %p bp %p", vp, bp);
994 lwkt_reltoken(&vp->v_token);
999 * Disassociate a buffer from a vnode.
1004 brelvp(struct buf *bp)
1008 KASSERT(bp->b_vp != NULL, ("brelvp: NULL"));
1011 * Delete from old vnode list, if on one.
1014 lwkt_gettoken(&vp->v_token);
1015 if (bp->b_flags & (B_VNDIRTY | B_VNCLEAN)) {
1016 if (bp->b_flags & B_VNDIRTY)
1017 buf_rb_tree_RB_REMOVE(&vp->v_rbdirty_tree, bp);
1019 buf_rb_tree_RB_REMOVE(&vp->v_rbclean_tree, bp);
1020 bp->b_flags &= ~(B_VNDIRTY | B_VNCLEAN);
1022 if (bp->b_flags & B_HASHED) {
1023 buf_rb_hash_RB_REMOVE(&vp->v_rbhash_tree, bp);
1024 bp->b_flags &= ~B_HASHED;
1028 * Only remove from synclist when no dirty buffers are left AND
1029 * the VFS has not flagged the vnode's inode as being dirty.
1031 if ((vp->v_flag & (VONWORKLST | VISDIRTY | VOBJDIRTY)) == VONWORKLST &&
1032 RB_EMPTY(&vp->v_rbdirty_tree)) {
1033 vn_syncer_remove(vp, 0);
1037 lwkt_reltoken(&vp->v_token);
1043 * Reassign the buffer to the proper clean/dirty list based on B_DELWRI.
1044 * This routine is called when the state of the B_DELWRI bit is changed.
1046 * Must be called with vp->v_token held.
1050 reassignbuf(struct buf *bp)
1052 struct vnode *vp = bp->b_vp;
1055 ASSERT_LWKT_TOKEN_HELD(&vp->v_token);
1059 * B_PAGING flagged buffers cannot be reassigned because their vp
1060 * is not fully linked in.
1062 if (bp->b_flags & B_PAGING)
1063 panic("cannot reassign paging buffer");
1065 if (bp->b_flags & B_DELWRI) {
1067 * Move to the dirty list, add the vnode to the worklist
1069 if (bp->b_flags & B_VNCLEAN) {
1070 buf_rb_tree_RB_REMOVE(&vp->v_rbclean_tree, bp);
1071 bp->b_flags &= ~B_VNCLEAN;
1073 if ((bp->b_flags & B_VNDIRTY) == 0) {
1074 if (buf_rb_tree_RB_INSERT(&vp->v_rbdirty_tree, bp)) {
1075 panic("reassignbuf: dup lblk vp %p bp %p",
1078 bp->b_flags |= B_VNDIRTY;
1080 if ((vp->v_flag & VONWORKLST) == 0) {
1081 switch (vp->v_type) {
1088 vp->v_rdev->si_mountpoint != NULL) {
1096 vn_syncer_add(vp, delay);
1100 * Move to the clean list, remove the vnode from the worklist
1101 * if no dirty blocks remain.
1103 if (bp->b_flags & B_VNDIRTY) {
1104 buf_rb_tree_RB_REMOVE(&vp->v_rbdirty_tree, bp);
1105 bp->b_flags &= ~B_VNDIRTY;
1107 if ((bp->b_flags & B_VNCLEAN) == 0) {
1108 if (buf_rb_tree_RB_INSERT(&vp->v_rbclean_tree, bp)) {
1109 panic("reassignbuf: dup lblk vp %p bp %p",
1112 bp->b_flags |= B_VNCLEAN;
1116 * Only remove from synclist when no dirty buffers are left
1117 * AND the VFS has not flagged the vnode's inode as being
1120 if ((vp->v_flag & (VONWORKLST | VISDIRTY | VOBJDIRTY)) ==
1122 RB_EMPTY(&vp->v_rbdirty_tree)) {
1123 vn_syncer_remove(vp, 0);
1129 * Create a vnode for a block device. Used for mounting the root file
1132 * A vref()'d vnode is returned.
1134 extern struct vop_ops *devfs_vnode_dev_vops_p;
1136 bdevvp(cdev_t dev, struct vnode **vpp)
1146 error = getspecialvnode(VT_NON, NULL, &devfs_vnode_dev_vops_p,
1157 v_associate_rdev(vp, dev);
1158 vp->v_umajor = dev->si_umajor;
1159 vp->v_uminor = dev->si_uminor;
1166 v_associate_rdev(struct vnode *vp, cdev_t dev)
1170 if (dev_is_good(dev) == 0)
1172 KKASSERT(vp->v_rdev == NULL);
1173 vp->v_rdev = reference_dev(dev);
1174 lwkt_gettoken(&spechash_token);
1175 SLIST_INSERT_HEAD(&dev->si_hlist, vp, v_cdevnext);
1176 lwkt_reltoken(&spechash_token);
1181 v_release_rdev(struct vnode *vp)
1185 if ((dev = vp->v_rdev) != NULL) {
1186 lwkt_gettoken(&spechash_token);
1187 SLIST_REMOVE(&dev->si_hlist, vp, vnode, v_cdevnext);
1190 lwkt_reltoken(&spechash_token);
1195 * Add a vnode to the alias list hung off the cdev_t. We only associate
1196 * the device number with the vnode. The actual device is not associated
1197 * until the vnode is opened (usually in spec_open()), and will be
1198 * disassociated on last close.
1201 addaliasu(struct vnode *nvp, int x, int y)
1203 if (nvp->v_type != VBLK && nvp->v_type != VCHR)
1204 panic("addaliasu on non-special vnode");
1210 * Simple call that a filesystem can make to try to get rid of a
1211 * vnode. It will fail if anyone is referencing the vnode (including
1214 * The filesystem can check whether its in-memory inode structure still
1215 * references the vp on return.
1217 * May only be called if the vnode is in a known state (i.e. being prevented
1218 * from being deallocated by some other condition such as a vfs inode hold).
1221 vclean_unlocked(struct vnode *vp)
1224 if (VREFCNT(vp) <= 1)
1230 * Disassociate a vnode from its underlying filesystem.
1232 * The vnode must be VX locked and referenced. In all normal situations
1233 * there are no active references. If vclean_vxlocked() is called while
1234 * there are active references, the vnode is being ripped out and we have
1235 * to call VOP_CLOSE() as appropriate before we can reclaim it.
1238 vclean_vxlocked(struct vnode *vp, int flags)
1243 struct namecache *ncp;
1246 * If the vnode has already been reclaimed we have nothing to do.
1248 if (vp->v_flag & VRECLAIMED)
1252 * Set flag to interlock operation, flag finalization to ensure
1253 * that the vnode winds up on the inactive list, and set v_act to 0.
1255 vsetflags(vp, VRECLAIMED);
1256 atomic_set_int(&vp->v_refcnt, VREF_FINALIZE);
1259 if (verbose_reclaims) {
1260 if ((ncp = TAILQ_FIRST(&vp->v_namecache)) != NULL)
1261 kprintf("Debug: reclaim %p %s\n", vp, ncp->nc_name);
1265 * Scrap the vfs cache
1267 while (cache_inval_vp(vp, 0) != 0) {
1268 kprintf("Warning: vnode %p clean/cache_resolution "
1269 "race detected\n", vp);
1270 tsleep(vp, 0, "vclninv", 2);
1274 * Check to see if the vnode is in use. If so we have to reference it
1275 * before we clean it out so that its count cannot fall to zero and
1276 * generate a race against ourselves to recycle it.
1278 active = (VREFCNT(vp) > 0);
1281 * Clean out any buffers associated with the vnode and destroy its
1282 * object, if it has one.
1284 vinvalbuf(vp, V_SAVE, 0, 0);
1287 * If purging an active vnode (typically during a forced unmount
1288 * or reboot), it must be closed and deactivated before being
1289 * reclaimed. This isn't really all that safe, but what can
1292 * Note that neither of these routines unlocks the vnode.
1294 if (active && (flags & DOCLOSE)) {
1295 while ((n = vp->v_opencount) != 0) {
1296 if (vp->v_writecount)
1297 VOP_CLOSE(vp, FWRITE|FNONBLOCK, NULL);
1299 VOP_CLOSE(vp, FNONBLOCK, NULL);
1300 if (vp->v_opencount == n) {
1301 kprintf("Warning: unable to force-close"
1309 * If the vnode has not been deactivated, deactivated it. Deactivation
1310 * can create new buffers and VM pages so we have to call vinvalbuf()
1311 * again to make sure they all get flushed.
1313 * This can occur if a file with a link count of 0 needs to be
1316 * If the vnode is already dead don't try to deactivate it.
1318 if ((vp->v_flag & VINACTIVE) == 0) {
1319 vsetflags(vp, VINACTIVE);
1322 vinvalbuf(vp, V_SAVE, 0, 0);
1326 * If the vnode has an object, destroy it.
1328 while ((object = vp->v_object) != NULL) {
1329 vm_object_hold(object);
1330 if (object == vp->v_object)
1332 vm_object_drop(object);
1335 if (object != NULL) {
1336 if (object->ref_count == 0) {
1337 if ((object->flags & OBJ_DEAD) == 0)
1338 vm_object_terminate(object);
1339 vm_object_drop(object);
1340 vclrflags(vp, VOBJBUF);
1342 vm_pager_deallocate(object);
1343 vclrflags(vp, VOBJBUF);
1344 vm_object_drop(object);
1347 KKASSERT((vp->v_flag & VOBJBUF) == 0);
1349 if (vp->v_flag & VOBJDIRTY)
1353 * Reclaim the vnode if not already dead.
1355 if (vp->v_mount && VOP_RECLAIM(vp))
1356 panic("vclean: cannot reclaim");
1359 * Done with purge, notify sleepers of the grim news.
1361 vp->v_ops = &dead_vnode_vops_p;
1366 * If we are destroying an active vnode, reactivate it now that
1367 * we have reassociated it with deadfs. This prevents the system
1368 * from crashing on the vnode due to it being unexpectedly marked
1369 * as inactive or reclaimed.
1371 if (active && (flags & DOCLOSE)) {
1372 vclrflags(vp, VINACTIVE | VRECLAIMED);
1377 * Eliminate all activity associated with the requested vnode
1378 * and with all vnodes aliased to the requested vnode.
1380 * The vnode must be referenced but should not be locked.
1383 vrevoke(struct vnode *vp, struct ucred *cred)
1391 * If the vnode has a device association, scrap all vnodes associated
1392 * with the device. Don't let the device disappear on us while we
1393 * are scrapping the vnodes.
1395 * The passed vp will probably show up in the list, do not VX lock
1398 * Releasing the vnode's rdev here can mess up specfs's call to
1399 * device close, so don't do it. The vnode has been disassociated
1400 * and the device will be closed after the last ref on the related
1401 * fp goes away (if not still open by e.g. the kernel).
1403 if (vp->v_type != VCHR) {
1404 error = fdrevoke(vp, DTYPE_VNODE, cred);
1407 if ((dev = vp->v_rdev) == NULL) {
1411 lwkt_gettoken(&spechash_token);
1414 vqn = SLIST_FIRST(&dev->si_hlist);
1417 while ((vq = vqn) != NULL) {
1418 if (VREFCNT(vq) > 0) {
1420 fdrevoke(vq, DTYPE_VNODE, cred);
1421 /*v_release_rdev(vq);*/
1423 if (vq->v_rdev != dev) {
1428 vqn = SLIST_NEXT(vq, v_cdevnext);
1433 lwkt_reltoken(&spechash_token);
1440 * This is called when the object underlying a vnode is being destroyed,
1441 * such as in a remove(). Try to recycle the vnode immediately if the
1442 * only active reference is our reference.
1444 * Directory vnodes in the namecache with children cannot be immediately
1445 * recycled because numerous VOP_N*() ops require them to be stable.
1447 * To avoid recursive recycling from VOP_INACTIVE implemenetations this
1448 * function is a NOP if VRECLAIMED is already set.
1451 vrecycle(struct vnode *vp)
1453 if (VREFCNT(vp) <= 1 && (vp->v_flag & VRECLAIMED) == 0) {
1454 if (cache_inval_vp_nonblock(vp))
1463 * Return the maximum I/O size allowed for strategy calls on VP.
1465 * If vp is VCHR or VBLK we dive the device, otherwise we use
1466 * the vp's mount info.
1468 * The returned value is clamped at MAXPHYS as most callers cannot use
1469 * buffers larger than that size.
1472 vmaxiosize(struct vnode *vp)
1476 if (vp->v_type == VBLK || vp->v_type == VCHR)
1477 maxiosize = vp->v_rdev->si_iosize_max;
1479 maxiosize = vp->v_mount->mnt_iosize_max;
1481 if (maxiosize > MAXPHYS)
1482 maxiosize = MAXPHYS;
1487 * Eliminate all activity associated with a vnode in preparation for
1490 * The vnode must be VX locked and refd and will remain VX locked and refd
1491 * on return. This routine may be called with the vnode in any state, as
1492 * long as it is VX locked. The vnode will be cleaned out and marked
1493 * VRECLAIMED but will not actually be reused until all existing refs and
1496 * NOTE: This routine may be called on a vnode which has not yet been
1497 * already been deactivated (VOP_INACTIVE), or on a vnode which has
1498 * already been reclaimed.
1500 * This routine is not responsible for placing us back on the freelist.
1501 * Instead, it happens automatically when the caller releases the VX lock
1502 * (assuming there aren't any other references).
1505 vgone_vxlocked(struct vnode *vp)
1508 * assert that the VX lock is held. This is an absolute requirement
1509 * now for vgone_vxlocked() to be called.
1511 KKASSERT(lockinuse(&vp->v_lock));
1514 * Clean out the filesystem specific data and set the VRECLAIMED
1515 * bit. Also deactivate the vnode if necessary.
1517 * The vnode should have automatically been removed from the syncer
1518 * list as syncer/dirty flags cleared during the cleaning.
1520 vclean_vxlocked(vp, DOCLOSE);
1523 * Normally panic if the vnode is still dirty, unless we are doing
1524 * a forced unmount (tmpfs typically).
1526 if (vp->v_flag & VONWORKLST) {
1527 if (vp->v_mount->mnt_kern_flag & MNTK_UNMOUNTF) {
1529 vn_syncer_remove(vp, 1);
1531 panic("vp %p still dirty in vgone after flush", vp);
1536 * Delete from old mount point vnode list, if on one.
1538 if (vp->v_mount != NULL) {
1539 KKASSERT(vp->v_data == NULL);
1540 insmntque(vp, NULL);
1544 * If special device, remove it from special device alias list
1545 * if it is on one. This should normally only occur if a vnode is
1546 * being revoked as the device should otherwise have been released
1549 if ((vp->v_type == VBLK || vp->v_type == VCHR) && vp->v_rdev != NULL) {
1560 * Calculate the total number of references to a special device. This
1561 * routine may only be called for VBLK and VCHR vnodes since v_rdev is
1562 * an overloaded field. Since dev_from_devid() can now return NULL, we
1563 * have to check for a NULL v_rdev.
1566 count_dev(cdev_t dev)
1571 if (SLIST_FIRST(&dev->si_hlist)) {
1572 lwkt_gettoken(&spechash_token);
1573 SLIST_FOREACH(vp, &dev->si_hlist, v_cdevnext) {
1574 count += vp->v_opencount;
1576 lwkt_reltoken(&spechash_token);
1582 vcount(struct vnode *vp)
1584 if (vp->v_rdev == NULL)
1586 return(count_dev(vp->v_rdev));
1590 * Initialize VMIO for a vnode. This routine MUST be called before a
1591 * VFS can issue buffer cache ops on a vnode. It is typically called
1592 * when a vnode is initialized from its inode.
1595 vinitvmio(struct vnode *vp, off_t filesize, int blksize, int boff)
1600 object = vp->v_object;
1602 vm_object_hold(object);
1603 KKASSERT(vp->v_object == object);
1606 if (object == NULL) {
1607 object = vnode_pager_alloc(vp, filesize, 0, 0, blksize, boff);
1610 * Dereference the reference we just created. This assumes
1611 * that the object is associated with the vp. Allow it to
1612 * have zero refs. It cannot be destroyed as long as it
1613 * is associated with the vnode.
1615 vm_object_hold(object);
1616 atomic_add_int(&object->ref_count, -1);
1619 KKASSERT((object->flags & OBJ_DEAD) == 0);
1621 KASSERT(vp->v_object != NULL, ("vinitvmio: NULL object"));
1622 vsetflags(vp, VOBJBUF);
1623 vm_object_drop(object);
1630 * Print out a description of a vnode.
1632 static char *typename[] =
1633 {"VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD"};
1636 vprint(char *label, struct vnode *vp)
1641 kprintf("%s: %p: ", label, (void *)vp);
1643 kprintf("%p: ", (void *)vp);
1644 kprintf("type %s, refcnt %08x, writecount %d, holdcnt %d,",
1645 typename[vp->v_type],
1646 vp->v_refcnt, vp->v_writecount, vp->v_auxrefs);
1648 if (vp->v_flag & VROOT)
1649 strcat(buf, "|VROOT");
1650 if (vp->v_flag & VPFSROOT)
1651 strcat(buf, "|VPFSROOT");
1652 if (vp->v_flag & VTEXT)
1653 strcat(buf, "|VTEXT");
1654 if (vp->v_flag & VSYSTEM)
1655 strcat(buf, "|VSYSTEM");
1656 if (vp->v_flag & VOBJBUF)
1657 strcat(buf, "|VOBJBUF");
1659 kprintf(" flags (%s)", &buf[1]);
1660 if (vp->v_data == NULL) {
1669 * Do the usual access checking.
1670 * file_mode, uid and gid are from the vnode in question,
1671 * while acc_mode and cred are from the VOP_ACCESS parameter list
1674 vaccess(enum vtype type, mode_t file_mode, uid_t uid, gid_t gid,
1675 mode_t acc_mode, struct ucred *cred)
1681 * Super-user always gets read/write access, but execute access depends
1682 * on at least one execute bit being set.
1684 if (priv_check_cred(cred, PRIV_ROOT, 0) == 0) {
1685 if ((acc_mode & VEXEC) && type != VDIR &&
1686 (file_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0)
1693 /* Otherwise, check the owner. */
1694 if (cred->cr_uid == uid) {
1695 if (acc_mode & VEXEC)
1697 if (acc_mode & VREAD)
1699 if (acc_mode & VWRITE)
1701 return ((file_mode & mask) == mask ? 0 : EACCES);
1704 /* Otherwise, check the groups. */
1705 ismember = groupmember(gid, cred);
1706 if (cred->cr_svgid == gid || ismember) {
1707 if (acc_mode & VEXEC)
1709 if (acc_mode & VREAD)
1711 if (acc_mode & VWRITE)
1713 return ((file_mode & mask) == mask ? 0 : EACCES);
1716 /* Otherwise, check everyone else. */
1717 if (acc_mode & VEXEC)
1719 if (acc_mode & VREAD)
1721 if (acc_mode & VWRITE)
1723 return ((file_mode & mask) == mask ? 0 : EACCES);
1727 #include <ddb/ddb.h>
1729 static int db_show_locked_vnodes(struct mount *mp, void *data);
1732 * List all of the locked vnodes in the system.
1733 * Called when debugging the kernel.
1735 DB_SHOW_COMMAND(lockedvnodes, lockedvnodes)
1737 kprintf("Locked vnodes\n");
1738 mountlist_scan(db_show_locked_vnodes, NULL,
1739 MNTSCAN_FORWARD|MNTSCAN_NOBUSY);
1743 db_show_locked_vnodes(struct mount *mp, void *data __unused)
1747 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
1748 if (vn_islocked(vp))
1756 * Top level filesystem related information gathering.
1758 static int sysctl_ovfs_conf (SYSCTL_HANDLER_ARGS);
1761 vfs_sysctl(SYSCTL_HANDLER_ARGS)
1763 int *name = (int *)arg1 - 1; /* XXX */
1764 u_int namelen = arg2 + 1; /* XXX */
1765 struct vfsconf *vfsp;
1768 #if 1 || defined(COMPAT_PRELITE2)
1769 /* Resolve ambiguity between VFS_VFSCONF and VFS_GENERIC. */
1771 return (sysctl_ovfs_conf(oidp, arg1, arg2, req));
1775 /* all sysctl names at this level are at least name and field */
1777 return (ENOTDIR); /* overloaded */
1778 if (name[0] != VFS_GENERIC) {
1779 vfsp = vfsconf_find_by_typenum(name[0]);
1781 return (EOPNOTSUPP);
1782 return ((*vfsp->vfc_vfsops->vfs_sysctl)(&name[1], namelen - 1,
1783 oldp, oldlenp, newp, newlen, p));
1787 case VFS_MAXTYPENUM:
1790 maxtypenum = vfsconf_get_maxtypenum();
1791 return (SYSCTL_OUT(req, &maxtypenum, sizeof(maxtypenum)));
1794 return (ENOTDIR); /* overloaded */
1795 vfsp = vfsconf_find_by_typenum(name[2]);
1797 return (EOPNOTSUPP);
1798 return (SYSCTL_OUT(req, vfsp, sizeof *vfsp));
1800 return (EOPNOTSUPP);
1803 SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RD, vfs_sysctl,
1804 "Generic filesystem");
1806 #if 1 || defined(COMPAT_PRELITE2)
1809 sysctl_ovfs_conf_iter(struct vfsconf *vfsp, void *data)
1812 struct ovfsconf ovfs;
1813 struct sysctl_req *req = (struct sysctl_req*) data;
1815 bzero(&ovfs, sizeof(ovfs));
1816 ovfs.vfc_vfsops = vfsp->vfc_vfsops; /* XXX used as flag */
1817 strcpy(ovfs.vfc_name, vfsp->vfc_name);
1818 ovfs.vfc_index = vfsp->vfc_typenum;
1819 ovfs.vfc_refcount = vfsp->vfc_refcount;
1820 ovfs.vfc_flags = vfsp->vfc_flags;
1821 error = SYSCTL_OUT(req, &ovfs, sizeof ovfs);
1823 return error; /* abort iteration with error code */
1825 return 0; /* continue iterating with next element */
1829 sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS)
1831 return vfsconf_each(sysctl_ovfs_conf_iter, (void*)req);
1834 #endif /* 1 || COMPAT_PRELITE2 */
1837 * Check to see if a filesystem is mounted on a block device.
1840 vfs_mountedon(struct vnode *vp)
1844 if ((dev = vp->v_rdev) == NULL) {
1845 /* if (vp->v_type != VBLK)
1846 dev = get_dev(vp->v_uminor, vp->v_umajor); */
1848 if (dev != NULL && dev->si_mountpoint)
1854 * Unmount all filesystems. The list is traversed in reverse order
1855 * of mounting to avoid dependencies.
1857 * We want the umountall to be able to break out of its loop if a
1858 * failure occurs, after scanning all possible mounts, so the callback
1859 * returns 0 on error.
1861 * NOTE: Do not call mountlist_remove(mp) on error any more, this will
1862 * confuse mountlist_scan()'s unbusy check.
1864 static int vfs_umountall_callback(struct mount *mp, void *data);
1867 vfs_unmountall(int halting)
1872 count = mountlist_scan(vfs_umountall_callback, &halting,
1873 MNTSCAN_REVERSE|MNTSCAN_NOBUSY);
1879 vfs_umountall_callback(struct mount *mp, void *data)
1882 int halting = *(int *)data;
1885 * NOTE: When halting, dounmount will disconnect but leave
1886 * certain mount points intact. e.g. devfs.
1888 error = dounmount(mp, MNT_FORCE, halting);
1890 kprintf("unmount of filesystem mounted from %s failed (",
1891 mp->mnt_stat.f_mntfromname);
1895 kprintf("%d)\n", error);
1903 * Checks the mount flags for parameter mp and put the names comma-separated
1904 * into a string buffer buf with a size limit specified by len.
1906 * It returns the number of bytes written into buf, and (*errorp) will be
1907 * set to 0, EINVAL (if passed length is 0), or ENOSPC (supplied buffer was
1908 * not large enough). The buffer will be 0-terminated if len was not 0.
1911 vfs_flagstostr(int flags, const struct mountctl_opt *optp,
1912 char *buf, size_t len, int *errorp)
1914 static const struct mountctl_opt optnames[] = {
1915 { MNT_RDONLY, "read-only" },
1916 { MNT_SYNCHRONOUS, "synchronous" },
1917 { MNT_NOEXEC, "noexec" },
1918 { MNT_NOSUID, "nosuid" },
1919 { MNT_NODEV, "nodev" },
1920 { MNT_AUTOMOUNTED, "automounted" },
1921 { MNT_ASYNC, "asynchronous" },
1922 { MNT_SUIDDIR, "suiddir" },
1923 { MNT_SOFTDEP, "soft-updates" },
1924 { MNT_NOSYMFOLLOW, "nosymfollow" },
1925 { MNT_TRIM, "trim" },
1926 { MNT_NOATIME, "noatime" },
1927 { MNT_NOCLUSTERR, "noclusterr" },
1928 { MNT_NOCLUSTERW, "noclusterw" },
1929 { MNT_EXRDONLY, "NFS read-only" },
1930 { MNT_EXPORTED, "NFS exported" },
1931 /* Remaining NFS flags could come here */
1932 { MNT_LOCAL, "local" },
1933 { MNT_QUOTA, "with-quotas" },
1934 /* { MNT_ROOTFS, "rootfs" }, */
1935 /* { MNT_IGNORE, "ignore" }, */
1945 bleft = len - 1; /* leave room for trailing \0 */
1948 * Checks the size of the string. If it contains
1949 * any data, then we will append the new flags to
1952 actsize = strlen(buf);
1956 /* Default flags if no flags passed */
1960 if (bleft < 0) { /* degenerate case, 0-length buffer */
1965 for (; flags && optp->o_opt; ++optp) {
1966 if ((flags & optp->o_opt) == 0)
1968 optlen = strlen(optp->o_name);
1969 if (bwritten || actsize > 0) {
1974 buf[bwritten++] = ',';
1975 buf[bwritten++] = ' ';
1978 if (bleft < optlen) {
1982 bcopy(optp->o_name, buf + bwritten, optlen);
1985 flags &= ~optp->o_opt;
1989 * Space already reserved for trailing \0
1996 * Build hash lists of net addresses and hang them off the mount point.
1997 * Called by ufs_mount() to set up the lists of export addresses.
2000 vfs_hang_addrlist(struct mount *mp, struct netexport *nep,
2001 const struct export_args *argp)
2004 struct radix_node_head *rnh;
2006 struct radix_node *rn;
2007 struct sockaddr *saddr, *smask = NULL;
2010 if (argp->ex_addrlen == 0) {
2011 if (mp->mnt_flag & MNT_DEFEXPORTED)
2013 np = &nep->ne_defexported;
2014 np->netc_exflags = argp->ex_flags;
2015 np->netc_anon = argp->ex_anon;
2016 np->netc_anon.cr_ref = 1;
2017 mp->mnt_flag |= MNT_DEFEXPORTED;
2021 if (argp->ex_addrlen < 0 || argp->ex_addrlen > MLEN)
2023 if (argp->ex_masklen < 0 || argp->ex_masklen > MLEN)
2026 i = sizeof(struct netcred) + argp->ex_addrlen + argp->ex_masklen;
2027 np = (struct netcred *)kmalloc(i, M_NETCRED, M_WAITOK | M_ZERO);
2028 saddr = (struct sockaddr *) (np + 1);
2029 if ((error = copyin(argp->ex_addr, (caddr_t) saddr, argp->ex_addrlen)))
2031 if (saddr->sa_len > argp->ex_addrlen)
2032 saddr->sa_len = argp->ex_addrlen;
2033 if (argp->ex_masklen) {
2034 smask = (struct sockaddr *)((caddr_t)saddr + argp->ex_addrlen);
2035 error = copyin(argp->ex_mask, (caddr_t)smask, argp->ex_masklen);
2038 if (smask->sa_len > argp->ex_masklen)
2039 smask->sa_len = argp->ex_masklen;
2042 if (nep->ne_maskhead == NULL) {
2043 if (!rn_inithead((void **)&nep->ne_maskhead, NULL, 0)) {
2048 if ((rnh = vfs_create_addrlist_af(saddr->sa_family, nep)) == NULL) {
2052 rn = (*rnh->rnh_addaddr)((char *)saddr, (char *)smask, rnh,
2055 if (rn == NULL || np != (struct netcred *)rn) { /* already exists */
2059 np->netc_exflags = argp->ex_flags;
2060 np->netc_anon = argp->ex_anon;
2061 np->netc_anon.cr_ref = 1;
2065 kfree(np, M_NETCRED);
2070 * Free netcred structures installed in the netexport
2073 vfs_free_netcred(struct radix_node *rn, void *w)
2075 struct radix_node_head *rnh = (struct radix_node_head *)w;
2077 (*rnh->rnh_deladdr) (rn->rn_key, rn->rn_mask, rnh);
2078 kfree(rn, M_NETCRED);
2084 * callback to free an element of the mask table installed in the
2085 * netexport. These may be created indirectly and are not netcred
2089 vfs_free_netcred_mask(struct radix_node *rn, void *w)
2091 struct radix_node_head *rnh = (struct radix_node_head *)w;
2093 (*rnh->rnh_deladdr) (rn->rn_key, rn->rn_mask, rnh);
2094 kfree(rn, M_RTABLE);
2099 static struct radix_node_head *
2100 vfs_create_addrlist_af(int af, struct netexport *nep)
2102 struct radix_node_head *rnh = NULL;
2103 #if defined(INET) || defined(INET6)
2104 struct radix_node_head *maskhead = nep->ne_maskhead;
2108 NE_ASSERT_LOCKED(nep);
2109 #if defined(INET) || defined(INET6)
2110 KKASSERT(maskhead != NULL);
2115 if ((rnh = nep->ne_inethead) == NULL) {
2116 off = offsetof(struct sockaddr_in, sin_addr) << 3;
2117 if (!rn_inithead((void **)&rnh, maskhead, off))
2119 nep->ne_inethead = rnh;
2125 if ((rnh = nep->ne_inet6head) == NULL) {
2126 off = offsetof(struct sockaddr_in6, sin6_addr) << 3;
2127 if (!rn_inithead((void **)&rnh, maskhead, off))
2129 nep->ne_inet6head = rnh;
2138 * helper function for freeing netcred elements
2141 vfs_free_addrlist_af(struct radix_node_head **prnh)
2143 struct radix_node_head *rnh = *prnh;
2145 (*rnh->rnh_walktree) (rnh, vfs_free_netcred, rnh);
2146 kfree(rnh, M_RTABLE);
2151 * helper function for freeing mask elements
2154 vfs_free_addrlist_masks(struct radix_node_head **prnh)
2156 struct radix_node_head *rnh = *prnh;
2158 (*rnh->rnh_walktree) (rnh, vfs_free_netcred_mask, rnh);
2159 kfree(rnh, M_RTABLE);
2164 * Free the net address hash lists that are hanging off the mount points.
2167 vfs_free_addrlist(struct netexport *nep)
2170 if (nep->ne_inethead != NULL)
2171 vfs_free_addrlist_af(&nep->ne_inethead);
2172 if (nep->ne_inet6head != NULL)
2173 vfs_free_addrlist_af(&nep->ne_inet6head);
2174 if (nep->ne_maskhead)
2175 vfs_free_addrlist_masks(&nep->ne_maskhead);
2180 vfs_export(struct mount *mp, struct netexport *nep,
2181 const struct export_args *argp)
2185 if (argp->ex_flags & MNT_DELEXPORT) {
2186 if (mp->mnt_flag & MNT_EXPUBLIC) {
2187 vfs_setpublicfs(NULL, NULL, NULL);
2188 mp->mnt_flag &= ~MNT_EXPUBLIC;
2190 vfs_free_addrlist(nep);
2191 mp->mnt_flag &= ~(MNT_EXPORTED | MNT_DEFEXPORTED);
2193 if (argp->ex_flags & MNT_EXPORTED) {
2194 if (argp->ex_flags & MNT_EXPUBLIC) {
2195 if ((error = vfs_setpublicfs(mp, nep, argp)) != 0)
2197 mp->mnt_flag |= MNT_EXPUBLIC;
2199 if ((error = vfs_hang_addrlist(mp, nep, argp)))
2201 mp->mnt_flag |= MNT_EXPORTED;
2208 * Set the publicly exported filesystem (WebNFS). Currently, only
2209 * one public filesystem is possible in the spec (RFC 2054 and 2055)
2212 vfs_setpublicfs(struct mount *mp, struct netexport *nep,
2213 const struct export_args *argp)
2220 * mp == NULL -> invalidate the current info, the FS is
2221 * no longer exported. May be called from either vfs_export
2222 * or unmount, so check if it hasn't already been done.
2225 if (nfs_pub.np_valid) {
2226 nfs_pub.np_valid = 0;
2227 if (nfs_pub.np_index != NULL) {
2228 kfree(nfs_pub.np_index, M_TEMP);
2229 nfs_pub.np_index = NULL;
2236 * Only one allowed at a time.
2238 if (nfs_pub.np_valid != 0 && mp != nfs_pub.np_mount)
2242 * Get real filehandle for root of exported FS.
2244 bzero((caddr_t)&nfs_pub.np_handle, sizeof(nfs_pub.np_handle));
2245 nfs_pub.np_handle.fh_fsid = mp->mnt_stat.f_fsid;
2247 if ((error = VFS_ROOT(mp, &rvp)))
2250 if ((error = VFS_VPTOFH(rvp, &nfs_pub.np_handle.fh_fid)))
2256 * If an indexfile was specified, pull it in.
2258 if (argp->ex_indexfile != NULL) {
2261 error = vn_get_namelen(rvp, &namelen);
2264 nfs_pub.np_index = kmalloc(namelen, M_TEMP, M_WAITOK);
2265 error = copyinstr(argp->ex_indexfile, nfs_pub.np_index,
2269 * Check for illegal filenames.
2271 for (cp = nfs_pub.np_index; *cp; cp++) {
2279 kfree(nfs_pub.np_index, M_TEMP);
2284 nfs_pub.np_mount = mp;
2285 nfs_pub.np_valid = 1;
2290 vfs_export_lookup(struct mount *mp, struct netexport *nep,
2291 struct sockaddr *nam)
2294 struct radix_node_head *rnh;
2295 struct sockaddr *saddr;
2298 if (mp->mnt_flag & MNT_EXPORTED) {
2300 * Lookup in the export list first.
2305 switch (saddr->sa_family) {
2308 rnh = nep->ne_inethead;
2313 rnh = nep->ne_inet6head;
2320 np = (struct netcred *)
2321 (*rnh->rnh_matchaddr)((char *)saddr,
2323 if (np && np->netc_rnodes->rn_flags & RNF_ROOT)
2329 * If no address match, use the default if it exists.
2331 if (np == NULL && mp->mnt_flag & MNT_DEFEXPORTED)
2332 np = &nep->ne_defexported;
2338 * perform msync on all vnodes under a mount point. The mount point must
2339 * be locked. This code is also responsible for lazy-freeing unreferenced
2340 * vnodes whos VM objects no longer contain pages.
2342 * NOTE: MNT_WAIT still skips vnodes in the VXLOCK state.
2344 * NOTE: XXX VOP_PUTPAGES and friends requires that the vnode be locked,
2345 * but vnode_pager_putpages() doesn't lock the vnode. We have to do it
2346 * way up in this high level function.
2348 static int vfs_msync_scan1(struct mount *mp, struct vnode *vp, void *data);
2349 static int vfs_msync_scan2(struct mount *mp, struct vnode *vp, void *data);
2352 vfs_msync(struct mount *mp, int flags)
2357 * tmpfs sets this flag to prevent msync(), sync, and the
2358 * filesystem periodic syncer from trying to flush VM pages
2359 * to swap. Only pure memory pressure flushes tmpfs VM pages
2362 if (mp->mnt_kern_flag & MNTK_NOMSYNC)
2366 * Ok, scan the vnodes for work. If the filesystem is using the
2367 * syncer thread feature we can use vsyncscan() instead of
2368 * vmntvnodescan(), which is much faster.
2370 vmsc_flags = VMSC_GETVP;
2371 if (flags != MNT_WAIT)
2372 vmsc_flags |= VMSC_NOWAIT;
2374 if (mp->mnt_kern_flag & MNTK_THR_SYNC) {
2375 vsyncscan(mp, vmsc_flags, vfs_msync_scan2,
2376 (void *)(intptr_t)flags);
2378 vmntvnodescan(mp, vmsc_flags,
2379 vfs_msync_scan1, vfs_msync_scan2,
2380 (void *)(intptr_t)flags);
2385 * scan1 is a fast pre-check. There could be hundreds of thousands of
2386 * vnodes, we cannot afford to do anything heavy weight until we have a
2387 * fairly good indication that there is work to do.
2391 vfs_msync_scan1(struct mount *mp, struct vnode *vp, void *data)
2393 int flags = (int)(intptr_t)data;
2395 if ((vp->v_flag & VRECLAIMED) == 0) {
2396 if (vp->v_auxrefs == 0 && VREFCNT(vp) <= 0 &&
2398 return(0); /* call scan2 */
2400 if ((mp->mnt_flag & MNT_RDONLY) == 0 &&
2401 (vp->v_flag & VOBJDIRTY) &&
2402 (flags == MNT_WAIT || vn_islocked(vp) == 0)) {
2403 return(0); /* call scan2 */
2408 * do not call scan2, continue the loop
2414 * This callback is handed a locked vnode.
2418 vfs_msync_scan2(struct mount *mp, struct vnode *vp, void *data)
2421 int flags = (int)(intptr_t)data;
2424 if (vp->v_flag & VRECLAIMED)
2427 if ((mp->mnt_flag & MNT_RDONLY) == 0 && (vp->v_flag & VOBJDIRTY)) {
2428 if ((obj = vp->v_object) != NULL) {
2429 if (flags == MNT_WAIT) {
2431 * VFS_MSYNC is called with MNT_WAIT when
2434 opcflags = OBJPC_SYNC;
2435 } else if (vp->v_writecount || obj->ref_count) {
2437 * VFS_MSYNC is otherwise called via the
2438 * periodic filesystem sync or the 'sync'
2439 * command. Honor MADV_NOSYNC / MAP_NOSYNC
2440 * if the file is open for writing or memory
2441 * mapped. Pages flagged PG_NOSYNC will not
2442 * be automatically flushed at this time.
2444 * The obj->ref_count test is not perfect
2445 * since temporary refs may be present, but
2446 * the periodic filesystem sync will ultimately
2447 * catch it if the file is not open and not
2450 opcflags = OBJPC_NOSYNC;
2453 * If the file is no longer open for writing
2454 * and also no longer mapped, do not honor
2455 * MAP_NOSYNC. That is, fully synchronize
2458 * This still occurs on the periodic fs sync,
2459 * so frontend programs which turn the file
2460 * over quickly enough can still avoid the
2461 * sync, but ultimately we do want to flush
2462 * even MADV_NOSYNC pages once it is no longer
2463 * mapped or open for writing.
2467 vm_object_page_clean(obj, 0, 0, opcflags);
2474 * Wake up anyone interested in vp because it is being revoked.
2477 vn_gone(struct vnode *vp)
2479 lwkt_gettoken(&vp->v_token);
2480 KNOTE(&vp->v_pollinfo.vpi_kqinfo.ki_note, NOTE_REVOKE);
2481 lwkt_reltoken(&vp->v_token);
2485 * extract the cdev_t from a VBLK or VCHR. The vnode must have been opened
2486 * (or v_rdev might be NULL).
2489 vn_todev(struct vnode *vp)
2491 if (vp->v_type != VBLK && vp->v_type != VCHR)
2493 KKASSERT(vp->v_rdev != NULL);
2494 return (vp->v_rdev);
2498 * Check if vnode represents a disk device. The vnode does not need to be
2504 vn_isdisk(struct vnode *vp, int *errp)
2508 if (vp->v_type != VCHR) {
2521 if (dev_is_good(dev) == 0) {
2526 if ((dev_dflags(dev) & D_DISK) == 0) {
2537 vn_get_namelen(struct vnode *vp, int *namelen)
2540 register_t retval[2];
2542 error = VOP_PATHCONF(vp, _PC_NAME_MAX, retval);
2545 *namelen = (int)retval[0];
2550 vop_write_dirent(int *error, struct uio *uio, ino_t d_ino, uint8_t d_type,
2551 uint16_t d_namlen, const char *d_name)
2556 len = _DIRENT_RECLEN(d_namlen);
2557 if (len > uio->uio_resid)
2560 dp = kmalloc(len, M_TEMP, M_WAITOK | M_ZERO);
2563 dp->d_namlen = d_namlen;
2564 dp->d_type = d_type;
2565 bcopy(d_name, dp->d_name, d_namlen);
2567 *error = uiomove((caddr_t)dp, len, uio);
2575 vn_mark_atime(struct vnode *vp, struct thread *td)
2577 struct proc *p = td->td_proc;
2578 struct ucred *cred = p ? p->p_ucred : proc0.p_ucred;
2580 if ((vp->v_mount->mnt_flag & (MNT_NOATIME | MNT_RDONLY)) == 0) {
2581 VOP_MARKATIME(vp, cred);
2586 * Calculate the number of entries in an inode-related chained hash table.
2587 * With today's memory sizes, maxvnodes can wind up being a very large
2588 * number. There is no reason to waste memory, so tolerate some stacking.
2591 vfs_inodehashsize(void)
2596 while (hsize < maxvnodes)
2598 while (hsize > maxvnodes * 2)
2599 hsize >>= 1; /* nominal 2x stacking */
2601 if (maxvnodes > 1024 * 1024)
2602 hsize >>= 1; /* nominal 8x stacking */
2604 if (maxvnodes > 128 * 1024)
2605 hsize >>= 1; /* nominal 4x stacking */
2618 #define SETHIGH(q, h) { \
2621 tmp.val[_QUAD_HIGHWORD] = (h); \
2624 #define SETLOW(q, l) { \
2627 tmp.val[_QUAD_LOWWORD] = (l); \
2632 init_va_filerev(void)
2637 getmicrouptime(&tv);
2638 SETHIGH(ret, tv.tv_sec);
2639 SETLOW(ret, tv.tv_usec * 4294);