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 <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);
129 static void vclean_vxlocked(struct vnode *vp, int flags);
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,
209 TSP_USEC_PRECISE, TSP_NSEC_PRECISE };
211 __read_mostly static int timestamp_precision = TSP_USEC;
212 SYSCTL_INT(_vfs, OID_AUTO, timestamp_precision, CTLFLAG_RW,
213 ×tamp_precision, 0, "Precision of file timestamps");
216 * Get a current timestamp.
221 vfs_timestamp(struct timespec *tsp)
223 switch (timestamp_precision) {
224 case TSP_SEC: /* seconds precision */
229 case TSP_HZ: /* ticks precision (limit to microseconds) */
231 tsp->tv_nsec -= tsp->tv_nsec % 1000;
233 case TSP_USEC: /* microseconds (ticks precision) */
235 tsp->tv_nsec -= tsp->tv_nsec % 1000;
237 case TSP_NSEC: /* nanoseconds (ticks precision) */
240 case TSP_USEC_PRECISE: /* microseconds (high preceision) */
242 tsp->tv_nsec -= tsp->tv_nsec % 1000;
244 case TSP_NSEC_PRECISE: /* nanoseconds (high precision) */
251 * Set vnode attributes to VNOVAL
254 vattr_null(struct vattr *vap)
257 vap->va_size = VNOVAL;
258 vap->va_bytes = VNOVAL;
259 vap->va_mode = VNOVAL;
260 vap->va_nlink = VNOVAL;
261 vap->va_uid = VNOVAL;
262 vap->va_gid = VNOVAL;
263 vap->va_fsid = VNOVAL;
264 vap->va_fileid = VNOVAL;
265 vap->va_blocksize = VNOVAL;
266 vap->va_rmajor = VNOVAL;
267 vap->va_rminor = VNOVAL;
268 vap->va_atime.tv_sec = VNOVAL;
269 vap->va_atime.tv_nsec = VNOVAL;
270 vap->va_mtime.tv_sec = VNOVAL;
271 vap->va_mtime.tv_nsec = VNOVAL;
272 vap->va_ctime.tv_sec = VNOVAL;
273 vap->va_ctime.tv_nsec = VNOVAL;
274 vap->va_flags = VNOVAL;
275 vap->va_gen = VNOVAL;
277 /* va_*_uuid fields are only valid if related flags are set */
281 * Flush out and invalidate all buffers associated with a vnode.
285 static int vinvalbuf_bp(struct buf *bp, void *data);
287 struct vinvalbuf_bp_info {
296 vinvalbuf(struct vnode *vp, int flags, int slpflag, int slptimeo)
298 struct vinvalbuf_bp_info info;
302 lwkt_gettoken(&vp->v_token);
305 * If we are being asked to save, call fsync to ensure that the inode
308 if (flags & V_SAVE) {
309 error = bio_track_wait(&vp->v_track_write, slpflag, slptimeo);
312 if (!RB_EMPTY(&vp->v_rbdirty_tree)) {
313 if ((error = VOP_FSYNC(vp, MNT_WAIT, 0)) != 0)
317 * Dirty bufs may be left or generated via races
318 * in circumstances where vinvalbuf() is called on
319 * a vnode not undergoing reclamation. Only
320 * panic if we are trying to reclaim the vnode.
322 if ((vp->v_flag & VRECLAIMED) &&
323 (bio_track_active(&vp->v_track_write) ||
324 !RB_EMPTY(&vp->v_rbdirty_tree))) {
325 panic("vinvalbuf: dirty bufs");
330 info.slptimeo = slptimeo;
331 info.lkflags = LK_EXCLUSIVE | LK_SLEEPFAIL;
332 if (slpflag & PCATCH)
333 info.lkflags |= LK_PCATCH;
338 * Flush the buffer cache until nothing is left, wait for all I/O
339 * to complete. At least one pass is required. We might block
340 * in the pip code so we have to re-check. Order is important.
346 if (!RB_EMPTY(&vp->v_rbclean_tree)) {
348 error = RB_SCAN(buf_rb_tree, &vp->v_rbclean_tree,
349 NULL, vinvalbuf_bp, &info);
351 if (!RB_EMPTY(&vp->v_rbdirty_tree)) {
353 error = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree,
354 NULL, vinvalbuf_bp, &info);
358 * Wait for I/O completion.
360 bio_track_wait(&vp->v_track_write, 0, 0);
361 if ((object = vp->v_object) != NULL)
362 refcount_wait(&object->paging_in_progress, "vnvlbx");
363 } while (bio_track_active(&vp->v_track_write) ||
364 !RB_EMPTY(&vp->v_rbclean_tree) ||
365 !RB_EMPTY(&vp->v_rbdirty_tree));
368 * Destroy the copy in the VM cache, too.
370 if ((object = vp->v_object) != NULL) {
371 vm_object_page_remove(object, 0, 0,
372 (flags & V_SAVE) ? TRUE : FALSE);
375 if (!RB_EMPTY(&vp->v_rbdirty_tree) || !RB_EMPTY(&vp->v_rbclean_tree))
376 panic("vinvalbuf: flush failed");
377 if (!RB_EMPTY(&vp->v_rbhash_tree))
378 panic("vinvalbuf: flush failed, buffers still present");
381 lwkt_reltoken(&vp->v_token);
386 vinvalbuf_bp(struct buf *bp, void *data)
388 struct vinvalbuf_bp_info *info = data;
391 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
392 atomic_add_int(&bp->b_refs, 1);
393 error = BUF_TIMELOCK(bp, info->lkflags,
394 "vinvalbuf", info->slptimeo);
395 atomic_subtract_int(&bp->b_refs, 1);
404 KKASSERT(bp->b_vp == info->vp);
407 * Must check clean/dirty status after successfully locking as
410 if ((info->clean && (bp->b_flags & B_DELWRI)) ||
411 (info->clean == 0 && (bp->b_flags & B_DELWRI) == 0)) {
417 * NOTE: NO B_LOCKED CHECK. Also no buf_checkwrite()
418 * check. This code will write out the buffer, period.
421 if (((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI) &&
422 (info->flags & V_SAVE)) {
424 } else if (info->flags & V_SAVE) {
426 * Cannot set B_NOCACHE on a clean buffer as this will
427 * destroy the VM backing store which might actually
428 * be dirty (and unsynchronized).
430 bp->b_flags |= (B_INVAL | B_RELBUF);
433 bp->b_flags |= (B_INVAL | B_NOCACHE | B_RELBUF);
440 * Truncate a file's buffer and pages to a specified length. This
441 * is in lieu of the old vinvalbuf mechanism, which performed unneeded
444 * The vnode must be locked.
446 static int vtruncbuf_bp_trunc_cmp(struct buf *bp, void *data);
447 static int vtruncbuf_bp_trunc(struct buf *bp, void *data);
448 static int vtruncbuf_bp_metasync_cmp(struct buf *bp, void *data);
449 static int vtruncbuf_bp_metasync(struct buf *bp, void *data);
451 struct vtruncbuf_info {
458 vtruncbuf(struct vnode *vp, off_t length, int blksize)
460 struct vtruncbuf_info info;
461 const char *filename;
465 * Round up to the *next* block, then destroy the buffers in question.
466 * Since we are only removing some of the buffers we must rely on the
467 * scan count to determine whether a loop is necessary.
469 if ((count = (int)(length % blksize)) != 0)
470 info.truncloffset = length + (blksize - count);
472 info.truncloffset = length;
475 lwkt_gettoken(&vp->v_token);
478 count = RB_SCAN(buf_rb_tree, &vp->v_rbclean_tree,
479 vtruncbuf_bp_trunc_cmp,
480 vtruncbuf_bp_trunc, &info);
482 count += RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree,
483 vtruncbuf_bp_trunc_cmp,
484 vtruncbuf_bp_trunc, &info);
488 * For safety, fsync any remaining metadata if the file is not being
489 * truncated to 0. Since the metadata does not represent the entire
490 * dirty list we have to rely on the hit count to ensure that we get
495 count = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree,
496 vtruncbuf_bp_metasync_cmp,
497 vtruncbuf_bp_metasync, &info);
502 * Clean out any left over VM backing store.
504 * It is possible to have in-progress I/O from buffers that were
505 * not part of the truncation. This should not happen if we
506 * are truncating to 0-length.
508 vnode_pager_setsize(vp, length);
509 bio_track_wait(&vp->v_track_write, 0, 0);
514 spin_lock(&vp->v_spin);
515 filename = TAILQ_FIRST(&vp->v_namecache) ?
516 TAILQ_FIRST(&vp->v_namecache)->nc_name : "?";
517 spin_unlock(&vp->v_spin);
520 * Make sure no buffers were instantiated while we were trying
521 * to clean out the remaining VM pages. This could occur due
522 * to busy dirty VM pages being flushed out to disk.
526 count = RB_SCAN(buf_rb_tree, &vp->v_rbclean_tree,
527 vtruncbuf_bp_trunc_cmp,
528 vtruncbuf_bp_trunc, &info);
530 count += RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree,
531 vtruncbuf_bp_trunc_cmp,
532 vtruncbuf_bp_trunc, &info);
534 kprintf("Warning: vtruncbuf(): Had to re-clean %d "
535 "left over buffers in %s\n", count, filename);
539 lwkt_reltoken(&vp->v_token);
545 * The callback buffer is beyond the new file EOF and must be destroyed.
546 * Note that the compare function must conform to the RB_SCAN's requirements.
550 vtruncbuf_bp_trunc_cmp(struct buf *bp, void *data)
552 struct vtruncbuf_info *info = data;
554 if (bp->b_loffset >= info->truncloffset)
561 vtruncbuf_bp_trunc(struct buf *bp, void *data)
563 struct vtruncbuf_info *info = data;
566 * Do not try to use a buffer we cannot immediately lock, but sleep
567 * anyway to prevent a livelock. The code will loop until all buffers
570 * We must always revalidate the buffer after locking it to deal
573 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
574 atomic_add_int(&bp->b_refs, 1);
575 if (BUF_LOCK(bp, LK_EXCLUSIVE|LK_SLEEPFAIL) == 0)
577 atomic_subtract_int(&bp->b_refs, 1);
578 } else if ((info->clean && (bp->b_flags & B_DELWRI)) ||
579 (info->clean == 0 && (bp->b_flags & B_DELWRI) == 0) ||
580 bp->b_vp != info->vp ||
581 vtruncbuf_bp_trunc_cmp(bp, data)) {
585 bp->b_flags |= (B_INVAL | B_RELBUF | B_NOCACHE);
592 * Fsync all meta-data after truncating a file to be non-zero. Only metadata
593 * blocks (with a negative loffset) are scanned.
594 * Note that the compare function must conform to the RB_SCAN's requirements.
597 vtruncbuf_bp_metasync_cmp(struct buf *bp, void *data __unused)
599 if (bp->b_loffset < 0)
605 vtruncbuf_bp_metasync(struct buf *bp, void *data)
607 struct vtruncbuf_info *info = data;
609 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
610 atomic_add_int(&bp->b_refs, 1);
611 if (BUF_LOCK(bp, LK_EXCLUSIVE|LK_SLEEPFAIL) == 0)
613 atomic_subtract_int(&bp->b_refs, 1);
614 } else if ((bp->b_flags & B_DELWRI) == 0 ||
615 bp->b_vp != info->vp ||
616 vtruncbuf_bp_metasync_cmp(bp, data)) {
620 if (bp->b_vp == info->vp)
629 * vfsync - implements a multipass fsync on a file which understands
630 * dependancies and meta-data. The passed vnode must be locked. The
631 * waitfor argument may be MNT_WAIT or MNT_NOWAIT, or MNT_LAZY.
633 * When fsyncing data asynchronously just do one consolidated pass starting
634 * with the most negative block number. This may not get all the data due
637 * When fsyncing data synchronously do a data pass, then a metadata pass,
638 * then do additional data+metadata passes to try to get all the data out.
640 * Caller must ref the vnode but does not have to lock it.
642 static int vfsync_wait_output(struct vnode *vp,
643 int (*waitoutput)(struct vnode *, struct thread *));
644 static int vfsync_dummy_cmp(struct buf *bp __unused, void *data __unused);
645 static int vfsync_data_only_cmp(struct buf *bp, void *data);
646 static int vfsync_meta_only_cmp(struct buf *bp, void *data);
647 static int vfsync_lazy_range_cmp(struct buf *bp, void *data);
648 static int vfsync_bp(struct buf *bp, void *data);
658 int (*checkdef)(struct buf *);
659 int (*cmpfunc)(struct buf *, void *);
663 vfsync(struct vnode *vp, int waitfor, int passes,
664 int (*checkdef)(struct buf *),
665 int (*waitoutput)(struct vnode *, struct thread *))
667 struct vfsync_info info;
670 bzero(&info, sizeof(info));
672 if ((info.checkdef = checkdef) == NULL)
675 lwkt_gettoken(&vp->v_token);
678 case MNT_LAZY | MNT_NOWAIT:
681 * Lazy (filesystem syncer typ) Asynchronous plus limit the
682 * number of data (not meta) pages we try to flush to 1MB.
683 * A non-zero return means that lazy limit was reached.
685 info.lazylimit = 1024 * 1024;
687 info.cmpfunc = vfsync_lazy_range_cmp;
688 error = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree,
689 vfsync_lazy_range_cmp, vfsync_bp, &info);
690 info.cmpfunc = vfsync_meta_only_cmp;
691 RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree,
692 vfsync_meta_only_cmp, vfsync_bp, &info);
695 else if (!RB_EMPTY(&vp->v_rbdirty_tree))
696 vn_syncer_add(vp, 1);
701 * Asynchronous. Do a data-only pass and a meta-only pass.
704 info.cmpfunc = vfsync_data_only_cmp;
705 RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, vfsync_data_only_cmp,
707 info.cmpfunc = vfsync_meta_only_cmp;
708 RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, vfsync_meta_only_cmp,
714 * Synchronous. Do a data-only pass, then a meta-data+data
715 * pass, then additional integrated passes to try to get
716 * all the dependancies flushed.
718 info.cmpfunc = vfsync_data_only_cmp;
720 RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, vfsync_data_only_cmp,
723 error = vfsync_wait_output(vp, waitoutput);
725 info.skippedbufs = 0;
726 info.cmpfunc = vfsync_dummy_cmp;
727 RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, NULL,
729 error = vfsync_wait_output(vp, waitoutput);
730 if (info.skippedbufs) {
731 kprintf("Warning: vfsync skipped %d dirty "
734 ((info.skippedbufs > 1) ? "s" : ""));
737 while (error == 0 && passes > 0 &&
738 !RB_EMPTY(&vp->v_rbdirty_tree)
740 info.skippedbufs = 0;
742 info.synchronous = 1;
745 info.cmpfunc = vfsync_dummy_cmp;
746 error = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, NULL,
752 error = vfsync_wait_output(vp, waitoutput);
753 if (info.skippedbufs && passes == 0) {
754 kprintf("Warning: vfsync skipped %d dirty "
755 "buf%s in final pass!\n",
757 ((info.skippedbufs > 1) ? "s" : ""));
762 * This case can occur normally because vnode lock might
765 if (!RB_EMPTY(&vp->v_rbdirty_tree))
766 kprintf("dirty bufs left after final pass\n");
770 lwkt_reltoken(&vp->v_token);
776 vfsync_wait_output(struct vnode *vp,
777 int (*waitoutput)(struct vnode *, struct thread *))
781 error = bio_track_wait(&vp->v_track_write, 0, 0);
783 error = waitoutput(vp, curthread);
788 vfsync_dummy_cmp(struct buf *bp __unused, void *data __unused)
794 vfsync_data_only_cmp(struct buf *bp, void *data)
796 if (bp->b_loffset < 0)
802 vfsync_meta_only_cmp(struct buf *bp, void *data)
804 if (bp->b_loffset < 0)
810 vfsync_lazy_range_cmp(struct buf *bp, void *data)
812 struct vfsync_info *info = data;
814 if (bp->b_loffset < info->vp->v_lazyw)
820 vfsync_bp(struct buf *bp, void *data)
822 struct vfsync_info *info = data;
823 struct vnode *vp = info->vp;
826 if (info->fastpass) {
828 * Ignore buffers that we cannot immediately lock.
830 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
832 * Removed BUF_TIMELOCK(..., 1), even a 1-tick
833 * delay can mess up performance
835 * Another reason is that during a dirty-buffer
836 * scan a clustered write can start I/O on buffers
837 * ahead of the scan, causing the scan to not
838 * get a lock here. Usually this means the write
839 * is already in progress so, in fact, we *want*
840 * to skip the buffer.
845 } else if (info->synchronous == 0) {
847 * Normal pass, give the buffer a little time to become
850 if (BUF_TIMELOCK(bp, LK_EXCLUSIVE, "bflst2", hz / 10)) {
856 * Synchronous pass, give the buffer a lot of time before
859 if (BUF_TIMELOCK(bp, LK_EXCLUSIVE, "bflst3", hz * 10)) {
866 * We must revalidate the buffer after locking.
868 if ((bp->b_flags & B_DELWRI) == 0 ||
869 bp->b_vp != info->vp ||
870 info->cmpfunc(bp, data)) {
876 * If syncdeps is not set we do not try to write buffers which have
879 if (!info->synchronous && info->syncdeps == 0 && info->checkdef(bp)) {
885 * B_NEEDCOMMIT (primarily used by NFS) is a state where the buffer
886 * has been written but an additional handshake with the device
887 * is required before we can dispose of the buffer. We have no idea
888 * how to do this so we have to skip these buffers.
890 if (bp->b_flags & B_NEEDCOMMIT) {
896 * Ask bioops if it is ok to sync. If not the VFS may have
897 * set B_LOCKED so we have to cycle the buffer.
899 if (LIST_FIRST(&bp->b_dep) != NULL && buf_checkwrite(bp)) {
905 if (info->synchronous) {
907 * Synchronous flush. An error may be returned and will
914 * Asynchronous flush. We use the error return to support
917 * In low-memory situations we revert to synchronous
918 * operation. This should theoretically prevent the I/O
919 * path from exhausting memory in a non-recoverable way.
921 vp->v_lazyw = bp->b_loffset;
923 if (vm_page_count_min(0)) {
925 info->lazycount += bp->b_bufsize;
929 info->lazycount += cluster_awrite(bp);
930 waitrunningbufspace();
931 /*vm_wait_nominal();*/
933 if (info->lazylimit && info->lazycount >= info->lazylimit)
942 * Associate a buffer with a vnode.
947 bgetvp(struct vnode *vp, struct buf *bp, int testsize)
949 KASSERT(bp->b_vp == NULL, ("bgetvp: not free"));
950 KKASSERT((bp->b_flags & (B_HASHED|B_DELWRI|B_VNCLEAN|B_VNDIRTY)) == 0);
953 * Insert onto list for new vnode.
955 lwkt_gettoken(&vp->v_token);
957 if (buf_rb_hash_RB_INSERT(&vp->v_rbhash_tree, bp)) {
958 lwkt_reltoken(&vp->v_token);
963 * Diagnostics (mainly for HAMMER debugging). Check for
964 * overlapping buffers.
966 if (check_buf_overlap) {
968 bx = buf_rb_hash_RB_PREV(bp);
970 if (bx->b_loffset + bx->b_bufsize > bp->b_loffset) {
971 kprintf("bgetvp: overlapl %016jx/%d %016jx "
973 (intmax_t)bx->b_loffset,
975 (intmax_t)bp->b_loffset,
977 if (check_buf_overlap > 1)
978 panic("bgetvp - overlapping buffer");
981 bx = buf_rb_hash_RB_NEXT(bp);
983 if (bp->b_loffset + testsize > bx->b_loffset) {
984 kprintf("bgetvp: overlapr %016jx/%d %016jx "
986 (intmax_t)bp->b_loffset,
988 (intmax_t)bx->b_loffset,
990 if (check_buf_overlap > 1)
991 panic("bgetvp - overlapping buffer");
996 bp->b_flags |= B_HASHED;
997 bp->b_flags |= B_VNCLEAN;
998 if (buf_rb_tree_RB_INSERT(&vp->v_rbclean_tree, bp))
999 panic("reassignbuf: dup lblk/clean vp %p bp %p", vp, bp);
1001 lwkt_reltoken(&vp->v_token);
1006 * Disassociate a buffer from a vnode.
1011 brelvp(struct buf *bp)
1015 KASSERT(bp->b_vp != NULL, ("brelvp: NULL"));
1018 * Delete from old vnode list, if on one.
1021 lwkt_gettoken(&vp->v_token);
1022 if (bp->b_flags & (B_VNDIRTY | B_VNCLEAN)) {
1023 if (bp->b_flags & B_VNDIRTY)
1024 buf_rb_tree_RB_REMOVE(&vp->v_rbdirty_tree, bp);
1026 buf_rb_tree_RB_REMOVE(&vp->v_rbclean_tree, bp);
1027 bp->b_flags &= ~(B_VNDIRTY | B_VNCLEAN);
1029 if (bp->b_flags & B_HASHED) {
1030 buf_rb_hash_RB_REMOVE(&vp->v_rbhash_tree, bp);
1031 bp->b_flags &= ~B_HASHED;
1035 * Only remove from synclist when no dirty buffers are left AND
1036 * the VFS has not flagged the vnode's inode as being dirty.
1038 if ((vp->v_flag & (VONWORKLST | VISDIRTY | VOBJDIRTY)) == VONWORKLST &&
1039 RB_EMPTY(&vp->v_rbdirty_tree)) {
1040 vn_syncer_remove(vp, 0);
1044 lwkt_reltoken(&vp->v_token);
1050 * Reassign the buffer to the proper clean/dirty list based on B_DELWRI.
1051 * This routine is called when the state of the B_DELWRI bit is changed.
1053 * Must be called with vp->v_token held.
1057 reassignbuf(struct buf *bp)
1059 struct vnode *vp = bp->b_vp;
1062 ASSERT_LWKT_TOKEN_HELD(&vp->v_token);
1066 * B_PAGING flagged buffers cannot be reassigned because their vp
1067 * is not fully linked in.
1069 if (bp->b_flags & B_PAGING)
1070 panic("cannot reassign paging buffer");
1072 if (bp->b_flags & B_DELWRI) {
1074 * Move to the dirty list, add the vnode to the worklist
1076 if (bp->b_flags & B_VNCLEAN) {
1077 buf_rb_tree_RB_REMOVE(&vp->v_rbclean_tree, bp);
1078 bp->b_flags &= ~B_VNCLEAN;
1080 if ((bp->b_flags & B_VNDIRTY) == 0) {
1081 if (buf_rb_tree_RB_INSERT(&vp->v_rbdirty_tree, bp)) {
1082 panic("reassignbuf: dup lblk vp %p bp %p",
1085 bp->b_flags |= B_VNDIRTY;
1087 if ((vp->v_flag & VONWORKLST) == 0) {
1088 switch (vp->v_type) {
1095 vp->v_rdev->si_mountpoint != NULL) {
1103 vn_syncer_add(vp, delay);
1107 * Move to the clean list, remove the vnode from the worklist
1108 * if no dirty blocks remain.
1110 if (bp->b_flags & B_VNDIRTY) {
1111 buf_rb_tree_RB_REMOVE(&vp->v_rbdirty_tree, bp);
1112 bp->b_flags &= ~B_VNDIRTY;
1114 if ((bp->b_flags & B_VNCLEAN) == 0) {
1115 if (buf_rb_tree_RB_INSERT(&vp->v_rbclean_tree, bp)) {
1116 panic("reassignbuf: dup lblk vp %p bp %p",
1119 bp->b_flags |= B_VNCLEAN;
1123 * Only remove from synclist when no dirty buffers are left
1124 * AND the VFS has not flagged the vnode's inode as being
1127 if ((vp->v_flag & (VONWORKLST | VISDIRTY | VOBJDIRTY)) ==
1129 RB_EMPTY(&vp->v_rbdirty_tree)) {
1130 vn_syncer_remove(vp, 0);
1136 * Create a vnode for a block device. Used for mounting the root file
1139 * A vref()'d vnode is returned.
1141 extern struct vop_ops *devfs_vnode_dev_vops_p;
1143 bdevvp(cdev_t dev, struct vnode **vpp)
1153 error = getspecialvnode(VT_NON, NULL, &devfs_vnode_dev_vops_p,
1164 v_associate_rdev(vp, dev);
1165 vp->v_umajor = dev->si_umajor;
1166 vp->v_uminor = dev->si_uminor;
1173 v_associate_rdev(struct vnode *vp, cdev_t dev)
1177 if (dev_is_good(dev) == 0)
1179 KKASSERT(vp->v_rdev == NULL);
1180 vp->v_rdev = reference_dev(dev);
1181 lwkt_gettoken(&spechash_token);
1182 SLIST_INSERT_HEAD(&dev->si_hlist, vp, v_cdevnext);
1183 lwkt_reltoken(&spechash_token);
1188 v_release_rdev(struct vnode *vp)
1192 if ((dev = vp->v_rdev) != NULL) {
1193 lwkt_gettoken(&spechash_token);
1194 SLIST_REMOVE(&dev->si_hlist, vp, vnode, v_cdevnext);
1197 lwkt_reltoken(&spechash_token);
1202 * Add a vnode to the alias list hung off the cdev_t. We only associate
1203 * the device number with the vnode. The actual device is not associated
1204 * until the vnode is opened (usually in spec_open()), and will be
1205 * disassociated on last close.
1208 addaliasu(struct vnode *nvp, int x, int y)
1210 if (nvp->v_type != VBLK && nvp->v_type != VCHR)
1211 panic("addaliasu on non-special vnode");
1217 * Simple call that a filesystem can make to try to get rid of a
1218 * vnode. It will fail if anyone is referencing the vnode (including
1221 * The filesystem can check whether its in-memory inode structure still
1222 * references the vp on return.
1224 * May only be called if the vnode is in a known state (i.e. being prevented
1225 * from being deallocated by some other condition such as a vfs inode hold).
1227 * This call might not succeed.
1230 vclean_unlocked(struct vnode *vp)
1233 if (VREFCNT(vp) <= 1)
1239 * Disassociate a vnode from its underlying filesystem.
1241 * The vnode must be VX locked and referenced. In all normal situations
1242 * there are no active references. If vclean_vxlocked() is called while
1243 * there are active references, the vnode is being ripped out and we have
1244 * to call VOP_CLOSE() as appropriate before we can reclaim it.
1247 vclean_vxlocked(struct vnode *vp, int flags)
1252 struct namecache *ncp;
1255 * If the vnode has already been reclaimed we have nothing to do.
1257 if (vp->v_flag & VRECLAIMED)
1261 * Set flag to interlock operation, flag finalization to ensure
1262 * that the vnode winds up on the inactive list, and set v_act to 0.
1264 vsetflags(vp, VRECLAIMED);
1265 atomic_set_int(&vp->v_refcnt, VREF_FINALIZE);
1268 if (verbose_reclaims) {
1269 if ((ncp = TAILQ_FIRST(&vp->v_namecache)) != NULL)
1270 kprintf("Debug: reclaim %p %s\n", vp, ncp->nc_name);
1274 * Scrap the vfs cache
1276 while (cache_inval_vp(vp, 0) != 0) {
1277 kprintf("Warning: vnode %p clean/cache_resolution "
1278 "race detected\n", vp);
1279 tsleep(vp, 0, "vclninv", 2);
1283 * Check to see if the vnode is in use. If so we have to reference it
1284 * before we clean it out so that its count cannot fall to zero and
1285 * generate a race against ourselves to recycle it.
1287 active = (VREFCNT(vp) > 0);
1290 * Clean out any buffers associated with the vnode and destroy its
1291 * object, if it has one.
1293 vinvalbuf(vp, V_SAVE, 0, 0);
1296 * If purging an active vnode (typically during a forced unmount
1297 * or reboot), it must be closed and deactivated before being
1298 * reclaimed. This isn't really all that safe, but what can
1301 * Note that neither of these routines unlocks the vnode.
1303 if (active && (flags & DOCLOSE)) {
1304 while ((n = vp->v_opencount) != 0) {
1305 if (vp->v_writecount)
1306 VOP_CLOSE(vp, FWRITE|FNONBLOCK, NULL);
1308 VOP_CLOSE(vp, FNONBLOCK, NULL);
1309 if (vp->v_opencount == n) {
1310 kprintf("Warning: unable to force-close"
1318 * If the vnode has not been deactivated, deactivated it. Deactivation
1319 * can create new buffers and VM pages so we have to call vinvalbuf()
1320 * again to make sure they all get flushed.
1322 * This can occur if a file with a link count of 0 needs to be
1325 * If the vnode is already dead don't try to deactivate it.
1327 if ((vp->v_flag & VINACTIVE) == 0) {
1328 vsetflags(vp, VINACTIVE);
1331 vinvalbuf(vp, V_SAVE, 0, 0);
1335 * If the vnode has an object, destroy it.
1337 while ((object = vp->v_object) != NULL) {
1338 vm_object_hold(object);
1339 if (object == vp->v_object)
1341 vm_object_drop(object);
1344 if (object != NULL) {
1345 if (object->ref_count == 0) {
1346 if ((object->flags & OBJ_DEAD) == 0)
1347 vm_object_terminate(object);
1348 vm_object_drop(object);
1349 vclrflags(vp, VOBJBUF);
1351 vm_pager_deallocate(object);
1352 vclrflags(vp, VOBJBUF);
1353 vm_object_drop(object);
1356 KKASSERT((vp->v_flag & VOBJBUF) == 0);
1358 if (vp->v_flag & VOBJDIRTY)
1362 * Reclaim the vnode if not already dead.
1364 if (vp->v_mount && VOP_RECLAIM(vp))
1365 panic("vclean: cannot reclaim");
1368 * Done with purge, notify sleepers of the grim news.
1370 vp->v_ops = &dead_vnode_vops_p;
1375 * If we are destroying an active vnode, reactivate it now that
1376 * we have reassociated it with deadfs. This prevents the system
1377 * from crashing on the vnode due to it being unexpectedly marked
1378 * as inactive or reclaimed.
1380 if (active && (flags & DOCLOSE)) {
1381 vclrflags(vp, VINACTIVE | VRECLAIMED);
1386 * Eliminate all activity associated with the requested vnode
1387 * and with all vnodes aliased to the requested vnode.
1389 * The vnode must be referenced but should not be locked.
1392 vrevoke(struct vnode *vp, struct ucred *cred)
1400 * If the vnode has a device association, scrap all vnodes associated
1401 * with the device. Don't let the device disappear on us while we
1402 * are scrapping the vnodes.
1404 * The passed vp will probably show up in the list, do not VX lock
1407 * Releasing the vnode's rdev here can mess up specfs's call to
1408 * device close, so don't do it. The vnode has been disassociated
1409 * and the device will be closed after the last ref on the related
1410 * fp goes away (if not still open by e.g. the kernel).
1412 if (vp->v_type != VCHR) {
1413 error = fdrevoke(vp, DTYPE_VNODE, cred);
1416 if ((dev = vp->v_rdev) == NULL) {
1420 lwkt_gettoken(&spechash_token);
1423 vqn = SLIST_FIRST(&dev->si_hlist);
1426 while ((vq = vqn) != NULL) {
1427 if (VREFCNT(vq) > 0) {
1429 fdrevoke(vq, DTYPE_VNODE, cred);
1430 /*v_release_rdev(vq);*/
1432 if (vq->v_rdev != dev) {
1437 vqn = SLIST_NEXT(vq, v_cdevnext);
1442 lwkt_reltoken(&spechash_token);
1449 * This is called when the object underlying a vnode is being destroyed,
1450 * such as in a remove(). Try to recycle the vnode immediately if the
1451 * only active reference is our reference.
1453 * Directory vnodes in the namecache with children cannot be immediately
1454 * recycled because numerous VOP_N*() ops require them to be stable.
1456 * To avoid recursive recycling from VOP_INACTIVE implemenetations this
1457 * function is a NOP if VRECLAIMED is already set.
1460 vrecycle(struct vnode *vp)
1462 if (VREFCNT(vp) <= 1 && (vp->v_flag & VRECLAIMED) == 0) {
1463 if (cache_inval_vp_nonblock(vp))
1472 * Return the maximum I/O size allowed for strategy calls on VP.
1474 * If vp is VCHR or VBLK we dive the device, otherwise we use
1475 * the vp's mount info.
1477 * The returned value is clamped at MAXPHYS as most callers cannot use
1478 * buffers larger than that size.
1481 vmaxiosize(struct vnode *vp)
1485 if (vp->v_type == VBLK || vp->v_type == VCHR)
1486 maxiosize = vp->v_rdev->si_iosize_max;
1488 maxiosize = vp->v_mount->mnt_iosize_max;
1490 if (maxiosize > MAXPHYS)
1491 maxiosize = MAXPHYS;
1496 * Eliminate all activity associated with a vnode in preparation for
1499 * The vnode must be VX locked and refd and will remain VX locked and refd
1500 * on return. This routine may be called with the vnode in any state, as
1501 * long as it is VX locked. The vnode will be cleaned out and marked
1502 * VRECLAIMED but will not actually be reused until all existing refs and
1505 * NOTE: This routine may be called on a vnode which has not yet been
1506 * already been deactivated (VOP_INACTIVE), or on a vnode which has
1507 * already been reclaimed.
1509 * This routine is not responsible for placing us back on the freelist.
1510 * Instead, it happens automatically when the caller releases the VX lock
1511 * (assuming there aren't any other references).
1514 vgone_vxlocked(struct vnode *vp)
1517 * assert that the VX lock is held. This is an absolute requirement
1518 * now for vgone_vxlocked() to be called.
1520 KKASSERT(lockinuse(&vp->v_lock));
1523 * Clean out the filesystem specific data and set the VRECLAIMED
1524 * bit. Also deactivate the vnode if necessary.
1526 * The vnode should have automatically been removed from the syncer
1527 * list as syncer/dirty flags cleared during the cleaning.
1529 vclean_vxlocked(vp, DOCLOSE);
1532 * Normally panic if the vnode is still dirty, unless we are doing
1533 * a forced unmount (tmpfs typically).
1535 if (vp->v_flag & VONWORKLST) {
1536 if (vp->v_mount->mnt_kern_flag & MNTK_UNMOUNTF) {
1538 vn_syncer_remove(vp, 1);
1540 panic("vp %p still dirty in vgone after flush", vp);
1545 * Delete from old mount point vnode list, if on one.
1547 if (vp->v_mount != NULL) {
1548 KKASSERT(vp->v_data == NULL);
1549 insmntque(vp, NULL);
1553 * If special device, remove it from special device alias list
1554 * if it is on one. This should normally only occur if a vnode is
1555 * being revoked as the device should otherwise have been released
1558 if ((vp->v_type == VBLK || vp->v_type == VCHR) && vp->v_rdev != NULL) {
1569 * Calculate the total number of references to a special device. This
1570 * routine may only be called for VBLK and VCHR vnodes since v_rdev is
1571 * an overloaded field. Since dev_from_devid() can now return NULL, we
1572 * have to check for a NULL v_rdev.
1575 count_dev(cdev_t dev)
1580 if (SLIST_FIRST(&dev->si_hlist)) {
1581 lwkt_gettoken(&spechash_token);
1582 SLIST_FOREACH(vp, &dev->si_hlist, v_cdevnext) {
1583 count += vp->v_opencount;
1585 lwkt_reltoken(&spechash_token);
1591 vcount(struct vnode *vp)
1593 if (vp->v_rdev == NULL)
1595 return(count_dev(vp->v_rdev));
1599 * Initialize VMIO for a vnode. This routine MUST be called before a
1600 * VFS can issue buffer cache ops on a vnode. It is typically called
1601 * when a vnode is initialized from its inode.
1604 vinitvmio(struct vnode *vp, off_t filesize, int blksize, int boff)
1609 object = vp->v_object;
1611 vm_object_hold(object);
1612 KKASSERT(vp->v_object == object);
1615 if (object == NULL) {
1616 object = vnode_pager_alloc(vp, filesize, 0, 0, blksize, boff);
1619 * Dereference the reference we just created. This assumes
1620 * that the object is associated with the vp. Allow it to
1621 * have zero refs. It cannot be destroyed as long as it
1622 * is associated with the vnode.
1624 vm_object_hold(object);
1625 atomic_add_int(&object->ref_count, -1);
1628 KKASSERT((object->flags & OBJ_DEAD) == 0);
1630 KASSERT(vp->v_object != NULL, ("vinitvmio: NULL object"));
1631 vsetflags(vp, VOBJBUF);
1632 vm_object_drop(object);
1639 * Print out a description of a vnode.
1641 static char *typename[] =
1642 {"VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD"};
1645 vprint(char *label, struct vnode *vp)
1650 kprintf("%s: %p: ", label, (void *)vp);
1652 kprintf("%p: ", (void *)vp);
1653 kprintf("type %s, refcnt %08x, writecount %d, holdcnt %d,",
1654 typename[vp->v_type],
1655 vp->v_refcnt, vp->v_writecount, vp->v_auxrefs);
1657 if (vp->v_flag & VROOT)
1658 strcat(buf, "|VROOT");
1659 if (vp->v_flag & VPFSROOT)
1660 strcat(buf, "|VPFSROOT");
1661 if (vp->v_flag & VTEXT)
1662 strcat(buf, "|VTEXT");
1663 if (vp->v_flag & VSYSTEM)
1664 strcat(buf, "|VSYSTEM");
1665 if (vp->v_flag & VOBJBUF)
1666 strcat(buf, "|VOBJBUF");
1668 kprintf(" flags (%s)", &buf[1]);
1669 if (vp->v_data == NULL) {
1678 * Do the usual access checking.
1679 * file_mode, uid and gid are from the vnode in question,
1680 * while acc_mode and cred are from the VOP_ACCESS parameter list
1683 vaccess(enum vtype type, mode_t file_mode, uid_t uid, gid_t gid,
1684 mode_t acc_mode, struct ucred *cred)
1690 * Super-user always gets read/write access, but execute access depends
1691 * on at least one execute bit being set.
1693 if (priv_check_cred(cred, PRIV_ROOT, 0) == 0) {
1694 if ((acc_mode & VEXEC) && type != VDIR &&
1695 (file_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0)
1702 /* Otherwise, check the owner. */
1703 if (cred->cr_uid == uid) {
1704 if (acc_mode & VEXEC)
1706 if (acc_mode & VREAD)
1708 if (acc_mode & VWRITE)
1710 return ((file_mode & mask) == mask ? 0 : EACCES);
1713 /* Otherwise, check the groups. */
1714 ismember = groupmember(gid, cred);
1715 if (cred->cr_svgid == gid || ismember) {
1716 if (acc_mode & VEXEC)
1718 if (acc_mode & VREAD)
1720 if (acc_mode & VWRITE)
1722 return ((file_mode & mask) == mask ? 0 : EACCES);
1725 /* Otherwise, check everyone else. */
1726 if (acc_mode & VEXEC)
1728 if (acc_mode & VREAD)
1730 if (acc_mode & VWRITE)
1732 return ((file_mode & mask) == mask ? 0 : EACCES);
1736 #include <ddb/ddb.h>
1738 static int db_show_locked_vnodes(struct mount *mp, void *data);
1741 * List all of the locked vnodes in the system.
1742 * Called when debugging the kernel.
1744 DB_SHOW_COMMAND(lockedvnodes, lockedvnodes)
1746 kprintf("Locked vnodes\n");
1747 mountlist_scan(db_show_locked_vnodes, NULL,
1748 MNTSCAN_FORWARD|MNTSCAN_NOBUSY);
1752 db_show_locked_vnodes(struct mount *mp, void *data __unused)
1756 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
1757 if (vn_islocked(vp))
1765 * Top level filesystem related information gathering.
1767 static int sysctl_ovfs_conf (SYSCTL_HANDLER_ARGS);
1770 vfs_sysctl(SYSCTL_HANDLER_ARGS)
1772 int *name = (int *)arg1 - 1; /* XXX */
1773 u_int namelen = arg2 + 1; /* XXX */
1774 struct vfsconf *vfsp;
1777 #if 1 || defined(COMPAT_PRELITE2)
1778 /* Resolve ambiguity between VFS_VFSCONF and VFS_GENERIC. */
1780 return (sysctl_ovfs_conf(oidp, arg1, arg2, req));
1784 /* all sysctl names at this level are at least name and field */
1786 return (ENOTDIR); /* overloaded */
1787 if (name[0] != VFS_GENERIC) {
1788 vfsp = vfsconf_find_by_typenum(name[0]);
1790 return (EOPNOTSUPP);
1791 return ((*vfsp->vfc_vfsops->vfs_sysctl)(&name[1], namelen - 1,
1792 oldp, oldlenp, newp, newlen, p));
1796 case VFS_MAXTYPENUM:
1799 maxtypenum = vfsconf_get_maxtypenum();
1800 return (SYSCTL_OUT(req, &maxtypenum, sizeof(maxtypenum)));
1803 return (ENOTDIR); /* overloaded */
1804 vfsp = vfsconf_find_by_typenum(name[2]);
1806 return (EOPNOTSUPP);
1807 return (SYSCTL_OUT(req, vfsp, sizeof *vfsp));
1809 return (EOPNOTSUPP);
1812 SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RD, vfs_sysctl,
1813 "Generic filesystem");
1815 #if 1 || defined(COMPAT_PRELITE2)
1818 sysctl_ovfs_conf_iter(struct vfsconf *vfsp, void *data)
1821 struct ovfsconf ovfs;
1822 struct sysctl_req *req = (struct sysctl_req*) data;
1824 bzero(&ovfs, sizeof(ovfs));
1825 ovfs.vfc_vfsops = vfsp->vfc_vfsops; /* XXX used as flag */
1826 strcpy(ovfs.vfc_name, vfsp->vfc_name);
1827 ovfs.vfc_index = vfsp->vfc_typenum;
1828 ovfs.vfc_refcount = vfsp->vfc_refcount;
1829 ovfs.vfc_flags = vfsp->vfc_flags;
1830 error = SYSCTL_OUT(req, &ovfs, sizeof ovfs);
1832 return error; /* abort iteration with error code */
1834 return 0; /* continue iterating with next element */
1838 sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS)
1840 return vfsconf_each(sysctl_ovfs_conf_iter, (void*)req);
1843 #endif /* 1 || COMPAT_PRELITE2 */
1846 * Check to see if a filesystem is mounted on a block device.
1849 vfs_mountedon(struct vnode *vp)
1854 if (dev != NULL && dev->si_mountpoint)
1860 * Unmount all filesystems. The list is traversed in reverse order
1861 * of mounting to avoid dependencies.
1863 * We want the umountall to be able to break out of its loop if a
1864 * failure occurs, after scanning all possible mounts, so the callback
1865 * returns 0 on error.
1867 * NOTE: Do not call mountlist_remove(mp) on error any more, this will
1868 * confuse mountlist_scan()'s unbusy check.
1870 static int vfs_umountall_callback(struct mount *mp, void *data);
1873 vfs_unmountall(int halting)
1878 count = mountlist_scan(vfs_umountall_callback, &halting,
1879 MNTSCAN_REVERSE|MNTSCAN_NOBUSY);
1885 vfs_umountall_callback(struct mount *mp, void *data)
1888 int halting = *(int *)data;
1891 * NOTE: When halting, dounmount will disconnect but leave
1892 * certain mount points intact. e.g. devfs.
1894 error = dounmount(mp, MNT_FORCE, halting);
1896 kprintf("unmount of filesystem mounted from %s failed (",
1897 mp->mnt_stat.f_mntfromname);
1901 kprintf("%d)\n", error);
1909 * Checks the mount flags for parameter mp and put the names comma-separated
1910 * into a string buffer buf with a size limit specified by len.
1912 * It returns the number of bytes written into buf, and (*errorp) will be
1913 * set to 0, EINVAL (if passed length is 0), or ENOSPC (supplied buffer was
1914 * not large enough). The buffer will be 0-terminated if len was not 0.
1917 vfs_flagstostr(int flags, const struct mountctl_opt *optp,
1918 char *buf, size_t len, int *errorp)
1920 static const struct mountctl_opt optnames[] = {
1921 { MNT_RDONLY, "read-only" },
1922 { MNT_SYNCHRONOUS, "synchronous" },
1923 { MNT_NOEXEC, "noexec" },
1924 { MNT_NOSUID, "nosuid" },
1925 { MNT_NODEV, "nodev" },
1926 { MNT_AUTOMOUNTED, "automounted" },
1927 { MNT_ASYNC, "asynchronous" },
1928 { MNT_SUIDDIR, "suiddir" },
1929 { MNT_SOFTDEP, "soft-updates" },
1930 { MNT_NOSYMFOLLOW, "nosymfollow" },
1931 { MNT_TRIM, "trim" },
1932 { MNT_NOATIME, "noatime" },
1933 { MNT_NOCLUSTERR, "noclusterr" },
1934 { MNT_NOCLUSTERW, "noclusterw" },
1935 { MNT_EXRDONLY, "NFS read-only" },
1936 { MNT_EXPORTED, "NFS exported" },
1937 /* Remaining NFS flags could come here */
1938 { MNT_LOCAL, "local" },
1939 { MNT_QUOTA, "with-quotas" },
1940 /* { MNT_ROOTFS, "rootfs" }, */
1941 /* { MNT_IGNORE, "ignore" }, */
1951 bleft = len - 1; /* leave room for trailing \0 */
1954 * Checks the size of the string. If it contains
1955 * any data, then we will append the new flags to
1958 actsize = strlen(buf);
1962 /* Default flags if no flags passed */
1966 if (bleft < 0) { /* degenerate case, 0-length buffer */
1971 for (; flags && optp->o_opt; ++optp) {
1972 if ((flags & optp->o_opt) == 0)
1974 optlen = strlen(optp->o_name);
1975 if (bwritten || actsize > 0) {
1980 buf[bwritten++] = ',';
1981 buf[bwritten++] = ' ';
1984 if (bleft < optlen) {
1988 bcopy(optp->o_name, buf + bwritten, optlen);
1991 flags &= ~optp->o_opt;
1995 * Space already reserved for trailing \0
2002 * Build hash lists of net addresses and hang them off the mount point.
2003 * Called by ufs_mount() to set up the lists of export addresses.
2006 vfs_hang_addrlist(struct mount *mp, struct netexport *nep,
2007 const struct export_args *argp)
2010 struct radix_node_head *rnh;
2012 struct radix_node *rn;
2013 struct sockaddr *saddr, *smask = NULL;
2016 if (argp->ex_addrlen == 0) {
2017 if (mp->mnt_flag & MNT_DEFEXPORTED)
2019 np = &nep->ne_defexported;
2020 np->netc_exflags = argp->ex_flags;
2021 np->netc_anon = argp->ex_anon;
2022 np->netc_anon.cr_ref = 1;
2023 mp->mnt_flag |= MNT_DEFEXPORTED;
2027 if (argp->ex_addrlen < 0 || argp->ex_addrlen > MLEN)
2029 if (argp->ex_masklen < 0 || argp->ex_masklen > MLEN)
2032 i = sizeof(struct netcred) + argp->ex_addrlen + argp->ex_masklen;
2033 np = (struct netcred *)kmalloc(i, M_NETCRED, M_WAITOK | M_ZERO);
2034 saddr = (struct sockaddr *) (np + 1);
2035 if ((error = copyin(argp->ex_addr, (caddr_t) saddr, argp->ex_addrlen)))
2037 if (saddr->sa_len > argp->ex_addrlen)
2038 saddr->sa_len = argp->ex_addrlen;
2039 if (argp->ex_masklen) {
2040 smask = (struct sockaddr *)((caddr_t)saddr + argp->ex_addrlen);
2041 error = copyin(argp->ex_mask, (caddr_t)smask, argp->ex_masklen);
2044 if (smask->sa_len > argp->ex_masklen)
2045 smask->sa_len = argp->ex_masklen;
2048 if (nep->ne_maskhead == NULL) {
2049 if (!rn_inithead((void **)&nep->ne_maskhead, NULL, 0)) {
2054 if ((rnh = vfs_create_addrlist_af(saddr->sa_family, nep)) == NULL) {
2058 rn = (*rnh->rnh_addaddr)((char *)saddr, (char *)smask, rnh,
2061 if (rn == NULL || np != (struct netcred *)rn) { /* already exists */
2065 np->netc_exflags = argp->ex_flags;
2066 np->netc_anon = argp->ex_anon;
2067 np->netc_anon.cr_ref = 1;
2071 kfree(np, M_NETCRED);
2076 * Free netcred structures installed in the netexport
2079 vfs_free_netcred(struct radix_node *rn, void *w)
2081 struct radix_node_head *rnh = (struct radix_node_head *)w;
2083 (*rnh->rnh_deladdr) (rn->rn_key, rn->rn_mask, rnh);
2084 kfree(rn, M_NETCRED);
2090 * callback to free an element of the mask table installed in the
2091 * netexport. These may be created indirectly and are not netcred
2095 vfs_free_netcred_mask(struct radix_node *rn, void *w)
2097 struct radix_node_head *rnh = (struct radix_node_head *)w;
2099 (*rnh->rnh_deladdr) (rn->rn_key, rn->rn_mask, rnh);
2100 kfree(rn, M_RTABLE);
2105 static struct radix_node_head *
2106 vfs_create_addrlist_af(int af, struct netexport *nep)
2108 struct radix_node_head *rnh = NULL;
2109 #if defined(INET) || defined(INET6)
2110 struct radix_node_head *maskhead = nep->ne_maskhead;
2114 NE_ASSERT_LOCKED(nep);
2115 #if defined(INET) || defined(INET6)
2116 KKASSERT(maskhead != NULL);
2121 if ((rnh = nep->ne_inethead) == NULL) {
2122 off = offsetof(struct sockaddr_in, sin_addr) << 3;
2123 if (!rn_inithead((void **)&rnh, maskhead, off))
2125 nep->ne_inethead = rnh;
2131 if ((rnh = nep->ne_inet6head) == NULL) {
2132 off = offsetof(struct sockaddr_in6, sin6_addr) << 3;
2133 if (!rn_inithead((void **)&rnh, maskhead, off))
2135 nep->ne_inet6head = rnh;
2144 * helper function for freeing netcred elements
2147 vfs_free_addrlist_af(struct radix_node_head **prnh)
2149 struct radix_node_head *rnh = *prnh;
2151 (*rnh->rnh_walktree) (rnh, vfs_free_netcred, rnh);
2152 kfree(rnh, M_RTABLE);
2157 * helper function for freeing mask elements
2160 vfs_free_addrlist_masks(struct radix_node_head **prnh)
2162 struct radix_node_head *rnh = *prnh;
2164 (*rnh->rnh_walktree) (rnh, vfs_free_netcred_mask, rnh);
2165 kfree(rnh, M_RTABLE);
2170 * Free the net address hash lists that are hanging off the mount points.
2173 vfs_free_addrlist(struct netexport *nep)
2176 if (nep->ne_inethead != NULL)
2177 vfs_free_addrlist_af(&nep->ne_inethead);
2178 if (nep->ne_inet6head != NULL)
2179 vfs_free_addrlist_af(&nep->ne_inet6head);
2180 if (nep->ne_maskhead)
2181 vfs_free_addrlist_masks(&nep->ne_maskhead);
2186 vfs_export(struct mount *mp, struct netexport *nep,
2187 const struct export_args *argp)
2191 if (argp->ex_flags & MNT_DELEXPORT) {
2192 if (mp->mnt_flag & MNT_EXPUBLIC) {
2193 vfs_setpublicfs(NULL, NULL, NULL);
2194 mp->mnt_flag &= ~MNT_EXPUBLIC;
2196 vfs_free_addrlist(nep);
2197 mp->mnt_flag &= ~(MNT_EXPORTED | MNT_DEFEXPORTED);
2199 if (argp->ex_flags & MNT_EXPORTED) {
2200 if (argp->ex_flags & MNT_EXPUBLIC) {
2201 if ((error = vfs_setpublicfs(mp, nep, argp)) != 0)
2203 mp->mnt_flag |= MNT_EXPUBLIC;
2205 if ((error = vfs_hang_addrlist(mp, nep, argp)))
2207 mp->mnt_flag |= MNT_EXPORTED;
2214 * Set the publicly exported filesystem (WebNFS). Currently, only
2215 * one public filesystem is possible in the spec (RFC 2054 and 2055)
2218 vfs_setpublicfs(struct mount *mp, struct netexport *nep,
2219 const struct export_args *argp)
2226 * mp == NULL -> invalidate the current info, the FS is
2227 * no longer exported. May be called from either vfs_export
2228 * or unmount, so check if it hasn't already been done.
2231 if (nfs_pub.np_valid) {
2232 nfs_pub.np_valid = 0;
2233 if (nfs_pub.np_index != NULL) {
2234 kfree(nfs_pub.np_index, M_TEMP);
2235 nfs_pub.np_index = NULL;
2242 * Only one allowed at a time.
2244 if (nfs_pub.np_valid != 0 && mp != nfs_pub.np_mount)
2248 * Get real filehandle for root of exported FS.
2250 bzero((caddr_t)&nfs_pub.np_handle, sizeof(nfs_pub.np_handle));
2251 nfs_pub.np_handle.fh_fsid = mp->mnt_stat.f_fsid;
2253 if ((error = VFS_ROOT(mp, &rvp)))
2256 if ((error = VFS_VPTOFH(rvp, &nfs_pub.np_handle.fh_fid)))
2262 * If an indexfile was specified, pull it in.
2264 if (argp->ex_indexfile != NULL) {
2267 error = vn_get_namelen(rvp, &namelen);
2270 nfs_pub.np_index = kmalloc(namelen, M_TEMP, M_WAITOK);
2271 error = copyinstr(argp->ex_indexfile, nfs_pub.np_index,
2275 * Check for illegal filenames.
2277 for (cp = nfs_pub.np_index; *cp; cp++) {
2285 kfree(nfs_pub.np_index, M_TEMP);
2290 nfs_pub.np_mount = mp;
2291 nfs_pub.np_valid = 1;
2296 vfs_export_lookup(struct mount *mp, struct netexport *nep,
2297 struct sockaddr *nam)
2300 struct radix_node_head *rnh;
2301 struct sockaddr *saddr;
2304 if (mp->mnt_flag & MNT_EXPORTED) {
2306 * Lookup in the export list first.
2311 switch (saddr->sa_family) {
2314 rnh = nep->ne_inethead;
2319 rnh = nep->ne_inet6head;
2326 np = (struct netcred *)
2327 (*rnh->rnh_matchaddr)((char *)saddr,
2329 if (np && np->netc_rnodes->rn_flags & RNF_ROOT)
2335 * If no address match, use the default if it exists.
2337 if (np == NULL && mp->mnt_flag & MNT_DEFEXPORTED)
2338 np = &nep->ne_defexported;
2344 * perform msync on all vnodes under a mount point. The mount point must
2345 * be locked. This code is also responsible for lazy-freeing unreferenced
2346 * vnodes whos VM objects no longer contain pages.
2348 * NOTE: MNT_WAIT still skips vnodes in the VXLOCK state.
2350 * NOTE: XXX VOP_PUTPAGES and friends requires that the vnode be locked,
2351 * but vnode_pager_putpages() doesn't lock the vnode. We have to do it
2352 * way up in this high level function.
2354 static int vfs_msync_scan1(struct mount *mp, struct vnode *vp, void *data);
2355 static int vfs_msync_scan2(struct mount *mp, struct vnode *vp, void *data);
2358 vfs_msync(struct mount *mp, int flags)
2363 * tmpfs sets this flag to prevent msync(), sync, and the
2364 * filesystem periodic syncer from trying to flush VM pages
2365 * to swap. Only pure memory pressure flushes tmpfs VM pages
2368 if (mp->mnt_kern_flag & MNTK_NOMSYNC)
2372 * Ok, scan the vnodes for work. If the filesystem is using the
2373 * syncer thread feature we can use vsyncscan() instead of
2374 * vmntvnodescan(), which is much faster.
2376 vmsc_flags = VMSC_GETVP;
2377 if (flags != MNT_WAIT)
2378 vmsc_flags |= VMSC_NOWAIT;
2380 if (mp->mnt_kern_flag & MNTK_THR_SYNC) {
2381 vsyncscan(mp, vmsc_flags, vfs_msync_scan2,
2382 (void *)(intptr_t)flags);
2384 vmntvnodescan(mp, vmsc_flags,
2385 vfs_msync_scan1, vfs_msync_scan2,
2386 (void *)(intptr_t)flags);
2391 * scan1 is a fast pre-check. There could be hundreds of thousands of
2392 * vnodes, we cannot afford to do anything heavy weight until we have a
2393 * fairly good indication that there is work to do.
2395 * The new namecache holds the vnode for each v_namecache association
2396 * so allow these refs.
2400 vfs_msync_scan1(struct mount *mp, struct vnode *vp, void *data)
2402 int flags = (int)(intptr_t)data;
2404 if ((vp->v_flag & VRECLAIMED) == 0) {
2405 if (vp->v_auxrefs == vp->v_namecache_count &&
2406 VREFCNT(vp) <= 0 && vp->v_object) {
2407 return(0); /* call scan2 */
2409 if ((mp->mnt_flag & MNT_RDONLY) == 0 &&
2410 (vp->v_flag & VOBJDIRTY) &&
2411 (flags == MNT_WAIT || vn_islocked(vp) == 0)) {
2412 return(0); /* call scan2 */
2417 * do not call scan2, continue the loop
2423 * This callback is handed a locked vnode.
2427 vfs_msync_scan2(struct mount *mp, struct vnode *vp, void *data)
2430 int flags = (int)(intptr_t)data;
2433 if (vp->v_flag & VRECLAIMED)
2436 if ((mp->mnt_flag & MNT_RDONLY) == 0 && (vp->v_flag & VOBJDIRTY)) {
2437 if ((obj = vp->v_object) != NULL) {
2438 if (flags == MNT_WAIT) {
2440 * VFS_MSYNC is called with MNT_WAIT when
2443 opcflags = OBJPC_SYNC;
2444 } else if (vp->v_writecount || obj->ref_count) {
2446 * VFS_MSYNC is otherwise called via the
2447 * periodic filesystem sync or the 'sync'
2448 * command. Honor MADV_NOSYNC / MAP_NOSYNC
2449 * if the file is open for writing or memory
2450 * mapped. Pages flagged PG_NOSYNC will not
2451 * be automatically flushed at this time.
2453 * The obj->ref_count test is not perfect
2454 * since temporary refs may be present, but
2455 * the periodic filesystem sync will ultimately
2456 * catch it if the file is not open and not
2459 opcflags = OBJPC_NOSYNC;
2462 * If the file is no longer open for writing
2463 * and also no longer mapped, do not honor
2464 * MAP_NOSYNC. That is, fully synchronize
2467 * This still occurs on the periodic fs sync,
2468 * so frontend programs which turn the file
2469 * over quickly enough can still avoid the
2470 * sync, but ultimately we do want to flush
2471 * even MADV_NOSYNC pages once it is no longer
2472 * mapped or open for writing.
2476 vm_object_page_clean(obj, 0, 0, opcflags);
2483 * Wake up anyone interested in vp because it is being revoked.
2486 vn_gone(struct vnode *vp)
2488 lwkt_gettoken(&vp->v_token);
2489 KNOTE(&vp->v_pollinfo.vpi_kqinfo.ki_note, NOTE_REVOKE);
2490 lwkt_reltoken(&vp->v_token);
2494 * extract the cdev_t from a VBLK or VCHR. The vnode must have been opened
2495 * (or v_rdev might be NULL).
2498 vn_todev(struct vnode *vp)
2500 if (vp->v_type != VBLK && vp->v_type != VCHR)
2502 KKASSERT(vp->v_rdev != NULL);
2503 return (vp->v_rdev);
2507 * Check if vnode represents a disk device. The vnode does not need to be
2513 vn_isdisk(struct vnode *vp, int *errp)
2517 if (vp->v_type != VCHR) {
2530 if (dev_is_good(dev) == 0) {
2535 if ((dev_dflags(dev) & D_DISK) == 0) {
2546 vn_get_namelen(struct vnode *vp, int *namelen)
2549 register_t retval[2];
2551 error = VOP_PATHCONF(vp, _PC_NAME_MAX, retval);
2554 *namelen = (int)retval[0];
2559 vop_write_dirent(int *error, struct uio *uio, ino_t d_ino, uint8_t d_type,
2560 uint16_t d_namlen, const char *d_name)
2565 len = _DIRENT_RECLEN(d_namlen);
2566 if (len > uio->uio_resid)
2569 dp = kmalloc(len, M_TEMP, M_WAITOK | M_ZERO);
2572 dp->d_namlen = d_namlen;
2573 dp->d_type = d_type;
2574 bcopy(d_name, dp->d_name, d_namlen);
2576 *error = uiomove((caddr_t)dp, len, uio);
2584 vn_mark_atime(struct vnode *vp, struct thread *td)
2586 struct proc *p = td->td_proc;
2587 struct ucred *cred = p ? p->p_ucred : proc0.p_ucred;
2589 if ((vp->v_mount->mnt_flag & (MNT_NOATIME | MNT_RDONLY)) == 0) {
2590 VOP_MARKATIME(vp, cred);
2595 * Calculate the number of entries in an inode-related chained hash table.
2596 * With today's memory sizes, maxvnodes can wind up being a very large
2597 * number. There is no reason to waste memory, so tolerate some stacking.
2600 vfs_inodehashsize(void)
2605 while (hsize < maxvnodes)
2607 while (hsize > maxvnodes * 2)
2608 hsize >>= 1; /* nominal 2x stacking */
2610 if (maxvnodes > 1024 * 1024)
2611 hsize >>= 1; /* nominal 8x stacking */
2613 if (maxvnodes > 128 * 1024)
2614 hsize >>= 1; /* nominal 4x stacking */
2627 #define SETHIGH(q, h) { \
2630 tmp.val[_QUAD_HIGHWORD] = (h); \
2633 #define SETLOW(q, l) { \
2636 tmp.val[_QUAD_LOWWORD] = (l); \
2641 init_va_filerev(void)
2646 getmicrouptime(&tv);
2647 SETHIGH(ret, tv.tv_sec);
2648 SETLOW(ret, tv.tv_usec * 4294);