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>
49 #include <sys/dirent.h>
50 #include <sys/eventhandler.h>
51 #include <sys/fcntl.h>
53 #include <sys/kernel.h>
54 #include <sys/kthread.h>
55 #include <sys/malloc.h>
57 #include <sys/mount.h>
60 #include <sys/reboot.h>
61 #include <sys/socket.h>
63 #include <sys/sysctl.h>
64 #include <sys/syslog.h>
65 #include <sys/unistd.h>
66 #include <sys/vmmeter.h>
67 #include <sys/vnode.h>
69 #include <machine/limits.h>
72 #include <vm/vm_object.h>
73 #include <vm/vm_extern.h>
74 #include <vm/vm_kern.h>
76 #include <vm/vm_map.h>
77 #include <vm/vm_page.h>
78 #include <vm/vm_pager.h>
79 #include <vm/vnode_pager.h>
80 #include <vm/vm_zone.h>
83 #include <sys/mplock2.h>
84 #include <vm/vm_page2.h>
86 #include <netinet/in.h>
88 static MALLOC_DEFINE(M_NETCRED, "Export Host", "Export host address structure");
90 __read_mostly int numvnodes;
91 SYSCTL_INT(_debug, OID_AUTO, numvnodes, CTLFLAG_RD, &numvnodes, 0,
92 "Number of vnodes allocated");
93 __read_mostly int verbose_reclaims;
94 SYSCTL_INT(_debug, OID_AUTO, verbose_reclaims, CTLFLAG_RD, &verbose_reclaims, 0,
95 "Output filename of reclaimed vnode(s)");
97 __read_mostly enum vtype iftovt_tab[16] = {
98 VNON, VFIFO, VCHR, VNON, VDIR, VNON, VBLK, VNON,
99 VREG, VNON, VLNK, VNON, VSOCK, VNON, VNON, VBAD,
101 __read_mostly int vttoif_tab[9] = {
102 0, S_IFREG, S_IFDIR, S_IFBLK, S_IFCHR, S_IFLNK,
103 S_IFSOCK, S_IFIFO, S_IFMT,
106 static int reassignbufcalls;
107 SYSCTL_INT(_vfs, OID_AUTO, reassignbufcalls, CTLFLAG_RW, &reassignbufcalls,
108 0, "Number of times buffers have been reassigned to the proper list");
110 __read_mostly static int check_buf_overlap = 2; /* invasive check */
111 SYSCTL_INT(_vfs, OID_AUTO, check_buf_overlap, CTLFLAG_RW, &check_buf_overlap,
112 0, "Enable overlapping buffer checks");
114 int nfs_mount_type = -1;
115 static struct lwkt_token spechash_token;
116 struct nfs_public nfs_pub; /* publicly exported FS */
118 __read_mostly int maxvnodes;
119 SYSCTL_INT(_kern, KERN_MAXVNODES, maxvnodes, CTLFLAG_RW,
120 &maxvnodes, 0, "Maximum number of vnodes");
122 static struct radix_node_head *vfs_create_addrlist_af(int af,
123 struct netexport *nep);
124 static void vfs_free_addrlist (struct netexport *nep);
125 static int vfs_free_netcred (struct radix_node *rn, void *w);
126 static void vfs_free_addrlist_af (struct radix_node_head **prnh);
127 static int vfs_hang_addrlist (struct mount *mp, struct netexport *nep,
128 const struct export_args *argp);
130 __read_mostly int prtactive = 0; /* 1 => print out reclaim of active vnodes */
133 * Red black tree functions
135 static int rb_buf_compare(struct buf *b1, struct buf *b2);
136 RB_GENERATE2(buf_rb_tree, buf, b_rbnode, rb_buf_compare, off_t, b_loffset);
137 RB_GENERATE2(buf_rb_hash, buf, b_rbhash, rb_buf_compare, off_t, b_loffset);
140 rb_buf_compare(struct buf *b1, struct buf *b2)
142 if (b1->b_loffset < b2->b_loffset)
144 if (b1->b_loffset > b2->b_loffset)
150 * Initialize the vnode management data structures.
152 * Called from vfsinit()
154 #define MAXVNBREAKMEM (1L * 1024 * 1024 * 1024)
155 #define MINVNODES 2000
156 #define MAXVNODES 4000000
161 int factor1; /* Limit based on ram (x 2 above 1GB) */
162 int factor2; /* Limit based on available KVM */
166 * Size maxvnodes to available memory. Size significantly
167 * smaller on low-memory systems (calculations for the first
168 * 1GB of ram), and pump it up a bit when free memory is
171 * The general minimum is maxproc * 8 (we want someone pushing
172 * up maxproc a lot to also get more vnodes). Usually maxproc
173 * does not affect this calculation.
175 * There isn't much of a point allowing maxvnodes to exceed a
176 * few million as our modern filesystems cache pages in the
177 * underlying block device and not so much hanging off of VM
180 factor1 = 50 * (sizeof(struct vm_object) + sizeof(struct vnode));
181 factor2 = 30 * (sizeof(struct vm_object) + sizeof(struct vnode));
183 freemem = (int64_t)vmstats.v_page_count * PAGE_SIZE;
185 maxvnodes = freemem / factor1;
186 if (freemem > MAXVNBREAKMEM)
187 maxvnodes += (freemem - MAXVNBREAKMEM) / factor1;
188 maxvnodes = imax(maxvnodes, maxproc * 8);
189 maxvnodes = imin(maxvnodes, KvaSize / factor2);
190 maxvnodes = imin(maxvnodes, MAXVNODES);
191 maxvnodes = imax(maxvnodes, MINVNODES);
193 lwkt_token_init(&spechash_token, "spechash");
197 * Knob to control the precision of file timestamps:
199 * 0 = seconds only; nanoseconds zeroed.
200 * 1 = seconds and nanoseconds, accurate within 1/HZ.
201 * 2 = seconds and nanoseconds, truncated to microseconds.
202 * >=3 = seconds and nanoseconds, maximum precision.
204 enum { TSP_SEC, TSP_HZ, TSP_USEC, TSP_NSEC };
206 __read_mostly static int timestamp_precision = TSP_SEC;
207 SYSCTL_INT(_vfs, OID_AUTO, timestamp_precision, CTLFLAG_RW,
208 ×tamp_precision, 0, "Precision of file timestamps");
211 * Get a current timestamp.
216 vfs_timestamp(struct timespec *tsp)
220 switch (timestamp_precision) {
222 tsp->tv_sec = time_second;
230 TIMEVAL_TO_TIMESPEC(&tv, tsp);
240 * Set vnode attributes to VNOVAL
243 vattr_null(struct vattr *vap)
246 vap->va_size = VNOVAL;
247 vap->va_bytes = VNOVAL;
248 vap->va_mode = VNOVAL;
249 vap->va_nlink = VNOVAL;
250 vap->va_uid = VNOVAL;
251 vap->va_gid = VNOVAL;
252 vap->va_fsid = VNOVAL;
253 vap->va_fileid = VNOVAL;
254 vap->va_blocksize = VNOVAL;
255 vap->va_rmajor = VNOVAL;
256 vap->va_rminor = VNOVAL;
257 vap->va_atime.tv_sec = VNOVAL;
258 vap->va_atime.tv_nsec = VNOVAL;
259 vap->va_mtime.tv_sec = VNOVAL;
260 vap->va_mtime.tv_nsec = VNOVAL;
261 vap->va_ctime.tv_sec = VNOVAL;
262 vap->va_ctime.tv_nsec = VNOVAL;
263 vap->va_flags = VNOVAL;
264 vap->va_gen = VNOVAL;
266 /* va_*_uuid fields are only valid if related flags are set */
270 * Flush out and invalidate all buffers associated with a vnode.
274 static int vinvalbuf_bp(struct buf *bp, void *data);
276 struct vinvalbuf_bp_info {
285 vinvalbuf(struct vnode *vp, int flags, int slpflag, int slptimeo)
287 struct vinvalbuf_bp_info info;
291 lwkt_gettoken(&vp->v_token);
294 * If we are being asked to save, call fsync to ensure that the inode
297 if (flags & V_SAVE) {
298 error = bio_track_wait(&vp->v_track_write, slpflag, slptimeo);
301 if (!RB_EMPTY(&vp->v_rbdirty_tree)) {
302 if ((error = VOP_FSYNC(vp, MNT_WAIT, 0)) != 0)
306 * Dirty bufs may be left or generated via races
307 * in circumstances where vinvalbuf() is called on
308 * a vnode not undergoing reclamation. Only
309 * panic if we are trying to reclaim the vnode.
311 if ((vp->v_flag & VRECLAIMED) &&
312 (bio_track_active(&vp->v_track_write) ||
313 !RB_EMPTY(&vp->v_rbdirty_tree))) {
314 panic("vinvalbuf: dirty bufs");
319 info.slptimeo = slptimeo;
320 info.lkflags = LK_EXCLUSIVE | LK_SLEEPFAIL;
321 if (slpflag & PCATCH)
322 info.lkflags |= LK_PCATCH;
327 * Flush the buffer cache until nothing is left, wait for all I/O
328 * to complete. At least one pass is required. We might block
329 * in the pip code so we have to re-check. Order is important.
335 if (!RB_EMPTY(&vp->v_rbclean_tree)) {
337 error = RB_SCAN(buf_rb_tree, &vp->v_rbclean_tree,
338 NULL, vinvalbuf_bp, &info);
340 if (!RB_EMPTY(&vp->v_rbdirty_tree)) {
342 error = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree,
343 NULL, vinvalbuf_bp, &info);
347 * Wait for I/O completion.
349 bio_track_wait(&vp->v_track_write, 0, 0);
350 if ((object = vp->v_object) != NULL)
351 refcount_wait(&object->paging_in_progress, "vnvlbx");
352 } while (bio_track_active(&vp->v_track_write) ||
353 !RB_EMPTY(&vp->v_rbclean_tree) ||
354 !RB_EMPTY(&vp->v_rbdirty_tree));
357 * Destroy the copy in the VM cache, too.
359 if ((object = vp->v_object) != NULL) {
360 vm_object_page_remove(object, 0, 0,
361 (flags & V_SAVE) ? TRUE : FALSE);
364 if (!RB_EMPTY(&vp->v_rbdirty_tree) || !RB_EMPTY(&vp->v_rbclean_tree))
365 panic("vinvalbuf: flush failed");
366 if (!RB_EMPTY(&vp->v_rbhash_tree))
367 panic("vinvalbuf: flush failed, buffers still present");
370 lwkt_reltoken(&vp->v_token);
375 vinvalbuf_bp(struct buf *bp, void *data)
377 struct vinvalbuf_bp_info *info = data;
380 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
381 atomic_add_int(&bp->b_refs, 1);
382 error = BUF_TIMELOCK(bp, info->lkflags,
383 "vinvalbuf", info->slptimeo);
384 atomic_subtract_int(&bp->b_refs, 1);
393 KKASSERT(bp->b_vp == info->vp);
396 * Must check clean/dirty status after successfully locking as
399 if ((info->clean && (bp->b_flags & B_DELWRI)) ||
400 (info->clean == 0 && (bp->b_flags & B_DELWRI) == 0)) {
406 * NOTE: NO B_LOCKED CHECK. Also no buf_checkwrite()
407 * check. This code will write out the buffer, period.
410 if (((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI) &&
411 (info->flags & V_SAVE)) {
413 } else if (info->flags & V_SAVE) {
415 * Cannot set B_NOCACHE on a clean buffer as this will
416 * destroy the VM backing store which might actually
417 * be dirty (and unsynchronized).
419 bp->b_flags |= (B_INVAL | B_RELBUF);
422 bp->b_flags |= (B_INVAL | B_NOCACHE | B_RELBUF);
429 * Truncate a file's buffer and pages to a specified length. This
430 * is in lieu of the old vinvalbuf mechanism, which performed unneeded
433 * The vnode must be locked.
435 static int vtruncbuf_bp_trunc_cmp(struct buf *bp, void *data);
436 static int vtruncbuf_bp_trunc(struct buf *bp, void *data);
437 static int vtruncbuf_bp_metasync_cmp(struct buf *bp, void *data);
438 static int vtruncbuf_bp_metasync(struct buf *bp, void *data);
440 struct vtruncbuf_info {
447 vtruncbuf(struct vnode *vp, off_t length, int blksize)
449 struct vtruncbuf_info info;
450 const char *filename;
454 * Round up to the *next* block, then destroy the buffers in question.
455 * Since we are only removing some of the buffers we must rely on the
456 * scan count to determine whether a loop is necessary.
458 if ((count = (int)(length % blksize)) != 0)
459 info.truncloffset = length + (blksize - count);
461 info.truncloffset = length;
464 lwkt_gettoken(&vp->v_token);
467 count = RB_SCAN(buf_rb_tree, &vp->v_rbclean_tree,
468 vtruncbuf_bp_trunc_cmp,
469 vtruncbuf_bp_trunc, &info);
471 count += RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree,
472 vtruncbuf_bp_trunc_cmp,
473 vtruncbuf_bp_trunc, &info);
477 * For safety, fsync any remaining metadata if the file is not being
478 * truncated to 0. Since the metadata does not represent the entire
479 * dirty list we have to rely on the hit count to ensure that we get
484 count = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree,
485 vtruncbuf_bp_metasync_cmp,
486 vtruncbuf_bp_metasync, &info);
491 * Clean out any left over VM backing store.
493 * It is possible to have in-progress I/O from buffers that were
494 * not part of the truncation. This should not happen if we
495 * are truncating to 0-length.
497 vnode_pager_setsize(vp, length);
498 bio_track_wait(&vp->v_track_write, 0, 0);
503 spin_lock(&vp->v_spin);
504 filename = TAILQ_FIRST(&vp->v_namecache) ?
505 TAILQ_FIRST(&vp->v_namecache)->nc_name : "?";
506 spin_unlock(&vp->v_spin);
509 * Make sure no buffers were instantiated while we were trying
510 * to clean out the remaining VM pages. This could occur due
511 * to busy dirty VM pages being flushed out to disk.
515 count = RB_SCAN(buf_rb_tree, &vp->v_rbclean_tree,
516 vtruncbuf_bp_trunc_cmp,
517 vtruncbuf_bp_trunc, &info);
519 count += RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree,
520 vtruncbuf_bp_trunc_cmp,
521 vtruncbuf_bp_trunc, &info);
523 kprintf("Warning: vtruncbuf(): Had to re-clean %d "
524 "left over buffers in %s\n", count, filename);
528 lwkt_reltoken(&vp->v_token);
534 * The callback buffer is beyond the new file EOF and must be destroyed.
535 * Note that the compare function must conform to the RB_SCAN's requirements.
539 vtruncbuf_bp_trunc_cmp(struct buf *bp, void *data)
541 struct vtruncbuf_info *info = data;
543 if (bp->b_loffset >= info->truncloffset)
550 vtruncbuf_bp_trunc(struct buf *bp, void *data)
552 struct vtruncbuf_info *info = data;
555 * Do not try to use a buffer we cannot immediately lock, but sleep
556 * anyway to prevent a livelock. The code will loop until all buffers
559 * We must always revalidate the buffer after locking it to deal
562 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
563 atomic_add_int(&bp->b_refs, 1);
564 if (BUF_LOCK(bp, LK_EXCLUSIVE|LK_SLEEPFAIL) == 0)
566 atomic_subtract_int(&bp->b_refs, 1);
567 } else if ((info->clean && (bp->b_flags & B_DELWRI)) ||
568 (info->clean == 0 && (bp->b_flags & B_DELWRI) == 0) ||
569 bp->b_vp != info->vp ||
570 vtruncbuf_bp_trunc_cmp(bp, data)) {
574 bp->b_flags |= (B_INVAL | B_RELBUF | B_NOCACHE);
581 * Fsync all meta-data after truncating a file to be non-zero. Only metadata
582 * blocks (with a negative loffset) are scanned.
583 * Note that the compare function must conform to the RB_SCAN's requirements.
586 vtruncbuf_bp_metasync_cmp(struct buf *bp, void *data __unused)
588 if (bp->b_loffset < 0)
594 vtruncbuf_bp_metasync(struct buf *bp, void *data)
596 struct vtruncbuf_info *info = data;
598 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
599 atomic_add_int(&bp->b_refs, 1);
600 if (BUF_LOCK(bp, LK_EXCLUSIVE|LK_SLEEPFAIL) == 0)
602 atomic_subtract_int(&bp->b_refs, 1);
603 } else if ((bp->b_flags & B_DELWRI) == 0 ||
604 bp->b_vp != info->vp ||
605 vtruncbuf_bp_metasync_cmp(bp, data)) {
609 if (bp->b_vp == info->vp)
618 * vfsync - implements a multipass fsync on a file which understands
619 * dependancies and meta-data. The passed vnode must be locked. The
620 * waitfor argument may be MNT_WAIT or MNT_NOWAIT, or MNT_LAZY.
622 * When fsyncing data asynchronously just do one consolidated pass starting
623 * with the most negative block number. This may not get all the data due
626 * When fsyncing data synchronously do a data pass, then a metadata pass,
627 * then do additional data+metadata passes to try to get all the data out.
629 * Caller must ref the vnode but does not have to lock it.
631 static int vfsync_wait_output(struct vnode *vp,
632 int (*waitoutput)(struct vnode *, struct thread *));
633 static int vfsync_dummy_cmp(struct buf *bp __unused, void *data __unused);
634 static int vfsync_data_only_cmp(struct buf *bp, void *data);
635 static int vfsync_meta_only_cmp(struct buf *bp, void *data);
636 static int vfsync_lazy_range_cmp(struct buf *bp, void *data);
637 static int vfsync_bp(struct buf *bp, void *data);
647 int (*checkdef)(struct buf *);
648 int (*cmpfunc)(struct buf *, void *);
652 vfsync(struct vnode *vp, int waitfor, int passes,
653 int (*checkdef)(struct buf *),
654 int (*waitoutput)(struct vnode *, struct thread *))
656 struct vfsync_info info;
659 bzero(&info, sizeof(info));
661 if ((info.checkdef = checkdef) == NULL)
664 lwkt_gettoken(&vp->v_token);
667 case MNT_LAZY | MNT_NOWAIT:
670 * Lazy (filesystem syncer typ) Asynchronous plus limit the
671 * number of data (not meta) pages we try to flush to 1MB.
672 * A non-zero return means that lazy limit was reached.
674 info.lazylimit = 1024 * 1024;
676 info.cmpfunc = vfsync_lazy_range_cmp;
677 error = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree,
678 vfsync_lazy_range_cmp, vfsync_bp, &info);
679 info.cmpfunc = vfsync_meta_only_cmp;
680 RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree,
681 vfsync_meta_only_cmp, vfsync_bp, &info);
684 else if (!RB_EMPTY(&vp->v_rbdirty_tree))
685 vn_syncer_add(vp, 1);
690 * Asynchronous. Do a data-only pass and a meta-only pass.
693 info.cmpfunc = vfsync_data_only_cmp;
694 RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, vfsync_data_only_cmp,
696 info.cmpfunc = vfsync_meta_only_cmp;
697 RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, vfsync_meta_only_cmp,
703 * Synchronous. Do a data-only pass, then a meta-data+data
704 * pass, then additional integrated passes to try to get
705 * all the dependancies flushed.
707 info.cmpfunc = vfsync_data_only_cmp;
709 RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, vfsync_data_only_cmp,
712 error = vfsync_wait_output(vp, waitoutput);
714 info.skippedbufs = 0;
715 info.cmpfunc = vfsync_dummy_cmp;
716 RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, NULL,
718 error = vfsync_wait_output(vp, waitoutput);
719 if (info.skippedbufs) {
720 kprintf("Warning: vfsync skipped %d dirty "
723 ((info.skippedbufs > 1) ? "s" : ""));
726 while (error == 0 && passes > 0 &&
727 !RB_EMPTY(&vp->v_rbdirty_tree)
729 info.skippedbufs = 0;
731 info.synchronous = 1;
734 info.cmpfunc = vfsync_dummy_cmp;
735 error = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, NULL,
741 error = vfsync_wait_output(vp, waitoutput);
742 if (info.skippedbufs && passes == 0) {
743 kprintf("Warning: vfsync skipped %d dirty "
744 "buf%s in final pass!\n",
746 ((info.skippedbufs > 1) ? "s" : ""));
751 * This case can occur normally because vnode lock might
754 if (!RB_EMPTY(&vp->v_rbdirty_tree))
755 kprintf("dirty bufs left after final pass\n");
759 lwkt_reltoken(&vp->v_token);
765 vfsync_wait_output(struct vnode *vp,
766 int (*waitoutput)(struct vnode *, struct thread *))
770 error = bio_track_wait(&vp->v_track_write, 0, 0);
772 error = waitoutput(vp, curthread);
777 vfsync_dummy_cmp(struct buf *bp __unused, void *data __unused)
783 vfsync_data_only_cmp(struct buf *bp, void *data)
785 if (bp->b_loffset < 0)
791 vfsync_meta_only_cmp(struct buf *bp, void *data)
793 if (bp->b_loffset < 0)
799 vfsync_lazy_range_cmp(struct buf *bp, void *data)
801 struct vfsync_info *info = data;
803 if (bp->b_loffset < info->vp->v_lazyw)
809 vfsync_bp(struct buf *bp, void *data)
811 struct vfsync_info *info = data;
812 struct vnode *vp = info->vp;
815 if (info->fastpass) {
817 * Ignore buffers that we cannot immediately lock.
819 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
821 * Removed BUF_TIMELOCK(..., 1), even a 1-tick
822 * delay can mess up performance
824 * Another reason is that during a dirty-buffer
825 * scan a clustered write can start I/O on buffers
826 * ahead of the scan, causing the scan to not
827 * get a lock here. Usually this means the write
828 * is already in progress so, in fact, we *want*
829 * to skip the buffer.
834 } else if (info->synchronous == 0) {
836 * Normal pass, give the buffer a little time to become
839 if (BUF_TIMELOCK(bp, LK_EXCLUSIVE, "bflst2", hz / 10)) {
845 * Synchronous pass, give the buffer a lot of time before
848 if (BUF_TIMELOCK(bp, LK_EXCLUSIVE, "bflst3", hz * 10)) {
855 * We must revalidate the buffer after locking.
857 if ((bp->b_flags & B_DELWRI) == 0 ||
858 bp->b_vp != info->vp ||
859 info->cmpfunc(bp, data)) {
865 * If syncdeps is not set we do not try to write buffers which have
868 if (!info->synchronous && info->syncdeps == 0 && info->checkdef(bp)) {
874 * B_NEEDCOMMIT (primarily used by NFS) is a state where the buffer
875 * has been written but an additional handshake with the device
876 * is required before we can dispose of the buffer. We have no idea
877 * how to do this so we have to skip these buffers.
879 if (bp->b_flags & B_NEEDCOMMIT) {
885 * Ask bioops if it is ok to sync. If not the VFS may have
886 * set B_LOCKED so we have to cycle the buffer.
888 if (LIST_FIRST(&bp->b_dep) != NULL && buf_checkwrite(bp)) {
894 if (info->synchronous) {
896 * Synchronous flush. An error may be returned and will
903 * Asynchronous flush. We use the error return to support
906 * In low-memory situations we revert to synchronous
907 * operation. This should theoretically prevent the I/O
908 * path from exhausting memory in a non-recoverable way.
910 vp->v_lazyw = bp->b_loffset;
912 if (vm_page_count_min(0)) {
914 info->lazycount += bp->b_bufsize;
918 info->lazycount += cluster_awrite(bp);
919 waitrunningbufspace();
920 /*vm_wait_nominal();*/
922 if (info->lazylimit && info->lazycount >= info->lazylimit)
931 * Associate a buffer with a vnode.
936 bgetvp(struct vnode *vp, struct buf *bp, int testsize)
938 KASSERT(bp->b_vp == NULL, ("bgetvp: not free"));
939 KKASSERT((bp->b_flags & (B_HASHED|B_DELWRI|B_VNCLEAN|B_VNDIRTY)) == 0);
942 * Insert onto list for new vnode.
944 lwkt_gettoken(&vp->v_token);
946 if (buf_rb_hash_RB_INSERT(&vp->v_rbhash_tree, bp)) {
947 lwkt_reltoken(&vp->v_token);
952 * Diagnostics (mainly for HAMMER debugging). Check for
953 * overlapping buffers.
955 if (check_buf_overlap) {
957 bx = buf_rb_hash_RB_PREV(bp);
959 if (bx->b_loffset + bx->b_bufsize > bp->b_loffset) {
960 kprintf("bgetvp: overlapl %016jx/%d %016jx "
962 (intmax_t)bx->b_loffset,
964 (intmax_t)bp->b_loffset,
966 if (check_buf_overlap > 1)
967 panic("bgetvp - overlapping buffer");
970 bx = buf_rb_hash_RB_NEXT(bp);
972 if (bp->b_loffset + testsize > bx->b_loffset) {
973 kprintf("bgetvp: overlapr %016jx/%d %016jx "
975 (intmax_t)bp->b_loffset,
977 (intmax_t)bx->b_loffset,
979 if (check_buf_overlap > 1)
980 panic("bgetvp - overlapping buffer");
985 bp->b_flags |= B_HASHED;
986 bp->b_flags |= B_VNCLEAN;
987 if (buf_rb_tree_RB_INSERT(&vp->v_rbclean_tree, bp))
988 panic("reassignbuf: dup lblk/clean vp %p bp %p", vp, bp);
990 lwkt_reltoken(&vp->v_token);
995 * Disassociate a buffer from a vnode.
1000 brelvp(struct buf *bp)
1004 KASSERT(bp->b_vp != NULL, ("brelvp: NULL"));
1007 * Delete from old vnode list, if on one.
1010 lwkt_gettoken(&vp->v_token);
1011 if (bp->b_flags & (B_VNDIRTY | B_VNCLEAN)) {
1012 if (bp->b_flags & B_VNDIRTY)
1013 buf_rb_tree_RB_REMOVE(&vp->v_rbdirty_tree, bp);
1015 buf_rb_tree_RB_REMOVE(&vp->v_rbclean_tree, bp);
1016 bp->b_flags &= ~(B_VNDIRTY | B_VNCLEAN);
1018 if (bp->b_flags & B_HASHED) {
1019 buf_rb_hash_RB_REMOVE(&vp->v_rbhash_tree, bp);
1020 bp->b_flags &= ~B_HASHED;
1024 * Only remove from synclist when no dirty buffers are left AND
1025 * the VFS has not flagged the vnode's inode as being dirty.
1027 if ((vp->v_flag & (VONWORKLST | VISDIRTY | VOBJDIRTY)) == VONWORKLST &&
1028 RB_EMPTY(&vp->v_rbdirty_tree)) {
1029 vn_syncer_remove(vp, 0);
1033 lwkt_reltoken(&vp->v_token);
1039 * Reassign the buffer to the proper clean/dirty list based on B_DELWRI.
1040 * This routine is called when the state of the B_DELWRI bit is changed.
1042 * Must be called with vp->v_token held.
1046 reassignbuf(struct buf *bp)
1048 struct vnode *vp = bp->b_vp;
1051 ASSERT_LWKT_TOKEN_HELD(&vp->v_token);
1055 * B_PAGING flagged buffers cannot be reassigned because their vp
1056 * is not fully linked in.
1058 if (bp->b_flags & B_PAGING)
1059 panic("cannot reassign paging buffer");
1061 if (bp->b_flags & B_DELWRI) {
1063 * Move to the dirty list, add the vnode to the worklist
1065 if (bp->b_flags & B_VNCLEAN) {
1066 buf_rb_tree_RB_REMOVE(&vp->v_rbclean_tree, bp);
1067 bp->b_flags &= ~B_VNCLEAN;
1069 if ((bp->b_flags & B_VNDIRTY) == 0) {
1070 if (buf_rb_tree_RB_INSERT(&vp->v_rbdirty_tree, bp)) {
1071 panic("reassignbuf: dup lblk vp %p bp %p",
1074 bp->b_flags |= B_VNDIRTY;
1076 if ((vp->v_flag & VONWORKLST) == 0) {
1077 switch (vp->v_type) {
1084 vp->v_rdev->si_mountpoint != NULL) {
1092 vn_syncer_add(vp, delay);
1096 * Move to the clean list, remove the vnode from the worklist
1097 * if no dirty blocks remain.
1099 if (bp->b_flags & B_VNDIRTY) {
1100 buf_rb_tree_RB_REMOVE(&vp->v_rbdirty_tree, bp);
1101 bp->b_flags &= ~B_VNDIRTY;
1103 if ((bp->b_flags & B_VNCLEAN) == 0) {
1104 if (buf_rb_tree_RB_INSERT(&vp->v_rbclean_tree, bp)) {
1105 panic("reassignbuf: dup lblk vp %p bp %p",
1108 bp->b_flags |= B_VNCLEAN;
1112 * Only remove from synclist when no dirty buffers are left
1113 * AND the VFS has not flagged the vnode's inode as being
1116 if ((vp->v_flag & (VONWORKLST | VISDIRTY | VOBJDIRTY)) ==
1118 RB_EMPTY(&vp->v_rbdirty_tree)) {
1119 vn_syncer_remove(vp, 0);
1125 * Create a vnode for a block device. Used for mounting the root file
1128 * A vref()'d vnode is returned.
1130 extern struct vop_ops *devfs_vnode_dev_vops_p;
1132 bdevvp(cdev_t dev, struct vnode **vpp)
1142 error = getspecialvnode(VT_NON, NULL, &devfs_vnode_dev_vops_p,
1153 v_associate_rdev(vp, dev);
1154 vp->v_umajor = dev->si_umajor;
1155 vp->v_uminor = dev->si_uminor;
1162 v_associate_rdev(struct vnode *vp, cdev_t dev)
1166 if (dev_is_good(dev) == 0)
1168 KKASSERT(vp->v_rdev == NULL);
1169 vp->v_rdev = reference_dev(dev);
1170 lwkt_gettoken(&spechash_token);
1171 SLIST_INSERT_HEAD(&dev->si_hlist, vp, v_cdevnext);
1172 lwkt_reltoken(&spechash_token);
1177 v_release_rdev(struct vnode *vp)
1181 if ((dev = vp->v_rdev) != NULL) {
1182 lwkt_gettoken(&spechash_token);
1183 SLIST_REMOVE(&dev->si_hlist, vp, vnode, v_cdevnext);
1186 lwkt_reltoken(&spechash_token);
1191 * Add a vnode to the alias list hung off the cdev_t. We only associate
1192 * the device number with the vnode. The actual device is not associated
1193 * until the vnode is opened (usually in spec_open()), and will be
1194 * disassociated on last close.
1197 addaliasu(struct vnode *nvp, int x, int y)
1199 if (nvp->v_type != VBLK && nvp->v_type != VCHR)
1200 panic("addaliasu on non-special vnode");
1206 * Simple call that a filesystem can make to try to get rid of a
1207 * vnode. It will fail if anyone is referencing the vnode (including
1210 * The filesystem can check whether its in-memory inode structure still
1211 * references the vp on return.
1213 * May only be called if the vnode is in a known state (i.e. being prevented
1214 * from being deallocated by some other condition such as a vfs inode hold).
1217 vclean_unlocked(struct vnode *vp)
1220 if (VREFCNT(vp) <= 1)
1226 * Disassociate a vnode from its underlying filesystem.
1228 * The vnode must be VX locked and referenced. In all normal situations
1229 * there are no active references. If vclean_vxlocked() is called while
1230 * there are active references, the vnode is being ripped out and we have
1231 * to call VOP_CLOSE() as appropriate before we can reclaim it.
1234 vclean_vxlocked(struct vnode *vp, int flags)
1239 struct namecache *ncp;
1242 * If the vnode has already been reclaimed we have nothing to do.
1244 if (vp->v_flag & VRECLAIMED)
1248 * Set flag to interlock operation, flag finalization to ensure
1249 * that the vnode winds up on the inactive list, and set v_act to 0.
1251 vsetflags(vp, VRECLAIMED);
1252 atomic_set_int(&vp->v_refcnt, VREF_FINALIZE);
1255 if (verbose_reclaims) {
1256 if ((ncp = TAILQ_FIRST(&vp->v_namecache)) != NULL)
1257 kprintf("Debug: reclaim %p %s\n", vp, ncp->nc_name);
1261 * Scrap the vfs cache
1263 while (cache_inval_vp(vp, 0) != 0) {
1264 kprintf("Warning: vnode %p clean/cache_resolution "
1265 "race detected\n", vp);
1266 tsleep(vp, 0, "vclninv", 2);
1270 * Check to see if the vnode is in use. If so we have to reference it
1271 * before we clean it out so that its count cannot fall to zero and
1272 * generate a race against ourselves to recycle it.
1274 active = (VREFCNT(vp) > 0);
1277 * Clean out any buffers associated with the vnode and destroy its
1278 * object, if it has one.
1280 vinvalbuf(vp, V_SAVE, 0, 0);
1283 * If purging an active vnode (typically during a forced unmount
1284 * or reboot), it must be closed and deactivated before being
1285 * reclaimed. This isn't really all that safe, but what can
1288 * Note that neither of these routines unlocks the vnode.
1290 if (active && (flags & DOCLOSE)) {
1291 while ((n = vp->v_opencount) != 0) {
1292 if (vp->v_writecount)
1293 VOP_CLOSE(vp, FWRITE|FNONBLOCK, NULL);
1295 VOP_CLOSE(vp, FNONBLOCK, NULL);
1296 if (vp->v_opencount == n) {
1297 kprintf("Warning: unable to force-close"
1305 * If the vnode has not been deactivated, deactivated it. Deactivation
1306 * can create new buffers and VM pages so we have to call vinvalbuf()
1307 * again to make sure they all get flushed.
1309 * This can occur if a file with a link count of 0 needs to be
1312 * If the vnode is already dead don't try to deactivate it.
1314 if ((vp->v_flag & VINACTIVE) == 0) {
1315 vsetflags(vp, VINACTIVE);
1318 vinvalbuf(vp, V_SAVE, 0, 0);
1322 * If the vnode has an object, destroy it.
1324 while ((object = vp->v_object) != NULL) {
1325 vm_object_hold(object);
1326 if (object == vp->v_object)
1328 vm_object_drop(object);
1331 if (object != NULL) {
1332 if (object->ref_count == 0) {
1333 if ((object->flags & OBJ_DEAD) == 0)
1334 vm_object_terminate(object);
1335 vm_object_drop(object);
1336 vclrflags(vp, VOBJBUF);
1338 vm_pager_deallocate(object);
1339 vclrflags(vp, VOBJBUF);
1340 vm_object_drop(object);
1343 KKASSERT((vp->v_flag & VOBJBUF) == 0);
1345 if (vp->v_flag & VOBJDIRTY)
1349 * Reclaim the vnode if not already dead.
1351 if (vp->v_mount && VOP_RECLAIM(vp))
1352 panic("vclean: cannot reclaim");
1355 * Done with purge, notify sleepers of the grim news.
1357 vp->v_ops = &dead_vnode_vops_p;
1362 * If we are destroying an active vnode, reactivate it now that
1363 * we have reassociated it with deadfs. This prevents the system
1364 * from crashing on the vnode due to it being unexpectedly marked
1365 * as inactive or reclaimed.
1367 if (active && (flags & DOCLOSE)) {
1368 vclrflags(vp, VINACTIVE | VRECLAIMED);
1373 * Eliminate all activity associated with the requested vnode
1374 * and with all vnodes aliased to the requested vnode.
1376 * The vnode must be referenced but should not be locked.
1379 vrevoke(struct vnode *vp, struct ucred *cred)
1387 * If the vnode has a device association, scrap all vnodes associated
1388 * with the device. Don't let the device disappear on us while we
1389 * are scrapping the vnodes.
1391 * The passed vp will probably show up in the list, do not VX lock
1394 * Releasing the vnode's rdev here can mess up specfs's call to
1395 * device close, so don't do it. The vnode has been disassociated
1396 * and the device will be closed after the last ref on the related
1397 * fp goes away (if not still open by e.g. the kernel).
1399 if (vp->v_type != VCHR) {
1400 error = fdrevoke(vp, DTYPE_VNODE, cred);
1403 if ((dev = vp->v_rdev) == NULL) {
1407 lwkt_gettoken(&spechash_token);
1410 vqn = SLIST_FIRST(&dev->si_hlist);
1413 while ((vq = vqn) != NULL) {
1414 if (VREFCNT(vq) > 0) {
1416 fdrevoke(vq, DTYPE_VNODE, cred);
1417 /*v_release_rdev(vq);*/
1419 if (vq->v_rdev != dev) {
1424 vqn = SLIST_NEXT(vq, v_cdevnext);
1429 lwkt_reltoken(&spechash_token);
1436 * This is called when the object underlying a vnode is being destroyed,
1437 * such as in a remove(). Try to recycle the vnode immediately if the
1438 * only active reference is our reference.
1440 * Directory vnodes in the namecache with children cannot be immediately
1441 * recycled because numerous VOP_N*() ops require them to be stable.
1443 * To avoid recursive recycling from VOP_INACTIVE implemenetations this
1444 * function is a NOP if VRECLAIMED is already set.
1447 vrecycle(struct vnode *vp)
1449 if (VREFCNT(vp) <= 1 && (vp->v_flag & VRECLAIMED) == 0) {
1450 if (cache_inval_vp_nonblock(vp))
1459 * Return the maximum I/O size allowed for strategy calls on VP.
1461 * If vp is VCHR or VBLK we dive the device, otherwise we use
1462 * the vp's mount info.
1464 * The returned value is clamped at MAXPHYS as most callers cannot use
1465 * buffers larger than that size.
1468 vmaxiosize(struct vnode *vp)
1472 if (vp->v_type == VBLK || vp->v_type == VCHR)
1473 maxiosize = vp->v_rdev->si_iosize_max;
1475 maxiosize = vp->v_mount->mnt_iosize_max;
1477 if (maxiosize > MAXPHYS)
1478 maxiosize = MAXPHYS;
1483 * Eliminate all activity associated with a vnode in preparation for
1486 * The vnode must be VX locked and refd and will remain VX locked and refd
1487 * on return. This routine may be called with the vnode in any state, as
1488 * long as it is VX locked. The vnode will be cleaned out and marked
1489 * VRECLAIMED but will not actually be reused until all existing refs and
1492 * NOTE: This routine may be called on a vnode which has not yet been
1493 * already been deactivated (VOP_INACTIVE), or on a vnode which has
1494 * already been reclaimed.
1496 * This routine is not responsible for placing us back on the freelist.
1497 * Instead, it happens automatically when the caller releases the VX lock
1498 * (assuming there aren't any other references).
1501 vgone_vxlocked(struct vnode *vp)
1504 * assert that the VX lock is held. This is an absolute requirement
1505 * now for vgone_vxlocked() to be called.
1507 KKASSERT(lockinuse(&vp->v_lock));
1510 * Clean out the filesystem specific data and set the VRECLAIMED
1511 * bit. Also deactivate the vnode if necessary.
1513 * The vnode should have automatically been removed from the syncer
1514 * list as syncer/dirty flags cleared during the cleaning.
1516 vclean_vxlocked(vp, DOCLOSE);
1519 * Normally panic if the vnode is still dirty, unless we are doing
1520 * a forced unmount (tmpfs typically).
1522 if (vp->v_flag & VONWORKLST) {
1523 if (vp->v_mount->mnt_kern_flag & MNTK_UNMOUNTF) {
1525 vn_syncer_remove(vp, 1);
1527 panic("vp %p still dirty in vgone after flush", vp);
1532 * Delete from old mount point vnode list, if on one.
1534 if (vp->v_mount != NULL) {
1535 KKASSERT(vp->v_data == NULL);
1536 insmntque(vp, NULL);
1540 * If special device, remove it from special device alias list
1541 * if it is on one. This should normally only occur if a vnode is
1542 * being revoked as the device should otherwise have been released
1545 if ((vp->v_type == VBLK || vp->v_type == VCHR) && vp->v_rdev != NULL) {
1556 * Lookup a vnode by device number.
1558 * Returns non-zero and *vpp set to a vref'd vnode on success.
1559 * Returns zero on failure.
1562 vfinddev(cdev_t dev, enum vtype type, struct vnode **vpp)
1566 lwkt_gettoken(&spechash_token);
1567 SLIST_FOREACH(vp, &dev->si_hlist, v_cdevnext) {
1568 if (type == vp->v_type) {
1571 lwkt_reltoken(&spechash_token);
1575 lwkt_reltoken(&spechash_token);
1580 * Calculate the total number of references to a special device. This
1581 * routine may only be called for VBLK and VCHR vnodes since v_rdev is
1582 * an overloaded field. Since udev2dev can now return NULL, we have
1583 * to check for a NULL v_rdev.
1586 count_dev(cdev_t dev)
1591 if (SLIST_FIRST(&dev->si_hlist)) {
1592 lwkt_gettoken(&spechash_token);
1593 SLIST_FOREACH(vp, &dev->si_hlist, v_cdevnext) {
1594 count += vp->v_opencount;
1596 lwkt_reltoken(&spechash_token);
1602 vcount(struct vnode *vp)
1604 if (vp->v_rdev == NULL)
1606 return(count_dev(vp->v_rdev));
1610 * Initialize VMIO for a vnode. This routine MUST be called before a
1611 * VFS can issue buffer cache ops on a vnode. It is typically called
1612 * when a vnode is initialized from its inode.
1615 vinitvmio(struct vnode *vp, off_t filesize, int blksize, int boff)
1620 object = vp->v_object;
1622 vm_object_hold(object);
1623 KKASSERT(vp->v_object == object);
1626 if (object == NULL) {
1627 object = vnode_pager_alloc(vp, filesize, 0, 0, blksize, boff);
1630 * Dereference the reference we just created. This assumes
1631 * that the object is associated with the vp. Allow it to
1632 * have zero refs. It cannot be destroyed as long as it
1633 * is associated with the vnode.
1635 vm_object_hold(object);
1636 atomic_add_int(&object->ref_count, -1);
1639 KKASSERT((object->flags & OBJ_DEAD) == 0);
1641 KASSERT(vp->v_object != NULL, ("vinitvmio: NULL object"));
1642 vsetflags(vp, VOBJBUF);
1643 vm_object_drop(object);
1650 * Print out a description of a vnode.
1652 static char *typename[] =
1653 {"VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD"};
1656 vprint(char *label, struct vnode *vp)
1661 kprintf("%s: %p: ", label, (void *)vp);
1663 kprintf("%p: ", (void *)vp);
1664 kprintf("type %s, refcnt %08x, writecount %d, holdcnt %d,",
1665 typename[vp->v_type],
1666 vp->v_refcnt, vp->v_writecount, vp->v_auxrefs);
1668 if (vp->v_flag & VROOT)
1669 strcat(buf, "|VROOT");
1670 if (vp->v_flag & VPFSROOT)
1671 strcat(buf, "|VPFSROOT");
1672 if (vp->v_flag & VTEXT)
1673 strcat(buf, "|VTEXT");
1674 if (vp->v_flag & VSYSTEM)
1675 strcat(buf, "|VSYSTEM");
1676 if (vp->v_flag & VOBJBUF)
1677 strcat(buf, "|VOBJBUF");
1679 kprintf(" flags (%s)", &buf[1]);
1680 if (vp->v_data == NULL) {
1689 * Do the usual access checking.
1690 * file_mode, uid and gid are from the vnode in question,
1691 * while acc_mode and cred are from the VOP_ACCESS parameter list
1694 vaccess(enum vtype type, mode_t file_mode, uid_t uid, gid_t gid,
1695 mode_t acc_mode, struct ucred *cred)
1701 * Super-user always gets read/write access, but execute access depends
1702 * on at least one execute bit being set.
1704 if (priv_check_cred(cred, PRIV_ROOT, 0) == 0) {
1705 if ((acc_mode & VEXEC) && type != VDIR &&
1706 (file_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0)
1713 /* Otherwise, check the owner. */
1714 if (cred->cr_uid == uid) {
1715 if (acc_mode & VEXEC)
1717 if (acc_mode & VREAD)
1719 if (acc_mode & VWRITE)
1721 return ((file_mode & mask) == mask ? 0 : EACCES);
1724 /* Otherwise, check the groups. */
1725 ismember = groupmember(gid, cred);
1726 if (cred->cr_svgid == gid || ismember) {
1727 if (acc_mode & VEXEC)
1729 if (acc_mode & VREAD)
1731 if (acc_mode & VWRITE)
1733 return ((file_mode & mask) == mask ? 0 : EACCES);
1736 /* Otherwise, check everyone else. */
1737 if (acc_mode & VEXEC)
1739 if (acc_mode & VREAD)
1741 if (acc_mode & VWRITE)
1743 return ((file_mode & mask) == mask ? 0 : EACCES);
1747 #include <ddb/ddb.h>
1749 static int db_show_locked_vnodes(struct mount *mp, void *data);
1752 * List all of the locked vnodes in the system.
1753 * Called when debugging the kernel.
1755 DB_SHOW_COMMAND(lockedvnodes, lockedvnodes)
1757 kprintf("Locked vnodes\n");
1758 mountlist_scan(db_show_locked_vnodes, NULL,
1759 MNTSCAN_FORWARD|MNTSCAN_NOBUSY);
1763 db_show_locked_vnodes(struct mount *mp, void *data __unused)
1767 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
1768 if (vn_islocked(vp))
1776 * Top level filesystem related information gathering.
1778 static int sysctl_ovfs_conf (SYSCTL_HANDLER_ARGS);
1781 vfs_sysctl(SYSCTL_HANDLER_ARGS)
1783 int *name = (int *)arg1 - 1; /* XXX */
1784 u_int namelen = arg2 + 1; /* XXX */
1785 struct vfsconf *vfsp;
1788 #if 1 || defined(COMPAT_PRELITE2)
1789 /* Resolve ambiguity between VFS_VFSCONF and VFS_GENERIC. */
1791 return (sysctl_ovfs_conf(oidp, arg1, arg2, req));
1795 /* all sysctl names at this level are at least name and field */
1797 return (ENOTDIR); /* overloaded */
1798 if (name[0] != VFS_GENERIC) {
1799 vfsp = vfsconf_find_by_typenum(name[0]);
1801 return (EOPNOTSUPP);
1802 return ((*vfsp->vfc_vfsops->vfs_sysctl)(&name[1], namelen - 1,
1803 oldp, oldlenp, newp, newlen, p));
1807 case VFS_MAXTYPENUM:
1810 maxtypenum = vfsconf_get_maxtypenum();
1811 return (SYSCTL_OUT(req, &maxtypenum, sizeof(maxtypenum)));
1814 return (ENOTDIR); /* overloaded */
1815 vfsp = vfsconf_find_by_typenum(name[2]);
1817 return (EOPNOTSUPP);
1818 return (SYSCTL_OUT(req, vfsp, sizeof *vfsp));
1820 return (EOPNOTSUPP);
1823 SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RD, vfs_sysctl,
1824 "Generic filesystem");
1826 #if 1 || defined(COMPAT_PRELITE2)
1829 sysctl_ovfs_conf_iter(struct vfsconf *vfsp, void *data)
1832 struct ovfsconf ovfs;
1833 struct sysctl_req *req = (struct sysctl_req*) data;
1835 bzero(&ovfs, sizeof(ovfs));
1836 ovfs.vfc_vfsops = vfsp->vfc_vfsops; /* XXX used as flag */
1837 strcpy(ovfs.vfc_name, vfsp->vfc_name);
1838 ovfs.vfc_index = vfsp->vfc_typenum;
1839 ovfs.vfc_refcount = vfsp->vfc_refcount;
1840 ovfs.vfc_flags = vfsp->vfc_flags;
1841 error = SYSCTL_OUT(req, &ovfs, sizeof ovfs);
1843 return error; /* abort iteration with error code */
1845 return 0; /* continue iterating with next element */
1849 sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS)
1851 return vfsconf_each(sysctl_ovfs_conf_iter, (void*)req);
1854 #endif /* 1 || COMPAT_PRELITE2 */
1857 * Check to see if a filesystem is mounted on a block device.
1860 vfs_mountedon(struct vnode *vp)
1864 if ((dev = vp->v_rdev) == NULL) {
1865 /* if (vp->v_type != VBLK)
1866 dev = get_dev(vp->v_uminor, vp->v_umajor); */
1868 if (dev != NULL && dev->si_mountpoint)
1874 * Unmount all filesystems. The list is traversed in reverse order
1875 * of mounting to avoid dependencies.
1877 * We want the umountall to be able to break out of its loop if a
1878 * failure occurs, after scanning all possible mounts, so the callback
1879 * returns 0 on error.
1881 * NOTE: Do not call mountlist_remove(mp) on error any more, this will
1882 * confuse mountlist_scan()'s unbusy check.
1884 static int vfs_umountall_callback(struct mount *mp, void *data);
1887 vfs_unmountall(int halting)
1892 count = mountlist_scan(vfs_umountall_callback, &halting,
1893 MNTSCAN_REVERSE|MNTSCAN_NOBUSY);
1899 vfs_umountall_callback(struct mount *mp, void *data)
1902 int halting = *(int *)data;
1905 * NOTE: When halting, dounmount will disconnect but leave
1906 * certain mount points intact. e.g. devfs.
1908 error = dounmount(mp, MNT_FORCE, halting);
1910 kprintf("unmount of filesystem mounted from %s failed (",
1911 mp->mnt_stat.f_mntfromname);
1915 kprintf("%d)\n", error);
1923 * Checks the mount flags for parameter mp and put the names comma-separated
1924 * into a string buffer buf with a size limit specified by len.
1926 * It returns the number of bytes written into buf, and (*errorp) will be
1927 * set to 0, EINVAL (if passed length is 0), or ENOSPC (supplied buffer was
1928 * not large enough). The buffer will be 0-terminated if len was not 0.
1931 vfs_flagstostr(int flags, const struct mountctl_opt *optp,
1932 char *buf, size_t len, int *errorp)
1934 static const struct mountctl_opt optnames[] = {
1935 { MNT_RDONLY, "read-only" },
1936 { MNT_SYNCHRONOUS, "synchronous" },
1937 { MNT_NOEXEC, "noexec" },
1938 { MNT_NOSUID, "nosuid" },
1939 { MNT_NODEV, "nodev" },
1940 { MNT_AUTOMOUNTED, "automounted" },
1941 { MNT_ASYNC, "asynchronous" },
1942 { MNT_SUIDDIR, "suiddir" },
1943 { MNT_SOFTDEP, "soft-updates" },
1944 { MNT_NOSYMFOLLOW, "nosymfollow" },
1945 { MNT_TRIM, "trim" },
1946 { MNT_NOATIME, "noatime" },
1947 { MNT_NOCLUSTERR, "noclusterr" },
1948 { MNT_NOCLUSTERW, "noclusterw" },
1949 { MNT_EXRDONLY, "NFS read-only" },
1950 { MNT_EXPORTED, "NFS exported" },
1951 /* Remaining NFS flags could come here */
1952 { MNT_LOCAL, "local" },
1953 { MNT_QUOTA, "with-quotas" },
1954 /* { MNT_ROOTFS, "rootfs" }, */
1955 /* { MNT_IGNORE, "ignore" }, */
1965 bleft = len - 1; /* leave room for trailing \0 */
1968 * Checks the size of the string. If it contains
1969 * any data, then we will append the new flags to
1972 actsize = strlen(buf);
1976 /* Default flags if no flags passed */
1980 if (bleft < 0) { /* degenerate case, 0-length buffer */
1985 for (; flags && optp->o_opt; ++optp) {
1986 if ((flags & optp->o_opt) == 0)
1988 optlen = strlen(optp->o_name);
1989 if (bwritten || actsize > 0) {
1994 buf[bwritten++] = ',';
1995 buf[bwritten++] = ' ';
1998 if (bleft < optlen) {
2002 bcopy(optp->o_name, buf + bwritten, optlen);
2005 flags &= ~optp->o_opt;
2009 * Space already reserved for trailing \0
2016 * Build hash lists of net addresses and hang them off the mount point.
2017 * Called by ufs_mount() to set up the lists of export addresses.
2020 vfs_hang_addrlist(struct mount *mp, struct netexport *nep,
2021 const struct export_args *argp)
2024 struct radix_node_head *rnh;
2026 struct radix_node *rn;
2027 struct sockaddr *saddr, *smask = NULL;
2030 if (argp->ex_addrlen == 0) {
2031 if (mp->mnt_flag & MNT_DEFEXPORTED)
2033 np = &nep->ne_defexported;
2034 np->netc_exflags = argp->ex_flags;
2035 np->netc_anon = argp->ex_anon;
2036 np->netc_anon.cr_ref = 1;
2037 mp->mnt_flag |= MNT_DEFEXPORTED;
2041 if (argp->ex_addrlen < 0 || argp->ex_addrlen > MLEN)
2043 if (argp->ex_masklen < 0 || argp->ex_masklen > MLEN)
2046 i = sizeof(struct netcred) + argp->ex_addrlen + argp->ex_masklen;
2047 np = (struct netcred *)kmalloc(i, M_NETCRED, M_WAITOK | M_ZERO);
2048 saddr = (struct sockaddr *) (np + 1);
2049 if ((error = copyin(argp->ex_addr, (caddr_t) saddr, argp->ex_addrlen)))
2051 if (saddr->sa_len > argp->ex_addrlen)
2052 saddr->sa_len = argp->ex_addrlen;
2053 if (argp->ex_masklen) {
2054 smask = (struct sockaddr *)((caddr_t)saddr + argp->ex_addrlen);
2055 error = copyin(argp->ex_mask, (caddr_t)smask, argp->ex_masklen);
2058 if (smask->sa_len > argp->ex_masklen)
2059 smask->sa_len = argp->ex_masklen;
2062 if (nep->ne_maskhead == NULL) {
2063 if (!rn_inithead((void **)&nep->ne_maskhead, NULL, 0)) {
2068 if ((rnh = vfs_create_addrlist_af(saddr->sa_family, nep)) == NULL) {
2072 rn = (*rnh->rnh_addaddr)((char *)saddr, (char *)smask, rnh,
2075 if (rn == NULL || np != (struct netcred *)rn) { /* already exists */
2079 np->netc_exflags = argp->ex_flags;
2080 np->netc_anon = argp->ex_anon;
2081 np->netc_anon.cr_ref = 1;
2085 kfree(np, M_NETCRED);
2090 * Free netcred structures installed in the netexport
2093 vfs_free_netcred(struct radix_node *rn, void *w)
2095 struct radix_node_head *rnh = (struct radix_node_head *)w;
2097 (*rnh->rnh_deladdr) (rn->rn_key, rn->rn_mask, rnh);
2098 kfree(rn, M_NETCRED);
2104 * callback to free an element of the mask table installed in the
2105 * netexport. These may be created indirectly and are not netcred
2109 vfs_free_netcred_mask(struct radix_node *rn, void *w)
2111 struct radix_node_head *rnh = (struct radix_node_head *)w;
2113 (*rnh->rnh_deladdr) (rn->rn_key, rn->rn_mask, rnh);
2114 kfree(rn, M_RTABLE);
2119 static struct radix_node_head *
2120 vfs_create_addrlist_af(int af, struct netexport *nep)
2122 struct radix_node_head *rnh = NULL;
2123 #if defined(INET) || defined(INET6)
2124 struct radix_node_head *maskhead = nep->ne_maskhead;
2128 NE_ASSERT_LOCKED(nep);
2129 #if defined(INET) || defined(INET6)
2130 KKASSERT(maskhead != NULL);
2135 if ((rnh = nep->ne_inethead) == NULL) {
2136 off = offsetof(struct sockaddr_in, sin_addr) << 3;
2137 if (!rn_inithead((void **)&rnh, maskhead, off))
2139 nep->ne_inethead = rnh;
2145 if ((rnh = nep->ne_inet6head) == NULL) {
2146 off = offsetof(struct sockaddr_in6, sin6_addr) << 3;
2147 if (!rn_inithead((void **)&rnh, maskhead, off))
2149 nep->ne_inet6head = rnh;
2158 * helper function for freeing netcred elements
2161 vfs_free_addrlist_af(struct radix_node_head **prnh)
2163 struct radix_node_head *rnh = *prnh;
2165 (*rnh->rnh_walktree) (rnh, vfs_free_netcred, rnh);
2166 kfree(rnh, M_RTABLE);
2171 * helper function for freeing mask elements
2174 vfs_free_addrlist_masks(struct radix_node_head **prnh)
2176 struct radix_node_head *rnh = *prnh;
2178 (*rnh->rnh_walktree) (rnh, vfs_free_netcred_mask, rnh);
2179 kfree(rnh, M_RTABLE);
2184 * Free the net address hash lists that are hanging off the mount points.
2187 vfs_free_addrlist(struct netexport *nep)
2190 if (nep->ne_inethead != NULL)
2191 vfs_free_addrlist_af(&nep->ne_inethead);
2192 if (nep->ne_inet6head != NULL)
2193 vfs_free_addrlist_af(&nep->ne_inet6head);
2194 if (nep->ne_maskhead)
2195 vfs_free_addrlist_masks(&nep->ne_maskhead);
2200 vfs_export(struct mount *mp, struct netexport *nep,
2201 const struct export_args *argp)
2205 if (argp->ex_flags & MNT_DELEXPORT) {
2206 if (mp->mnt_flag & MNT_EXPUBLIC) {
2207 vfs_setpublicfs(NULL, NULL, NULL);
2208 mp->mnt_flag &= ~MNT_EXPUBLIC;
2210 vfs_free_addrlist(nep);
2211 mp->mnt_flag &= ~(MNT_EXPORTED | MNT_DEFEXPORTED);
2213 if (argp->ex_flags & MNT_EXPORTED) {
2214 if (argp->ex_flags & MNT_EXPUBLIC) {
2215 if ((error = vfs_setpublicfs(mp, nep, argp)) != 0)
2217 mp->mnt_flag |= MNT_EXPUBLIC;
2219 if ((error = vfs_hang_addrlist(mp, nep, argp)))
2221 mp->mnt_flag |= MNT_EXPORTED;
2228 * Set the publicly exported filesystem (WebNFS). Currently, only
2229 * one public filesystem is possible in the spec (RFC 2054 and 2055)
2232 vfs_setpublicfs(struct mount *mp, struct netexport *nep,
2233 const struct export_args *argp)
2240 * mp == NULL -> invalidate the current info, the FS is
2241 * no longer exported. May be called from either vfs_export
2242 * or unmount, so check if it hasn't already been done.
2245 if (nfs_pub.np_valid) {
2246 nfs_pub.np_valid = 0;
2247 if (nfs_pub.np_index != NULL) {
2248 kfree(nfs_pub.np_index, M_TEMP);
2249 nfs_pub.np_index = NULL;
2256 * Only one allowed at a time.
2258 if (nfs_pub.np_valid != 0 && mp != nfs_pub.np_mount)
2262 * Get real filehandle for root of exported FS.
2264 bzero((caddr_t)&nfs_pub.np_handle, sizeof(nfs_pub.np_handle));
2265 nfs_pub.np_handle.fh_fsid = mp->mnt_stat.f_fsid;
2267 if ((error = VFS_ROOT(mp, &rvp)))
2270 if ((error = VFS_VPTOFH(rvp, &nfs_pub.np_handle.fh_fid)))
2276 * If an indexfile was specified, pull it in.
2278 if (argp->ex_indexfile != NULL) {
2281 error = vn_get_namelen(rvp, &namelen);
2284 nfs_pub.np_index = kmalloc(namelen, M_TEMP, M_WAITOK);
2285 error = copyinstr(argp->ex_indexfile, nfs_pub.np_index,
2289 * Check for illegal filenames.
2291 for (cp = nfs_pub.np_index; *cp; cp++) {
2299 kfree(nfs_pub.np_index, M_TEMP);
2304 nfs_pub.np_mount = mp;
2305 nfs_pub.np_valid = 1;
2310 vfs_export_lookup(struct mount *mp, struct netexport *nep,
2311 struct sockaddr *nam)
2314 struct radix_node_head *rnh;
2315 struct sockaddr *saddr;
2318 if (mp->mnt_flag & MNT_EXPORTED) {
2320 * Lookup in the export list first.
2325 switch (saddr->sa_family) {
2328 rnh = nep->ne_inethead;
2333 rnh = nep->ne_inet6head;
2340 np = (struct netcred *)
2341 (*rnh->rnh_matchaddr)((char *)saddr,
2343 if (np && np->netc_rnodes->rn_flags & RNF_ROOT)
2349 * If no address match, use the default if it exists.
2351 if (np == NULL && mp->mnt_flag & MNT_DEFEXPORTED)
2352 np = &nep->ne_defexported;
2358 * perform msync on all vnodes under a mount point. The mount point must
2359 * be locked. This code is also responsible for lazy-freeing unreferenced
2360 * vnodes whos VM objects no longer contain pages.
2362 * NOTE: MNT_WAIT still skips vnodes in the VXLOCK state.
2364 * NOTE: XXX VOP_PUTPAGES and friends requires that the vnode be locked,
2365 * but vnode_pager_putpages() doesn't lock the vnode. We have to do it
2366 * way up in this high level function.
2368 static int vfs_msync_scan1(struct mount *mp, struct vnode *vp, void *data);
2369 static int vfs_msync_scan2(struct mount *mp, struct vnode *vp, void *data);
2372 vfs_msync(struct mount *mp, int flags)
2377 * tmpfs sets this flag to prevent msync(), sync, and the
2378 * filesystem periodic syncer from trying to flush VM pages
2379 * to swap. Only pure memory pressure flushes tmpfs VM pages
2382 if (mp->mnt_kern_flag & MNTK_NOMSYNC)
2386 * Ok, scan the vnodes for work. If the filesystem is using the
2387 * syncer thread feature we can use vsyncscan() instead of
2388 * vmntvnodescan(), which is much faster.
2390 vmsc_flags = VMSC_GETVP;
2391 if (flags != MNT_WAIT)
2392 vmsc_flags |= VMSC_NOWAIT;
2394 if (mp->mnt_kern_flag & MNTK_THR_SYNC) {
2395 vsyncscan(mp, vmsc_flags, vfs_msync_scan2,
2396 (void *)(intptr_t)flags);
2398 vmntvnodescan(mp, vmsc_flags,
2399 vfs_msync_scan1, vfs_msync_scan2,
2400 (void *)(intptr_t)flags);
2405 * scan1 is a fast pre-check. There could be hundreds of thousands of
2406 * vnodes, we cannot afford to do anything heavy weight until we have a
2407 * fairly good indication that there is work to do.
2411 vfs_msync_scan1(struct mount *mp, struct vnode *vp, void *data)
2413 int flags = (int)(intptr_t)data;
2415 if ((vp->v_flag & VRECLAIMED) == 0) {
2416 if (vp->v_auxrefs == 0 && VREFCNT(vp) <= 0 &&
2418 return(0); /* call scan2 */
2420 if ((mp->mnt_flag & MNT_RDONLY) == 0 &&
2421 (vp->v_flag & VOBJDIRTY) &&
2422 (flags == MNT_WAIT || vn_islocked(vp) == 0)) {
2423 return(0); /* call scan2 */
2428 * do not call scan2, continue the loop
2434 * This callback is handed a locked vnode.
2438 vfs_msync_scan2(struct mount *mp, struct vnode *vp, void *data)
2441 int flags = (int)(intptr_t)data;
2444 if (vp->v_flag & VRECLAIMED)
2447 if ((mp->mnt_flag & MNT_RDONLY) == 0 && (vp->v_flag & VOBJDIRTY)) {
2448 if ((obj = vp->v_object) != NULL) {
2449 if (flags == MNT_WAIT) {
2451 * VFS_MSYNC is called with MNT_WAIT when
2454 opcflags = OBJPC_SYNC;
2455 } else if (vp->v_writecount || obj->ref_count) {
2457 * VFS_MSYNC is otherwise called via the
2458 * periodic filesystem sync or the 'sync'
2459 * command. Honor MADV_NOSYNC / MAP_NOSYNC
2460 * if the file is open for writing or memory
2461 * mapped. Pages flagged PG_NOSYNC will not
2462 * be automatically flushed at this time.
2464 * The obj->ref_count test is not perfect
2465 * since temporary refs may be present, but
2466 * the periodic filesystem sync will ultimately
2467 * catch it if the file is not open and not
2470 opcflags = OBJPC_NOSYNC;
2473 * If the file is no longer open for writing
2474 * and also no longer mapped, do not honor
2475 * MAP_NOSYNC. That is, fully synchronize
2478 * This still occurs on the periodic fs sync,
2479 * so frontend programs which turn the file
2480 * over quickly enough can still avoid the
2481 * sync, but ultimately we do want to flush
2482 * even MADV_NOSYNC pages once it is no longer
2483 * mapped or open for writing.
2487 vm_object_page_clean(obj, 0, 0, opcflags);
2494 * Wake up anyone interested in vp because it is being revoked.
2497 vn_gone(struct vnode *vp)
2499 lwkt_gettoken(&vp->v_token);
2500 KNOTE(&vp->v_pollinfo.vpi_kqinfo.ki_note, NOTE_REVOKE);
2501 lwkt_reltoken(&vp->v_token);
2505 * extract the cdev_t from a VBLK or VCHR. The vnode must have been opened
2506 * (or v_rdev might be NULL).
2509 vn_todev(struct vnode *vp)
2511 if (vp->v_type != VBLK && vp->v_type != VCHR)
2513 KKASSERT(vp->v_rdev != NULL);
2514 return (vp->v_rdev);
2518 * Check if vnode represents a disk device. The vnode does not need to be
2524 vn_isdisk(struct vnode *vp, int *errp)
2528 if (vp->v_type != VCHR) {
2541 if (dev_is_good(dev) == 0) {
2546 if ((dev_dflags(dev) & D_DISK) == 0) {
2557 vn_get_namelen(struct vnode *vp, int *namelen)
2560 register_t retval[2];
2562 error = VOP_PATHCONF(vp, _PC_NAME_MAX, retval);
2565 *namelen = (int)retval[0];
2570 vop_write_dirent(int *error, struct uio *uio, ino_t d_ino, uint8_t d_type,
2571 uint16_t d_namlen, const char *d_name)
2576 len = _DIRENT_RECLEN(d_namlen);
2577 if (len > uio->uio_resid)
2580 dp = kmalloc(len, M_TEMP, M_WAITOK | M_ZERO);
2583 dp->d_namlen = d_namlen;
2584 dp->d_type = d_type;
2585 bcopy(d_name, dp->d_name, d_namlen);
2587 *error = uiomove((caddr_t)dp, len, uio);
2595 vn_mark_atime(struct vnode *vp, struct thread *td)
2597 struct proc *p = td->td_proc;
2598 struct ucred *cred = p ? p->p_ucred : proc0.p_ucred;
2600 if ((vp->v_mount->mnt_flag & (MNT_NOATIME | MNT_RDONLY)) == 0) {
2601 VOP_MARKATIME(vp, cred);
2606 * Calculate the number of entries in an inode-related chained hash table.
2607 * With today's memory sizes, maxvnodes can wind up being a very large
2608 * number. There is no reason to waste memory, so tolerate some stacking.
2611 vfs_inodehashsize(void)
2616 while (hsize < maxvnodes)
2618 while (hsize > maxvnodes * 2)
2619 hsize >>= 1; /* nominal 2x stacking */
2621 if (maxvnodes > 1024 * 1024)
2622 hsize >>= 1; /* nominal 8x stacking */
2624 if (maxvnodes > 128 * 1024)
2625 hsize >>= 1; /* nominal 4x stacking */