if_vtnet - Use ifsq_watchdog_* functions as the watchdog.
[dragonfly.git] / sys / kern / vfs_subr.c
blob718092d5c362778972a401e406c61831e14b8b46
1 /*
2 * Copyright (c) 1989, 1993
3 * The Regents of the University of California. All rights reserved.
4 * (c) UNIX System Laboratories, Inc.
5 * All or some portions of this file are derived from material licensed
6 * to the University of California by American Telephone and Telegraph
7 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8 * the permission of UNIX System Laboratories, Inc.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * SUCH DAMAGE.
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
41 #include "opt_ddb.h"
42 #include "opt_inet.h"
43 #include "opt_inet6.h"
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/buf.h>
48 #include <sys/conf.h>
49 #include <sys/dirent.h>
50 #include <sys/eventhandler.h>
51 #include <sys/fcntl.h>
52 #include <sys/file.h>
53 #include <sys/kernel.h>
54 #include <sys/kthread.h>
55 #include <sys/malloc.h>
56 #include <sys/mbuf.h>
57 #include <sys/mount.h>
58 #include <sys/priv.h>
59 #include <sys/proc.h>
60 #include <sys/reboot.h>
61 #include <sys/socket.h>
62 #include <sys/stat.h>
63 #include <sys/sysctl.h>
64 #include <sys/syslog.h>
65 #include <sys/unistd.h>
66 #include <sys/vmmeter.h>
67 #include <sys/vnode.h>
69 #include <machine/limits.h>
71 #include <vm/vm.h>
72 #include <vm/vm_object.h>
73 #include <vm/vm_extern.h>
74 #include <vm/vm_kern.h>
75 #include <vm/pmap.h>
76 #include <vm/vm_map.h>
77 #include <vm/vm_page.h>
78 #include <vm/vm_pager.h>
79 #include <vm/vnode_pager.h>
80 #include <vm/vm_zone.h>
82 #include <sys/buf2.h>
83 #include <sys/thread2.h>
84 #include <sys/mplock2.h>
85 #include <vm/vm_page2.h>
87 #include <netinet/in.h>
89 static MALLOC_DEFINE(M_NETCRED, "Export Host", "Export host address structure");
91 int numvnodes;
92 SYSCTL_INT(_debug, OID_AUTO, numvnodes, CTLFLAG_RD, &numvnodes, 0,
93 "Number of vnodes allocated");
94 int verbose_reclaims;
95 SYSCTL_INT(_debug, OID_AUTO, verbose_reclaims, CTLFLAG_RD, &verbose_reclaims, 0,
96 "Output filename of reclaimed vnode(s)");
98 enum vtype iftovt_tab[16] = {
99 VNON, VFIFO, VCHR, VNON, VDIR, VNON, VBLK, VNON,
100 VREG, VNON, VLNK, VNON, VSOCK, VNON, VNON, VBAD,
102 int vttoif_tab[9] = {
103 0, S_IFREG, S_IFDIR, S_IFBLK, S_IFCHR, S_IFLNK,
104 S_IFSOCK, S_IFIFO, S_IFMT,
107 static int reassignbufcalls;
108 SYSCTL_INT(_vfs, OID_AUTO, reassignbufcalls, CTLFLAG_RW, &reassignbufcalls,
109 0, "Number of times buffers have been reassigned to the proper list");
111 static int check_buf_overlap = 2; /* invasive check */
112 SYSCTL_INT(_vfs, OID_AUTO, check_buf_overlap, CTLFLAG_RW, &check_buf_overlap,
113 0, "Enable overlapping buffer checks");
115 int nfs_mount_type = -1;
116 static struct lwkt_token spechash_token;
117 struct nfs_public nfs_pub; /* publicly exported FS */
119 int maxvnodes;
120 SYSCTL_INT(_kern, KERN_MAXVNODES, maxvnodes, CTLFLAG_RW,
121 &maxvnodes, 0, "Maximum number of vnodes");
123 static struct radix_node_head *vfs_create_addrlist_af(int af,
124 struct netexport *nep);
125 static void vfs_free_addrlist (struct netexport *nep);
126 static int vfs_free_netcred (struct radix_node *rn, void *w);
127 static void vfs_free_addrlist_af (struct radix_node_head **prnh);
128 static int vfs_hang_addrlist (struct mount *mp, struct netexport *nep,
129 const struct export_args *argp);
131 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);
140 static int
141 rb_buf_compare(struct buf *b1, struct buf *b2)
143 if (b1->b_loffset < b2->b_loffset)
144 return(-1);
145 if (b1->b_loffset > b2->b_loffset)
146 return(1);
147 return(0);
151 * Initialize the vnode management data structures.
153 * Called from vfsinit()
155 void
156 vfs_subr_init(void)
158 int factor1;
159 int factor2;
162 * Desiredvnodes is kern.maxvnodes. We want to scale it
163 * according to available system memory but we may also have
164 * to limit it based on available KVM.
166 * WARNING! For machines with 64-256M of ram we have to be sure
167 * that the default limit scales down well due to HAMMER
168 * taking up significantly more memory per-vnode vs UFS.
169 * We want around ~5800 on a 128M machine.
171 * WARNING! Now that KVM is substantially larger (e.g. 8TB+),
172 * also limit maxvnodes based on a 128GB metric. This
173 * gives us something like ~3 millon vnodes. sysctl
174 * can be used to increase it further if desired.
176 * For disk cachhing purposes, filesystems like HAMMER1
177 * and HAMMER2 will or can be told to cache file data
178 * via the block device instead of excessively in vnodes.
180 factor1 = 25 * (sizeof(struct vm_object) + sizeof(struct vnode));
181 factor2 = 30 * (sizeof(struct vm_object) + sizeof(struct vnode));
182 maxvnodes = imin((int64_t)vmstats.v_page_count * PAGE_SIZE / factor1,
183 KvaSize / factor2);
184 maxvnodes = imax(maxvnodes, maxproc * 8);
185 maxvnodes = imin(maxvnodes, 64LL*1024*1024*1024 / factor2);
187 lwkt_token_init(&spechash_token, "spechash");
191 * Knob to control the precision of file timestamps:
193 * 0 = seconds only; nanoseconds zeroed.
194 * 1 = seconds and nanoseconds, accurate within 1/HZ.
195 * 2 = seconds and nanoseconds, truncated to microseconds.
196 * >=3 = seconds and nanoseconds, maximum precision.
198 enum { TSP_SEC, TSP_HZ, TSP_USEC, TSP_NSEC };
200 static int timestamp_precision = TSP_SEC;
201 SYSCTL_INT(_vfs, OID_AUTO, timestamp_precision, CTLFLAG_RW,
202 &timestamp_precision, 0, "Precision of file timestamps");
205 * Get a current timestamp.
207 * MPSAFE
209 void
210 vfs_timestamp(struct timespec *tsp)
212 struct timeval tv;
214 switch (timestamp_precision) {
215 case TSP_SEC:
216 tsp->tv_sec = time_second;
217 tsp->tv_nsec = 0;
218 break;
219 case TSP_HZ:
220 getnanotime(tsp);
221 break;
222 case TSP_USEC:
223 microtime(&tv);
224 TIMEVAL_TO_TIMESPEC(&tv, tsp);
225 break;
226 case TSP_NSEC:
227 default:
228 nanotime(tsp);
229 break;
234 * Set vnode attributes to VNOVAL
236 void
237 vattr_null(struct vattr *vap)
239 vap->va_type = VNON;
240 vap->va_size = VNOVAL;
241 vap->va_bytes = VNOVAL;
242 vap->va_mode = VNOVAL;
243 vap->va_nlink = VNOVAL;
244 vap->va_uid = VNOVAL;
245 vap->va_gid = VNOVAL;
246 vap->va_fsid = VNOVAL;
247 vap->va_fileid = VNOVAL;
248 vap->va_blocksize = VNOVAL;
249 vap->va_rmajor = VNOVAL;
250 vap->va_rminor = VNOVAL;
251 vap->va_atime.tv_sec = VNOVAL;
252 vap->va_atime.tv_nsec = VNOVAL;
253 vap->va_mtime.tv_sec = VNOVAL;
254 vap->va_mtime.tv_nsec = VNOVAL;
255 vap->va_ctime.tv_sec = VNOVAL;
256 vap->va_ctime.tv_nsec = VNOVAL;
257 vap->va_flags = VNOVAL;
258 vap->va_gen = VNOVAL;
259 vap->va_vaflags = 0;
260 /* va_*_uuid fields are only valid if related flags are set */
264 * Flush out and invalidate all buffers associated with a vnode.
266 * vp must be locked.
268 static int vinvalbuf_bp(struct buf *bp, void *data);
270 struct vinvalbuf_bp_info {
271 struct vnode *vp;
272 int slptimeo;
273 int lkflags;
274 int flags;
275 int clean;
279 vinvalbuf(struct vnode *vp, int flags, int slpflag, int slptimeo)
281 struct vinvalbuf_bp_info info;
282 vm_object_t object;
283 int error;
285 lwkt_gettoken(&vp->v_token);
288 * If we are being asked to save, call fsync to ensure that the inode
289 * is updated.
291 if (flags & V_SAVE) {
292 error = bio_track_wait(&vp->v_track_write, slpflag, slptimeo);
293 if (error)
294 goto done;
295 if (!RB_EMPTY(&vp->v_rbdirty_tree)) {
296 if ((error = VOP_FSYNC(vp, MNT_WAIT, 0)) != 0)
297 goto done;
298 #if 0
300 * Dirty bufs may be left or generated via races
301 * in circumstances where vinvalbuf() is called on
302 * a vnode not undergoing reclamation. Only
303 * panic if we are trying to reclaim the vnode.
305 if ((vp->v_flag & VRECLAIMED) &&
306 (bio_track_active(&vp->v_track_write) ||
307 !RB_EMPTY(&vp->v_rbdirty_tree))) {
308 panic("vinvalbuf: dirty bufs");
310 #endif
313 info.slptimeo = slptimeo;
314 info.lkflags = LK_EXCLUSIVE | LK_SLEEPFAIL;
315 if (slpflag & PCATCH)
316 info.lkflags |= LK_PCATCH;
317 info.flags = flags;
318 info.vp = vp;
321 * Flush the buffer cache until nothing is left, wait for all I/O
322 * to complete. At least one pass is required. We might block
323 * in the pip code so we have to re-check. Order is important.
325 do {
327 * Flush buffer cache
329 if (!RB_EMPTY(&vp->v_rbclean_tree)) {
330 info.clean = 1;
331 error = RB_SCAN(buf_rb_tree, &vp->v_rbclean_tree,
332 NULL, vinvalbuf_bp, &info);
334 if (!RB_EMPTY(&vp->v_rbdirty_tree)) {
335 info.clean = 0;
336 error = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree,
337 NULL, vinvalbuf_bp, &info);
341 * Wait for I/O completion.
343 bio_track_wait(&vp->v_track_write, 0, 0);
344 if ((object = vp->v_object) != NULL)
345 refcount_wait(&object->paging_in_progress, "vnvlbx");
346 } while (bio_track_active(&vp->v_track_write) ||
347 !RB_EMPTY(&vp->v_rbclean_tree) ||
348 !RB_EMPTY(&vp->v_rbdirty_tree));
351 * Destroy the copy in the VM cache, too.
353 if ((object = vp->v_object) != NULL) {
354 vm_object_page_remove(object, 0, 0,
355 (flags & V_SAVE) ? TRUE : FALSE);
358 if (!RB_EMPTY(&vp->v_rbdirty_tree) || !RB_EMPTY(&vp->v_rbclean_tree))
359 panic("vinvalbuf: flush failed");
360 if (!RB_EMPTY(&vp->v_rbhash_tree))
361 panic("vinvalbuf: flush failed, buffers still present");
362 error = 0;
363 done:
364 lwkt_reltoken(&vp->v_token);
365 return (error);
368 static int
369 vinvalbuf_bp(struct buf *bp, void *data)
371 struct vinvalbuf_bp_info *info = data;
372 int error;
374 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
375 atomic_add_int(&bp->b_refs, 1);
376 error = BUF_TIMELOCK(bp, info->lkflags,
377 "vinvalbuf", info->slptimeo);
378 atomic_subtract_int(&bp->b_refs, 1);
379 if (error == 0) {
380 BUF_UNLOCK(bp);
381 error = ENOLCK;
383 if (error == ENOLCK)
384 return(0);
385 return (-error);
387 KKASSERT(bp->b_vp == info->vp);
390 * Must check clean/dirty status after successfully locking as
391 * it may race.
393 if ((info->clean && (bp->b_flags & B_DELWRI)) ||
394 (info->clean == 0 && (bp->b_flags & B_DELWRI) == 0)) {
395 BUF_UNLOCK(bp);
396 return(0);
400 * NOTE: NO B_LOCKED CHECK. Also no buf_checkwrite()
401 * check. This code will write out the buffer, period.
403 bremfree(bp);
404 if (((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI) &&
405 (info->flags & V_SAVE)) {
406 cluster_awrite(bp);
407 } else if (info->flags & V_SAVE) {
409 * Cannot set B_NOCACHE on a clean buffer as this will
410 * destroy the VM backing store which might actually
411 * be dirty (and unsynchronized).
413 bp->b_flags |= (B_INVAL | B_RELBUF);
414 brelse(bp);
415 } else {
416 bp->b_flags |= (B_INVAL | B_NOCACHE | B_RELBUF);
417 brelse(bp);
419 return(0);
423 * Truncate a file's buffer and pages to a specified length. This
424 * is in lieu of the old vinvalbuf mechanism, which performed unneeded
425 * sync activity.
427 * The vnode must be locked.
429 static int vtruncbuf_bp_trunc_cmp(struct buf *bp, void *data);
430 static int vtruncbuf_bp_trunc(struct buf *bp, void *data);
431 static int vtruncbuf_bp_metasync_cmp(struct buf *bp, void *data);
432 static int vtruncbuf_bp_metasync(struct buf *bp, void *data);
434 struct vtruncbuf_info {
435 struct vnode *vp;
436 off_t truncloffset;
437 int clean;
441 vtruncbuf(struct vnode *vp, off_t length, int blksize)
443 struct vtruncbuf_info info;
444 const char *filename;
445 int count;
448 * Round up to the *next* block, then destroy the buffers in question.
449 * Since we are only removing some of the buffers we must rely on the
450 * scan count to determine whether a loop is necessary.
452 if ((count = (int)(length % blksize)) != 0)
453 info.truncloffset = length + (blksize - count);
454 else
455 info.truncloffset = length;
456 info.vp = vp;
458 lwkt_gettoken(&vp->v_token);
459 do {
460 info.clean = 1;
461 count = RB_SCAN(buf_rb_tree, &vp->v_rbclean_tree,
462 vtruncbuf_bp_trunc_cmp,
463 vtruncbuf_bp_trunc, &info);
464 info.clean = 0;
465 count += RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree,
466 vtruncbuf_bp_trunc_cmp,
467 vtruncbuf_bp_trunc, &info);
468 } while(count);
471 * For safety, fsync any remaining metadata if the file is not being
472 * truncated to 0. Since the metadata does not represent the entire
473 * dirty list we have to rely on the hit count to ensure that we get
474 * all of it.
476 if (length > 0) {
477 do {
478 count = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree,
479 vtruncbuf_bp_metasync_cmp,
480 vtruncbuf_bp_metasync, &info);
481 } while (count);
485 * Clean out any left over VM backing store.
487 * It is possible to have in-progress I/O from buffers that were
488 * not part of the truncation. This should not happen if we
489 * are truncating to 0-length.
491 vnode_pager_setsize(vp, length);
492 bio_track_wait(&vp->v_track_write, 0, 0);
495 * Debugging only
497 spin_lock(&vp->v_spin);
498 filename = TAILQ_FIRST(&vp->v_namecache) ?
499 TAILQ_FIRST(&vp->v_namecache)->nc_name : "?";
500 spin_unlock(&vp->v_spin);
503 * Make sure no buffers were instantiated while we were trying
504 * to clean out the remaining VM pages. This could occur due
505 * to busy dirty VM pages being flushed out to disk.
507 do {
508 info.clean = 1;
509 count = RB_SCAN(buf_rb_tree, &vp->v_rbclean_tree,
510 vtruncbuf_bp_trunc_cmp,
511 vtruncbuf_bp_trunc, &info);
512 info.clean = 0;
513 count += RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree,
514 vtruncbuf_bp_trunc_cmp,
515 vtruncbuf_bp_trunc, &info);
516 if (count) {
517 kprintf("Warning: vtruncbuf(): Had to re-clean %d "
518 "left over buffers in %s\n", count, filename);
520 } while(count);
522 lwkt_reltoken(&vp->v_token);
524 return (0);
528 * The callback buffer is beyond the new file EOF and must be destroyed.
529 * Note that the compare function must conform to the RB_SCAN's requirements.
531 static
533 vtruncbuf_bp_trunc_cmp(struct buf *bp, void *data)
535 struct vtruncbuf_info *info = data;
537 if (bp->b_loffset >= info->truncloffset)
538 return(0);
539 return(-1);
542 static
543 int
544 vtruncbuf_bp_trunc(struct buf *bp, void *data)
546 struct vtruncbuf_info *info = data;
549 * Do not try to use a buffer we cannot immediately lock, but sleep
550 * anyway to prevent a livelock. The code will loop until all buffers
551 * can be acted upon.
553 * We must always revalidate the buffer after locking it to deal
554 * with MP races.
556 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
557 atomic_add_int(&bp->b_refs, 1);
558 if (BUF_LOCK(bp, LK_EXCLUSIVE|LK_SLEEPFAIL) == 0)
559 BUF_UNLOCK(bp);
560 atomic_subtract_int(&bp->b_refs, 1);
561 } else if ((info->clean && (bp->b_flags & B_DELWRI)) ||
562 (info->clean == 0 && (bp->b_flags & B_DELWRI) == 0) ||
563 bp->b_vp != info->vp ||
564 vtruncbuf_bp_trunc_cmp(bp, data)) {
565 BUF_UNLOCK(bp);
566 } else {
567 bremfree(bp);
568 bp->b_flags |= (B_INVAL | B_RELBUF | B_NOCACHE);
569 brelse(bp);
571 return(1);
575 * Fsync all meta-data after truncating a file to be non-zero. Only metadata
576 * blocks (with a negative loffset) are scanned.
577 * Note that the compare function must conform to the RB_SCAN's requirements.
579 static int
580 vtruncbuf_bp_metasync_cmp(struct buf *bp, void *data __unused)
582 if (bp->b_loffset < 0)
583 return(0);
584 return(1);
587 static int
588 vtruncbuf_bp_metasync(struct buf *bp, void *data)
590 struct vtruncbuf_info *info = data;
592 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
593 atomic_add_int(&bp->b_refs, 1);
594 if (BUF_LOCK(bp, LK_EXCLUSIVE|LK_SLEEPFAIL) == 0)
595 BUF_UNLOCK(bp);
596 atomic_subtract_int(&bp->b_refs, 1);
597 } else if ((bp->b_flags & B_DELWRI) == 0 ||
598 bp->b_vp != info->vp ||
599 vtruncbuf_bp_metasync_cmp(bp, data)) {
600 BUF_UNLOCK(bp);
601 } else {
602 bremfree(bp);
603 if (bp->b_vp == info->vp)
604 bawrite(bp);
605 else
606 bwrite(bp);
608 return(1);
612 * vfsync - implements a multipass fsync on a file which understands
613 * dependancies and meta-data. The passed vnode must be locked. The
614 * waitfor argument may be MNT_WAIT or MNT_NOWAIT, or MNT_LAZY.
616 * When fsyncing data asynchronously just do one consolidated pass starting
617 * with the most negative block number. This may not get all the data due
618 * to dependancies.
620 * When fsyncing data synchronously do a data pass, then a metadata pass,
621 * then do additional data+metadata passes to try to get all the data out.
623 * Caller must ref the vnode but does not have to lock it.
625 static int vfsync_wait_output(struct vnode *vp,
626 int (*waitoutput)(struct vnode *, struct thread *));
627 static int vfsync_dummy_cmp(struct buf *bp __unused, void *data __unused);
628 static int vfsync_data_only_cmp(struct buf *bp, void *data);
629 static int vfsync_meta_only_cmp(struct buf *bp, void *data);
630 static int vfsync_lazy_range_cmp(struct buf *bp, void *data);
631 static int vfsync_bp(struct buf *bp, void *data);
633 struct vfsync_info {
634 struct vnode *vp;
635 int fastpass;
636 int synchronous;
637 int syncdeps;
638 int lazycount;
639 int lazylimit;
640 int skippedbufs;
641 int (*checkdef)(struct buf *);
642 int (*cmpfunc)(struct buf *, void *);
646 vfsync(struct vnode *vp, int waitfor, int passes,
647 int (*checkdef)(struct buf *),
648 int (*waitoutput)(struct vnode *, struct thread *))
650 struct vfsync_info info;
651 int error;
653 bzero(&info, sizeof(info));
654 info.vp = vp;
655 if ((info.checkdef = checkdef) == NULL)
656 info.syncdeps = 1;
658 lwkt_gettoken(&vp->v_token);
660 switch(waitfor) {
661 case MNT_LAZY | MNT_NOWAIT:
662 case MNT_LAZY:
664 * Lazy (filesystem syncer typ) Asynchronous plus limit the
665 * number of data (not meta) pages we try to flush to 1MB.
666 * A non-zero return means that lazy limit was reached.
668 info.lazylimit = 1024 * 1024;
669 info.syncdeps = 1;
670 info.cmpfunc = vfsync_lazy_range_cmp;
671 error = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree,
672 vfsync_lazy_range_cmp, vfsync_bp, &info);
673 info.cmpfunc = vfsync_meta_only_cmp;
674 RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree,
675 vfsync_meta_only_cmp, vfsync_bp, &info);
676 if (error == 0)
677 vp->v_lazyw = 0;
678 else if (!RB_EMPTY(&vp->v_rbdirty_tree))
679 vn_syncer_add(vp, 1);
680 error = 0;
681 break;
682 case MNT_NOWAIT:
684 * Asynchronous. Do a data-only pass and a meta-only pass.
686 info.syncdeps = 1;
687 info.cmpfunc = vfsync_data_only_cmp;
688 RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, vfsync_data_only_cmp,
689 vfsync_bp, &info);
690 info.cmpfunc = vfsync_meta_only_cmp;
691 RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, vfsync_meta_only_cmp,
692 vfsync_bp, &info);
693 error = 0;
694 break;
695 default:
697 * Synchronous. Do a data-only pass, then a meta-data+data
698 * pass, then additional integrated passes to try to get
699 * all the dependancies flushed.
701 info.cmpfunc = vfsync_data_only_cmp;
702 info.fastpass = 1;
703 RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, vfsync_data_only_cmp,
704 vfsync_bp, &info);
705 info.fastpass = 0;
706 error = vfsync_wait_output(vp, waitoutput);
707 if (error == 0) {
708 info.skippedbufs = 0;
709 info.cmpfunc = vfsync_dummy_cmp;
710 RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, NULL,
711 vfsync_bp, &info);
712 error = vfsync_wait_output(vp, waitoutput);
713 if (info.skippedbufs) {
714 kprintf("Warning: vfsync skipped %d dirty "
715 "buf%s in pass2!\n",
716 info.skippedbufs,
717 ((info.skippedbufs > 1) ? "s" : ""));
720 while (error == 0 && passes > 0 &&
721 !RB_EMPTY(&vp->v_rbdirty_tree)
723 info.skippedbufs = 0;
724 if (--passes == 0) {
725 info.synchronous = 1;
726 info.syncdeps = 1;
728 info.cmpfunc = vfsync_dummy_cmp;
729 error = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, NULL,
730 vfsync_bp, &info);
731 if (error < 0)
732 error = -error;
733 info.syncdeps = 1;
734 if (error == 0)
735 error = vfsync_wait_output(vp, waitoutput);
736 if (info.skippedbufs && passes == 0) {
737 kprintf("Warning: vfsync skipped %d dirty "
738 "buf%s in final pass!\n",
739 info.skippedbufs,
740 ((info.skippedbufs > 1) ? "s" : ""));
743 #if 0
745 * This case can occur normally because vnode lock might
746 * not be held.
748 if (!RB_EMPTY(&vp->v_rbdirty_tree))
749 kprintf("dirty bufs left after final pass\n");
750 #endif
751 break;
753 lwkt_reltoken(&vp->v_token);
755 return(error);
758 static int
759 vfsync_wait_output(struct vnode *vp,
760 int (*waitoutput)(struct vnode *, struct thread *))
762 int error;
764 error = bio_track_wait(&vp->v_track_write, 0, 0);
765 if (waitoutput)
766 error = waitoutput(vp, curthread);
767 return(error);
770 static int
771 vfsync_dummy_cmp(struct buf *bp __unused, void *data __unused)
773 return(0);
776 static int
777 vfsync_data_only_cmp(struct buf *bp, void *data)
779 if (bp->b_loffset < 0)
780 return(-1);
781 return(0);
784 static int
785 vfsync_meta_only_cmp(struct buf *bp, void *data)
787 if (bp->b_loffset < 0)
788 return(0);
789 return(1);
792 static int
793 vfsync_lazy_range_cmp(struct buf *bp, void *data)
795 struct vfsync_info *info = data;
797 if (bp->b_loffset < info->vp->v_lazyw)
798 return(-1);
799 return(0);
802 static int
803 vfsync_bp(struct buf *bp, void *data)
805 struct vfsync_info *info = data;
806 struct vnode *vp = info->vp;
807 int error;
809 if (info->fastpass) {
811 * Ignore buffers that we cannot immediately lock.
813 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
814 if (BUF_TIMELOCK(bp, LK_EXCLUSIVE, "bflst1", 1)) {
815 ++info->skippedbufs;
816 return(0);
819 } else if (info->synchronous == 0) {
821 * Normal pass, give the buffer a little time to become
822 * available to us.
824 if (BUF_TIMELOCK(bp, LK_EXCLUSIVE, "bflst2", hz / 10)) {
825 ++info->skippedbufs;
826 return(0);
828 } else {
830 * Synchronous pass, give the buffer a lot of time before
831 * giving up.
833 if (BUF_TIMELOCK(bp, LK_EXCLUSIVE, "bflst3", hz * 10)) {
834 ++info->skippedbufs;
835 return(0);
840 * We must revalidate the buffer after locking.
842 if ((bp->b_flags & B_DELWRI) == 0 ||
843 bp->b_vp != info->vp ||
844 info->cmpfunc(bp, data)) {
845 BUF_UNLOCK(bp);
846 return(0);
850 * If syncdeps is not set we do not try to write buffers which have
851 * dependancies.
853 if (!info->synchronous && info->syncdeps == 0 && info->checkdef(bp)) {
854 BUF_UNLOCK(bp);
855 return(0);
859 * B_NEEDCOMMIT (primarily used by NFS) is a state where the buffer
860 * has been written but an additional handshake with the device
861 * is required before we can dispose of the buffer. We have no idea
862 * how to do this so we have to skip these buffers.
864 if (bp->b_flags & B_NEEDCOMMIT) {
865 BUF_UNLOCK(bp);
866 return(0);
870 * Ask bioops if it is ok to sync. If not the VFS may have
871 * set B_LOCKED so we have to cycle the buffer.
873 if (LIST_FIRST(&bp->b_dep) != NULL && buf_checkwrite(bp)) {
874 bremfree(bp);
875 brelse(bp);
876 return(0);
879 if (info->synchronous) {
881 * Synchronous flush. An error may be returned and will
882 * stop the scan.
884 bremfree(bp);
885 error = bwrite(bp);
886 } else {
888 * Asynchronous flush. We use the error return to support
889 * MNT_LAZY flushes.
891 * In low-memory situations we revert to synchronous
892 * operation. This should theoretically prevent the I/O
893 * path from exhausting memory in a non-recoverable way.
895 vp->v_lazyw = bp->b_loffset;
896 bremfree(bp);
897 if (vm_page_count_min(0)) {
898 /* low memory */
899 info->lazycount += bp->b_bufsize;
900 bwrite(bp);
901 } else {
902 /* normal */
903 info->lazycount += cluster_awrite(bp);
904 waitrunningbufspace();
905 /*vm_wait_nominal();*/
907 if (info->lazylimit && info->lazycount >= info->lazylimit)
908 error = 1;
909 else
910 error = 0;
912 return(-error);
916 * Associate a buffer with a vnode.
918 * MPSAFE
921 bgetvp(struct vnode *vp, struct buf *bp, int testsize)
923 KASSERT(bp->b_vp == NULL, ("bgetvp: not free"));
924 KKASSERT((bp->b_flags & (B_HASHED|B_DELWRI|B_VNCLEAN|B_VNDIRTY)) == 0);
927 * Insert onto list for new vnode.
929 lwkt_gettoken(&vp->v_token);
931 if (buf_rb_hash_RB_INSERT(&vp->v_rbhash_tree, bp)) {
932 lwkt_reltoken(&vp->v_token);
933 return (EEXIST);
937 * Diagnostics (mainly for HAMMER debugging). Check for
938 * overlapping buffers.
940 if (check_buf_overlap) {
941 struct buf *bx;
942 bx = buf_rb_hash_RB_PREV(bp);
943 if (bx) {
944 if (bx->b_loffset + bx->b_bufsize > bp->b_loffset) {
945 kprintf("bgetvp: overlapl %016jx/%d %016jx "
946 "bx %p bp %p\n",
947 (intmax_t)bx->b_loffset,
948 bx->b_bufsize,
949 (intmax_t)bp->b_loffset,
950 bx, bp);
951 if (check_buf_overlap > 1)
952 panic("bgetvp - overlapping buffer");
955 bx = buf_rb_hash_RB_NEXT(bp);
956 if (bx) {
957 if (bp->b_loffset + testsize > bx->b_loffset) {
958 kprintf("bgetvp: overlapr %016jx/%d %016jx "
959 "bp %p bx %p\n",
960 (intmax_t)bp->b_loffset,
961 testsize,
962 (intmax_t)bx->b_loffset,
963 bp, bx);
964 if (check_buf_overlap > 1)
965 panic("bgetvp - overlapping buffer");
969 bp->b_vp = vp;
970 bp->b_flags |= B_HASHED;
971 bp->b_flags |= B_VNCLEAN;
972 if (buf_rb_tree_RB_INSERT(&vp->v_rbclean_tree, bp))
973 panic("reassignbuf: dup lblk/clean vp %p bp %p", vp, bp);
974 /*vhold(vp);*/
975 lwkt_reltoken(&vp->v_token);
976 return(0);
980 * Disassociate a buffer from a vnode.
982 * MPSAFE
984 void
985 brelvp(struct buf *bp)
987 struct vnode *vp;
989 KASSERT(bp->b_vp != NULL, ("brelvp: NULL"));
992 * Delete from old vnode list, if on one.
994 vp = bp->b_vp;
995 lwkt_gettoken(&vp->v_token);
996 if (bp->b_flags & (B_VNDIRTY | B_VNCLEAN)) {
997 if (bp->b_flags & B_VNDIRTY)
998 buf_rb_tree_RB_REMOVE(&vp->v_rbdirty_tree, bp);
999 else
1000 buf_rb_tree_RB_REMOVE(&vp->v_rbclean_tree, bp);
1001 bp->b_flags &= ~(B_VNDIRTY | B_VNCLEAN);
1003 if (bp->b_flags & B_HASHED) {
1004 buf_rb_hash_RB_REMOVE(&vp->v_rbhash_tree, bp);
1005 bp->b_flags &= ~B_HASHED;
1009 * Only remove from synclist when no dirty buffers are left AND
1010 * the VFS has not flagged the vnode's inode as being dirty.
1012 if ((vp->v_flag & (VONWORKLST | VISDIRTY | VOBJDIRTY)) == VONWORKLST &&
1013 RB_EMPTY(&vp->v_rbdirty_tree)) {
1014 vn_syncer_remove(vp, 0);
1016 bp->b_vp = NULL;
1018 lwkt_reltoken(&vp->v_token);
1020 /*vdrop(vp);*/
1024 * Reassign the buffer to the proper clean/dirty list based on B_DELWRI.
1025 * This routine is called when the state of the B_DELWRI bit is changed.
1027 * Must be called with vp->v_token held.
1028 * MPSAFE
1030 void
1031 reassignbuf(struct buf *bp)
1033 struct vnode *vp = bp->b_vp;
1034 int delay;
1036 ASSERT_LWKT_TOKEN_HELD(&vp->v_token);
1037 ++reassignbufcalls;
1040 * B_PAGING flagged buffers cannot be reassigned because their vp
1041 * is not fully linked in.
1043 if (bp->b_flags & B_PAGING)
1044 panic("cannot reassign paging buffer");
1046 if (bp->b_flags & B_DELWRI) {
1048 * Move to the dirty list, add the vnode to the worklist
1050 if (bp->b_flags & B_VNCLEAN) {
1051 buf_rb_tree_RB_REMOVE(&vp->v_rbclean_tree, bp);
1052 bp->b_flags &= ~B_VNCLEAN;
1054 if ((bp->b_flags & B_VNDIRTY) == 0) {
1055 if (buf_rb_tree_RB_INSERT(&vp->v_rbdirty_tree, bp)) {
1056 panic("reassignbuf: dup lblk vp %p bp %p",
1057 vp, bp);
1059 bp->b_flags |= B_VNDIRTY;
1061 if ((vp->v_flag & VONWORKLST) == 0) {
1062 switch (vp->v_type) {
1063 case VDIR:
1064 delay = dirdelay;
1065 break;
1066 case VCHR:
1067 case VBLK:
1068 if (vp->v_rdev &&
1069 vp->v_rdev->si_mountpoint != NULL) {
1070 delay = metadelay;
1071 break;
1073 /* fall through */
1074 default:
1075 delay = filedelay;
1077 vn_syncer_add(vp, delay);
1079 } else {
1081 * Move to the clean list, remove the vnode from the worklist
1082 * if no dirty blocks remain.
1084 if (bp->b_flags & B_VNDIRTY) {
1085 buf_rb_tree_RB_REMOVE(&vp->v_rbdirty_tree, bp);
1086 bp->b_flags &= ~B_VNDIRTY;
1088 if ((bp->b_flags & B_VNCLEAN) == 0) {
1089 if (buf_rb_tree_RB_INSERT(&vp->v_rbclean_tree, bp)) {
1090 panic("reassignbuf: dup lblk vp %p bp %p",
1091 vp, bp);
1093 bp->b_flags |= B_VNCLEAN;
1097 * Only remove from synclist when no dirty buffers are left
1098 * AND the VFS has not flagged the vnode's inode as being
1099 * dirty.
1101 if ((vp->v_flag & (VONWORKLST | VISDIRTY | VOBJDIRTY)) ==
1102 VONWORKLST &&
1103 RB_EMPTY(&vp->v_rbdirty_tree)) {
1104 vn_syncer_remove(vp, 0);
1110 * Create a vnode for a block device. Used for mounting the root file
1111 * system.
1113 * A vref()'d vnode is returned.
1115 extern struct vop_ops *devfs_vnode_dev_vops_p;
1117 bdevvp(cdev_t dev, struct vnode **vpp)
1119 struct vnode *vp;
1120 struct vnode *nvp;
1121 int error;
1123 if (dev == NULL) {
1124 *vpp = NULLVP;
1125 return (ENXIO);
1127 error = getspecialvnode(VT_NON, NULL, &devfs_vnode_dev_vops_p,
1128 &nvp, 0, 0);
1129 if (error) {
1130 *vpp = NULLVP;
1131 return (error);
1133 vp = nvp;
1134 vp->v_type = VCHR;
1135 #if 0
1136 vp->v_rdev = dev;
1137 #endif
1138 v_associate_rdev(vp, dev);
1139 vp->v_umajor = dev->si_umajor;
1140 vp->v_uminor = dev->si_uminor;
1141 vx_unlock(vp);
1142 *vpp = vp;
1143 return (0);
1147 v_associate_rdev(struct vnode *vp, cdev_t dev)
1149 if (dev == NULL)
1150 return(ENXIO);
1151 if (dev_is_good(dev) == 0)
1152 return(ENXIO);
1153 KKASSERT(vp->v_rdev == NULL);
1154 vp->v_rdev = reference_dev(dev);
1155 lwkt_gettoken(&spechash_token);
1156 SLIST_INSERT_HEAD(&dev->si_hlist, vp, v_cdevnext);
1157 lwkt_reltoken(&spechash_token);
1158 return(0);
1161 void
1162 v_release_rdev(struct vnode *vp)
1164 cdev_t dev;
1166 if ((dev = vp->v_rdev) != NULL) {
1167 lwkt_gettoken(&spechash_token);
1168 SLIST_REMOVE(&dev->si_hlist, vp, vnode, v_cdevnext);
1169 vp->v_rdev = NULL;
1170 release_dev(dev);
1171 lwkt_reltoken(&spechash_token);
1176 * Add a vnode to the alias list hung off the cdev_t. We only associate
1177 * the device number with the vnode. The actual device is not associated
1178 * until the vnode is opened (usually in spec_open()), and will be
1179 * disassociated on last close.
1181 void
1182 addaliasu(struct vnode *nvp, int x, int y)
1184 if (nvp->v_type != VBLK && nvp->v_type != VCHR)
1185 panic("addaliasu on non-special vnode");
1186 nvp->v_umajor = x;
1187 nvp->v_uminor = y;
1191 * Simple call that a filesystem can make to try to get rid of a
1192 * vnode. It will fail if anyone is referencing the vnode (including
1193 * the caller).
1195 * The filesystem can check whether its in-memory inode structure still
1196 * references the vp on return.
1198 * May only be called if the vnode is in a known state (i.e. being prevented
1199 * from being deallocated by some other condition such as a vfs inode hold).
1201 void
1202 vclean_unlocked(struct vnode *vp)
1204 vx_get(vp);
1205 if (VREFCNT(vp) <= 1)
1206 vgone_vxlocked(vp);
1207 vx_put(vp);
1211 * Disassociate a vnode from its underlying filesystem.
1213 * The vnode must be VX locked and referenced. In all normal situations
1214 * there are no active references. If vclean_vxlocked() is called while
1215 * there are active references, the vnode is being ripped out and we have
1216 * to call VOP_CLOSE() as appropriate before we can reclaim it.
1218 void
1219 vclean_vxlocked(struct vnode *vp, int flags)
1221 int active;
1222 int n;
1223 vm_object_t object;
1224 struct namecache *ncp;
1227 * If the vnode has already been reclaimed we have nothing to do.
1229 if (vp->v_flag & VRECLAIMED)
1230 return;
1233 * Set flag to interlock operation, flag finalization to ensure
1234 * that the vnode winds up on the inactive list, and set v_act to 0.
1236 vsetflags(vp, VRECLAIMED);
1237 atomic_set_int(&vp->v_refcnt, VREF_FINALIZE);
1238 vp->v_act = 0;
1240 if (verbose_reclaims) {
1241 if ((ncp = TAILQ_FIRST(&vp->v_namecache)) != NULL)
1242 kprintf("Debug: reclaim %p %s\n", vp, ncp->nc_name);
1246 * Scrap the vfs cache
1248 while (cache_inval_vp(vp, 0) != 0) {
1249 kprintf("Warning: vnode %p clean/cache_resolution "
1250 "race detected\n", vp);
1251 tsleep(vp, 0, "vclninv", 2);
1255 * Check to see if the vnode is in use. If so we have to reference it
1256 * before we clean it out so that its count cannot fall to zero and
1257 * generate a race against ourselves to recycle it.
1259 active = (VREFCNT(vp) > 0);
1262 * Clean out any buffers associated with the vnode and destroy its
1263 * object, if it has one.
1265 vinvalbuf(vp, V_SAVE, 0, 0);
1268 * If purging an active vnode (typically during a forced unmount
1269 * or reboot), it must be closed and deactivated before being
1270 * reclaimed. This isn't really all that safe, but what can
1271 * we do? XXX.
1273 * Note that neither of these routines unlocks the vnode.
1275 if (active && (flags & DOCLOSE)) {
1276 while ((n = vp->v_opencount) != 0) {
1277 if (vp->v_writecount)
1278 VOP_CLOSE(vp, FWRITE|FNONBLOCK, NULL);
1279 else
1280 VOP_CLOSE(vp, FNONBLOCK, NULL);
1281 if (vp->v_opencount == n) {
1282 kprintf("Warning: unable to force-close"
1283 " vnode %p\n", vp);
1284 break;
1290 * If the vnode has not been deactivated, deactivated it. Deactivation
1291 * can create new buffers and VM pages so we have to call vinvalbuf()
1292 * again to make sure they all get flushed.
1294 * This can occur if a file with a link count of 0 needs to be
1295 * truncated.
1297 * If the vnode is already dead don't try to deactivate it.
1299 if ((vp->v_flag & VINACTIVE) == 0) {
1300 vsetflags(vp, VINACTIVE);
1301 if (vp->v_mount)
1302 VOP_INACTIVE(vp);
1303 vinvalbuf(vp, V_SAVE, 0, 0);
1307 * If the vnode has an object, destroy it.
1309 while ((object = vp->v_object) != NULL) {
1310 vm_object_hold(object);
1311 if (object == vp->v_object)
1312 break;
1313 vm_object_drop(object);
1316 if (object != NULL) {
1317 if (object->ref_count == 0) {
1318 if ((object->flags & OBJ_DEAD) == 0)
1319 vm_object_terminate(object);
1320 vm_object_drop(object);
1321 vclrflags(vp, VOBJBUF);
1322 } else {
1323 vm_pager_deallocate(object);
1324 vclrflags(vp, VOBJBUF);
1325 vm_object_drop(object);
1328 KKASSERT((vp->v_flag & VOBJBUF) == 0);
1330 if (vp->v_flag & VOBJDIRTY)
1331 vclrobjdirty(vp);
1334 * Reclaim the vnode if not already dead.
1336 if (vp->v_mount && VOP_RECLAIM(vp))
1337 panic("vclean: cannot reclaim");
1340 * Done with purge, notify sleepers of the grim news.
1342 vp->v_ops = &dead_vnode_vops_p;
1343 vn_gone(vp);
1344 vp->v_tag = VT_NON;
1347 * If we are destroying an active vnode, reactivate it now that
1348 * we have reassociated it with deadfs. This prevents the system
1349 * from crashing on the vnode due to it being unexpectedly marked
1350 * as inactive or reclaimed.
1352 if (active && (flags & DOCLOSE)) {
1353 vclrflags(vp, VINACTIVE | VRECLAIMED);
1358 * Eliminate all activity associated with the requested vnode
1359 * and with all vnodes aliased to the requested vnode.
1361 * The vnode must be referenced but should not be locked.
1364 vrevoke(struct vnode *vp, struct ucred *cred)
1366 struct vnode *vq;
1367 struct vnode *vqn;
1368 cdev_t dev;
1369 int error;
1372 * If the vnode has a device association, scrap all vnodes associated
1373 * with the device. Don't let the device disappear on us while we
1374 * are scrapping the vnodes.
1376 * The passed vp will probably show up in the list, do not VX lock
1377 * it twice!
1379 * Releasing the vnode's rdev here can mess up specfs's call to
1380 * device close, so don't do it. The vnode has been disassociated
1381 * and the device will be closed after the last ref on the related
1382 * fp goes away (if not still open by e.g. the kernel).
1384 if (vp->v_type != VCHR) {
1385 error = fdrevoke(vp, DTYPE_VNODE, cred);
1386 return (error);
1388 if ((dev = vp->v_rdev) == NULL) {
1389 return(0);
1391 reference_dev(dev);
1392 lwkt_gettoken(&spechash_token);
1394 restart:
1395 vqn = SLIST_FIRST(&dev->si_hlist);
1396 if (vqn)
1397 vhold(vqn);
1398 while ((vq = vqn) != NULL) {
1399 if (VREFCNT(vq) > 0) {
1400 vref(vq);
1401 fdrevoke(vq, DTYPE_VNODE, cred);
1402 /*v_release_rdev(vq);*/
1403 vrele(vq);
1404 if (vq->v_rdev != dev) {
1405 vdrop(vq);
1406 goto restart;
1409 vqn = SLIST_NEXT(vq, v_cdevnext);
1410 if (vqn)
1411 vhold(vqn);
1412 vdrop(vq);
1414 lwkt_reltoken(&spechash_token);
1415 dev_drevoke(dev);
1416 release_dev(dev);
1417 return (0);
1421 * This is called when the object underlying a vnode is being destroyed,
1422 * such as in a remove(). Try to recycle the vnode immediately if the
1423 * only active reference is our reference.
1425 * Directory vnodes in the namecache with children cannot be immediately
1426 * recycled because numerous VOP_N*() ops require them to be stable.
1428 * To avoid recursive recycling from VOP_INACTIVE implemenetations this
1429 * function is a NOP if VRECLAIMED is already set.
1432 vrecycle(struct vnode *vp)
1434 if (VREFCNT(vp) <= 1 && (vp->v_flag & VRECLAIMED) == 0) {
1435 if (cache_inval_vp_nonblock(vp))
1436 return(0);
1437 vgone_vxlocked(vp);
1438 return (1);
1440 return (0);
1444 * Return the maximum I/O size allowed for strategy calls on VP.
1446 * If vp is VCHR or VBLK we dive the device, otherwise we use
1447 * the vp's mount info.
1449 * The returned value is clamped at MAXPHYS as most callers cannot use
1450 * buffers larger than that size.
1453 vmaxiosize(struct vnode *vp)
1455 int maxiosize;
1457 if (vp->v_type == VBLK || vp->v_type == VCHR)
1458 maxiosize = vp->v_rdev->si_iosize_max;
1459 else
1460 maxiosize = vp->v_mount->mnt_iosize_max;
1462 if (maxiosize > MAXPHYS)
1463 maxiosize = MAXPHYS;
1464 return (maxiosize);
1468 * Eliminate all activity associated with a vnode in preparation for
1469 * destruction.
1471 * The vnode must be VX locked and refd and will remain VX locked and refd
1472 * on return. This routine may be called with the vnode in any state, as
1473 * long as it is VX locked. The vnode will be cleaned out and marked
1474 * VRECLAIMED but will not actually be reused until all existing refs and
1475 * holds go away.
1477 * NOTE: This routine may be called on a vnode which has not yet been
1478 * already been deactivated (VOP_INACTIVE), or on a vnode which has
1479 * already been reclaimed.
1481 * This routine is not responsible for placing us back on the freelist.
1482 * Instead, it happens automatically when the caller releases the VX lock
1483 * (assuming there aren't any other references).
1485 void
1486 vgone_vxlocked(struct vnode *vp)
1489 * assert that the VX lock is held. This is an absolute requirement
1490 * now for vgone_vxlocked() to be called.
1492 KKASSERT(lockinuse(&vp->v_lock));
1495 * Clean out the filesystem specific data and set the VRECLAIMED
1496 * bit. Also deactivate the vnode if necessary.
1498 * The vnode should have automatically been removed from the syncer
1499 * list as syncer/dirty flags cleared during the cleaning.
1501 vclean_vxlocked(vp, DOCLOSE);
1504 * Normally panic if the vnode is still dirty, unless we are doing
1505 * a forced unmount (tmpfs typically).
1507 if (vp->v_flag & VONWORKLST) {
1508 if (vp->v_mount->mnt_kern_flag & MNTK_UNMOUNTF) {
1509 /* force removal */
1510 vn_syncer_remove(vp, 1);
1511 } else {
1512 panic("vp %p still dirty in vgone after flush", vp);
1517 * Delete from old mount point vnode list, if on one.
1519 if (vp->v_mount != NULL) {
1520 KKASSERT(vp->v_data == NULL);
1521 insmntque(vp, NULL);
1525 * If special device, remove it from special device alias list
1526 * if it is on one. This should normally only occur if a vnode is
1527 * being revoked as the device should otherwise have been released
1528 * naturally.
1530 if ((vp->v_type == VBLK || vp->v_type == VCHR) && vp->v_rdev != NULL) {
1531 v_release_rdev(vp);
1535 * Set us to VBAD
1537 vp->v_type = VBAD;
1541 * Lookup a vnode by device number.
1543 * Returns non-zero and *vpp set to a vref'd vnode on success.
1544 * Returns zero on failure.
1547 vfinddev(cdev_t dev, enum vtype type, struct vnode **vpp)
1549 struct vnode *vp;
1551 lwkt_gettoken(&spechash_token);
1552 SLIST_FOREACH(vp, &dev->si_hlist, v_cdevnext) {
1553 if (type == vp->v_type) {
1554 *vpp = vp;
1555 vref(vp);
1556 lwkt_reltoken(&spechash_token);
1557 return (1);
1560 lwkt_reltoken(&spechash_token);
1561 return (0);
1565 * Calculate the total number of references to a special device. This
1566 * routine may only be called for VBLK and VCHR vnodes since v_rdev is
1567 * an overloaded field. Since udev2dev can now return NULL, we have
1568 * to check for a NULL v_rdev.
1571 count_dev(cdev_t dev)
1573 struct vnode *vp;
1574 int count = 0;
1576 if (SLIST_FIRST(&dev->si_hlist)) {
1577 lwkt_gettoken(&spechash_token);
1578 SLIST_FOREACH(vp, &dev->si_hlist, v_cdevnext) {
1579 count += vp->v_opencount;
1581 lwkt_reltoken(&spechash_token);
1583 return(count);
1587 vcount(struct vnode *vp)
1589 if (vp->v_rdev == NULL)
1590 return(0);
1591 return(count_dev(vp->v_rdev));
1595 * Initialize VMIO for a vnode. This routine MUST be called before a
1596 * VFS can issue buffer cache ops on a vnode. It is typically called
1597 * when a vnode is initialized from its inode.
1600 vinitvmio(struct vnode *vp, off_t filesize, int blksize, int boff)
1602 vm_object_t object;
1603 int error = 0;
1605 object = vp->v_object;
1606 if (object) {
1607 vm_object_hold(object);
1608 KKASSERT(vp->v_object == object);
1611 if (object == NULL) {
1612 object = vnode_pager_alloc(vp, filesize, 0, 0, blksize, boff);
1615 * Dereference the reference we just created. This assumes
1616 * that the object is associated with the vp. Allow it to
1617 * have zero refs. It cannot be destroyed as long as it
1618 * is associated with the vnode.
1620 vm_object_hold(object);
1621 atomic_add_int(&object->ref_count, -1);
1622 vrele(vp);
1623 } else {
1624 KKASSERT((object->flags & OBJ_DEAD) == 0);
1626 KASSERT(vp->v_object != NULL, ("vinitvmio: NULL object"));
1627 vsetflags(vp, VOBJBUF);
1628 vm_object_drop(object);
1630 return (error);
1635 * Print out a description of a vnode.
1637 static char *typename[] =
1638 {"VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD"};
1640 void
1641 vprint(char *label, struct vnode *vp)
1643 char buf[96];
1645 if (label != NULL)
1646 kprintf("%s: %p: ", label, (void *)vp);
1647 else
1648 kprintf("%p: ", (void *)vp);
1649 kprintf("type %s, refcnt %08x, writecount %d, holdcnt %d,",
1650 typename[vp->v_type],
1651 vp->v_refcnt, vp->v_writecount, vp->v_auxrefs);
1652 buf[0] = '\0';
1653 if (vp->v_flag & VROOT)
1654 strcat(buf, "|VROOT");
1655 if (vp->v_flag & VPFSROOT)
1656 strcat(buf, "|VPFSROOT");
1657 if (vp->v_flag & VTEXT)
1658 strcat(buf, "|VTEXT");
1659 if (vp->v_flag & VSYSTEM)
1660 strcat(buf, "|VSYSTEM");
1661 if (vp->v_flag & VOBJBUF)
1662 strcat(buf, "|VOBJBUF");
1663 if (buf[0] != '\0')
1664 kprintf(" flags (%s)", &buf[1]);
1665 if (vp->v_data == NULL) {
1666 kprintf("\n");
1667 } else {
1668 kprintf("\n\t");
1669 VOP_PRINT(vp);
1674 * Do the usual access checking.
1675 * file_mode, uid and gid are from the vnode in question,
1676 * while acc_mode and cred are from the VOP_ACCESS parameter list
1679 vaccess(enum vtype type, mode_t file_mode, uid_t uid, gid_t gid,
1680 mode_t acc_mode, struct ucred *cred)
1682 mode_t mask;
1683 int ismember;
1686 * Super-user always gets read/write access, but execute access depends
1687 * on at least one execute bit being set.
1689 if (priv_check_cred(cred, PRIV_ROOT, 0) == 0) {
1690 if ((acc_mode & VEXEC) && type != VDIR &&
1691 (file_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0)
1692 return (EACCES);
1693 return (0);
1696 mask = 0;
1698 /* Otherwise, check the owner. */
1699 if (cred->cr_uid == uid) {
1700 if (acc_mode & VEXEC)
1701 mask |= S_IXUSR;
1702 if (acc_mode & VREAD)
1703 mask |= S_IRUSR;
1704 if (acc_mode & VWRITE)
1705 mask |= S_IWUSR;
1706 return ((file_mode & mask) == mask ? 0 : EACCES);
1709 /* Otherwise, check the groups. */
1710 ismember = groupmember(gid, cred);
1711 if (cred->cr_svgid == gid || ismember) {
1712 if (acc_mode & VEXEC)
1713 mask |= S_IXGRP;
1714 if (acc_mode & VREAD)
1715 mask |= S_IRGRP;
1716 if (acc_mode & VWRITE)
1717 mask |= S_IWGRP;
1718 return ((file_mode & mask) == mask ? 0 : EACCES);
1721 /* Otherwise, check everyone else. */
1722 if (acc_mode & VEXEC)
1723 mask |= S_IXOTH;
1724 if (acc_mode & VREAD)
1725 mask |= S_IROTH;
1726 if (acc_mode & VWRITE)
1727 mask |= S_IWOTH;
1728 return ((file_mode & mask) == mask ? 0 : EACCES);
1731 #ifdef DDB
1732 #include <ddb/ddb.h>
1734 static int db_show_locked_vnodes(struct mount *mp, void *data);
1737 * List all of the locked vnodes in the system.
1738 * Called when debugging the kernel.
1740 DB_SHOW_COMMAND(lockedvnodes, lockedvnodes)
1742 kprintf("Locked vnodes\n");
1743 mountlist_scan(db_show_locked_vnodes, NULL,
1744 MNTSCAN_FORWARD|MNTSCAN_NOBUSY);
1747 static int
1748 db_show_locked_vnodes(struct mount *mp, void *data __unused)
1750 struct vnode *vp;
1752 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
1753 if (vn_islocked(vp))
1754 vprint(NULL, vp);
1756 return(0);
1758 #endif
1761 * Top level filesystem related information gathering.
1763 static int sysctl_ovfs_conf (SYSCTL_HANDLER_ARGS);
1765 static int
1766 vfs_sysctl(SYSCTL_HANDLER_ARGS)
1768 int *name = (int *)arg1 - 1; /* XXX */
1769 u_int namelen = arg2 + 1; /* XXX */
1770 struct vfsconf *vfsp;
1771 int maxtypenum;
1773 #if 1 || defined(COMPAT_PRELITE2)
1774 /* Resolve ambiguity between VFS_VFSCONF and VFS_GENERIC. */
1775 if (namelen == 1)
1776 return (sysctl_ovfs_conf(oidp, arg1, arg2, req));
1777 #endif
1779 #ifdef notyet
1780 /* all sysctl names at this level are at least name and field */
1781 if (namelen < 2)
1782 return (ENOTDIR); /* overloaded */
1783 if (name[0] != VFS_GENERIC) {
1784 vfsp = vfsconf_find_by_typenum(name[0]);
1785 if (vfsp == NULL)
1786 return (EOPNOTSUPP);
1787 return ((*vfsp->vfc_vfsops->vfs_sysctl)(&name[1], namelen - 1,
1788 oldp, oldlenp, newp, newlen, p));
1790 #endif
1791 switch (name[1]) {
1792 case VFS_MAXTYPENUM:
1793 if (namelen != 2)
1794 return (ENOTDIR);
1795 maxtypenum = vfsconf_get_maxtypenum();
1796 return (SYSCTL_OUT(req, &maxtypenum, sizeof(maxtypenum)));
1797 case VFS_CONF:
1798 if (namelen != 3)
1799 return (ENOTDIR); /* overloaded */
1800 vfsp = vfsconf_find_by_typenum(name[2]);
1801 if (vfsp == NULL)
1802 return (EOPNOTSUPP);
1803 return (SYSCTL_OUT(req, vfsp, sizeof *vfsp));
1805 return (EOPNOTSUPP);
1808 SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RD, vfs_sysctl,
1809 "Generic filesystem");
1811 #if 1 || defined(COMPAT_PRELITE2)
1813 static int
1814 sysctl_ovfs_conf_iter(struct vfsconf *vfsp, void *data)
1816 int error;
1817 struct ovfsconf ovfs;
1818 struct sysctl_req *req = (struct sysctl_req*) data;
1820 bzero(&ovfs, sizeof(ovfs));
1821 ovfs.vfc_vfsops = vfsp->vfc_vfsops; /* XXX used as flag */
1822 strcpy(ovfs.vfc_name, vfsp->vfc_name);
1823 ovfs.vfc_index = vfsp->vfc_typenum;
1824 ovfs.vfc_refcount = vfsp->vfc_refcount;
1825 ovfs.vfc_flags = vfsp->vfc_flags;
1826 error = SYSCTL_OUT(req, &ovfs, sizeof ovfs);
1827 if (error)
1828 return error; /* abort iteration with error code */
1829 else
1830 return 0; /* continue iterating with next element */
1833 static int
1834 sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS)
1836 return vfsconf_each(sysctl_ovfs_conf_iter, (void*)req);
1839 #endif /* 1 || COMPAT_PRELITE2 */
1842 * Check to see if a filesystem is mounted on a block device.
1845 vfs_mountedon(struct vnode *vp)
1847 cdev_t dev;
1849 if ((dev = vp->v_rdev) == NULL) {
1850 /* if (vp->v_type != VBLK)
1851 dev = get_dev(vp->v_uminor, vp->v_umajor); */
1853 if (dev != NULL && dev->si_mountpoint)
1854 return (EBUSY);
1855 return (0);
1859 * Unmount all filesystems. The list is traversed in reverse order
1860 * of mounting to avoid dependencies.
1862 * We want the umountall to be able to break out of its loop if a
1863 * failure occurs, after scanning all possible mounts, so the callback
1864 * returns 0 on error.
1866 * NOTE: Do not call mountlist_remove(mp) on error any more, this will
1867 * confuse mountlist_scan()'s unbusy check.
1869 static int vfs_umountall_callback(struct mount *mp, void *data);
1871 void
1872 vfs_unmountall(int halting)
1874 int count;
1876 do {
1877 count = mountlist_scan(vfs_umountall_callback, &halting,
1878 MNTSCAN_REVERSE|MNTSCAN_NOBUSY);
1879 } while (count);
1882 static
1884 vfs_umountall_callback(struct mount *mp, void *data)
1886 int error;
1887 int halting = *(int *)data;
1890 * NOTE: When halting, dounmount will disconnect but leave
1891 * certain mount points intact. e.g. devfs.
1893 error = dounmount(mp, MNT_FORCE, halting);
1894 if (error) {
1895 kprintf("unmount of filesystem mounted from %s failed (",
1896 mp->mnt_stat.f_mntfromname);
1897 if (error == EBUSY)
1898 kprintf("BUSY)\n");
1899 else
1900 kprintf("%d)\n", error);
1901 return 0;
1902 } else {
1903 return 1;
1908 * Checks the mount flags for parameter mp and put the names comma-separated
1909 * into a string buffer buf with a size limit specified by len.
1911 * It returns the number of bytes written into buf, and (*errorp) will be
1912 * set to 0, EINVAL (if passed length is 0), or ENOSPC (supplied buffer was
1913 * not large enough). The buffer will be 0-terminated if len was not 0.
1915 size_t
1916 vfs_flagstostr(int flags, const struct mountctl_opt *optp,
1917 char *buf, size_t len, int *errorp)
1919 static const struct mountctl_opt optnames[] = {
1920 { MNT_RDONLY, "read-only" },
1921 { MNT_SYNCHRONOUS, "synchronous" },
1922 { MNT_NOEXEC, "noexec" },
1923 { MNT_NOSUID, "nosuid" },
1924 { MNT_NODEV, "nodev" },
1925 { MNT_AUTOMOUNTED, "automounted" },
1926 { MNT_ASYNC, "asynchronous" },
1927 { MNT_SUIDDIR, "suiddir" },
1928 { MNT_SOFTDEP, "soft-updates" },
1929 { MNT_NOSYMFOLLOW, "nosymfollow" },
1930 { MNT_TRIM, "trim" },
1931 { MNT_NOATIME, "noatime" },
1932 { MNT_NOCLUSTERR, "noclusterr" },
1933 { MNT_NOCLUSTERW, "noclusterw" },
1934 { MNT_EXRDONLY, "NFS read-only" },
1935 { MNT_EXPORTED, "NFS exported" },
1936 /* Remaining NFS flags could come here */
1937 { MNT_LOCAL, "local" },
1938 { MNT_QUOTA, "with-quotas" },
1939 /* { MNT_ROOTFS, "rootfs" }, */
1940 /* { MNT_IGNORE, "ignore" }, */
1941 { 0, NULL}
1943 int bwritten;
1944 int bleft;
1945 int optlen;
1946 int actsize;
1948 *errorp = 0;
1949 bwritten = 0;
1950 bleft = len - 1; /* leave room for trailing \0 */
1953 * Checks the size of the string. If it contains
1954 * any data, then we will append the new flags to
1955 * it.
1957 actsize = strlen(buf);
1958 if (actsize > 0)
1959 buf += actsize;
1961 /* Default flags if no flags passed */
1962 if (optp == NULL)
1963 optp = optnames;
1965 if (bleft < 0) { /* degenerate case, 0-length buffer */
1966 *errorp = EINVAL;
1967 return(0);
1970 for (; flags && optp->o_opt; ++optp) {
1971 if ((flags & optp->o_opt) == 0)
1972 continue;
1973 optlen = strlen(optp->o_name);
1974 if (bwritten || actsize > 0) {
1975 if (bleft < 2) {
1976 *errorp = ENOSPC;
1977 break;
1979 buf[bwritten++] = ',';
1980 buf[bwritten++] = ' ';
1981 bleft -= 2;
1983 if (bleft < optlen) {
1984 *errorp = ENOSPC;
1985 break;
1987 bcopy(optp->o_name, buf + bwritten, optlen);
1988 bwritten += optlen;
1989 bleft -= optlen;
1990 flags &= ~optp->o_opt;
1994 * Space already reserved for trailing \0
1996 buf[bwritten] = 0;
1997 return (bwritten);
2001 * Build hash lists of net addresses and hang them off the mount point.
2002 * Called by ufs_mount() to set up the lists of export addresses.
2004 static int
2005 vfs_hang_addrlist(struct mount *mp, struct netexport *nep,
2006 const struct export_args *argp)
2008 struct netcred *np;
2009 struct radix_node_head *rnh;
2010 int i;
2011 struct radix_node *rn;
2012 struct sockaddr *saddr, *smask = NULL;
2013 int error;
2015 if (argp->ex_addrlen == 0) {
2016 if (mp->mnt_flag & MNT_DEFEXPORTED)
2017 return (EPERM);
2018 np = &nep->ne_defexported;
2019 np->netc_exflags = argp->ex_flags;
2020 np->netc_anon = argp->ex_anon;
2021 np->netc_anon.cr_ref = 1;
2022 mp->mnt_flag |= MNT_DEFEXPORTED;
2023 return (0);
2026 if (argp->ex_addrlen < 0 || argp->ex_addrlen > MLEN)
2027 return (EINVAL);
2028 if (argp->ex_masklen < 0 || argp->ex_masklen > MLEN)
2029 return (EINVAL);
2031 i = sizeof(struct netcred) + argp->ex_addrlen + argp->ex_masklen;
2032 np = (struct netcred *)kmalloc(i, M_NETCRED, M_WAITOK | M_ZERO);
2033 saddr = (struct sockaddr *) (np + 1);
2034 if ((error = copyin(argp->ex_addr, (caddr_t) saddr, argp->ex_addrlen)))
2035 goto out;
2036 if (saddr->sa_len > argp->ex_addrlen)
2037 saddr->sa_len = argp->ex_addrlen;
2038 if (argp->ex_masklen) {
2039 smask = (struct sockaddr *)((caddr_t)saddr + argp->ex_addrlen);
2040 error = copyin(argp->ex_mask, (caddr_t)smask, argp->ex_masklen);
2041 if (error)
2042 goto out;
2043 if (smask->sa_len > argp->ex_masklen)
2044 smask->sa_len = argp->ex_masklen;
2046 NE_LOCK(nep);
2047 if (nep->ne_maskhead == NULL) {
2048 if (!rn_inithead((void **)&nep->ne_maskhead, NULL, 0)) {
2049 error = ENOBUFS;
2050 goto out;
2053 if ((rnh = vfs_create_addrlist_af(saddr->sa_family, nep)) == NULL) {
2054 error = ENOBUFS;
2055 goto out;
2057 rn = (*rnh->rnh_addaddr)((char *)saddr, (char *)smask, rnh,
2058 np->netc_rnodes);
2059 NE_UNLOCK(nep);
2060 if (rn == NULL || np != (struct netcred *)rn) { /* already exists */
2061 error = EPERM;
2062 goto out;
2064 np->netc_exflags = argp->ex_flags;
2065 np->netc_anon = argp->ex_anon;
2066 np->netc_anon.cr_ref = 1;
2067 return (0);
2069 out:
2070 kfree(np, M_NETCRED);
2071 return (error);
2075 * Free netcred structures installed in the netexport
2077 static int
2078 vfs_free_netcred(struct radix_node *rn, void *w)
2080 struct radix_node_head *rnh = (struct radix_node_head *)w;
2082 (*rnh->rnh_deladdr) (rn->rn_key, rn->rn_mask, rnh);
2083 kfree(rn, M_NETCRED);
2085 return (0);
2089 * callback to free an element of the mask table installed in the
2090 * netexport. These may be created indirectly and are not netcred
2091 * structures.
2093 static int
2094 vfs_free_netcred_mask(struct radix_node *rn, void *w)
2096 struct radix_node_head *rnh = (struct radix_node_head *)w;
2098 (*rnh->rnh_deladdr) (rn->rn_key, rn->rn_mask, rnh);
2099 kfree(rn, M_RTABLE);
2101 return (0);
2104 static struct radix_node_head *
2105 vfs_create_addrlist_af(int af, struct netexport *nep)
2107 struct radix_node_head *rnh = NULL;
2108 #if defined(INET) || defined(INET6)
2109 struct radix_node_head *maskhead = nep->ne_maskhead;
2110 int off;
2111 #endif
2113 NE_ASSERT_LOCKED(nep);
2114 KKASSERT(maskhead != NULL);
2115 switch (af) {
2116 #ifdef INET
2117 case AF_INET:
2118 if ((rnh = nep->ne_inethead) == NULL) {
2119 off = offsetof(struct sockaddr_in, sin_addr) << 3;
2120 if (!rn_inithead((void **)&rnh, maskhead, off))
2121 return (NULL);
2122 nep->ne_inethead = rnh;
2124 break;
2125 #endif
2126 #ifdef INET6
2127 case AF_INET6:
2128 if ((rnh = nep->ne_inet6head) == NULL) {
2129 off = offsetof(struct sockaddr_in6, sin6_addr) << 3;
2130 if (!rn_inithead((void **)&rnh, maskhead, off))
2131 return (NULL);
2132 nep->ne_inet6head = rnh;
2134 break;
2135 #endif
2137 return (rnh);
2141 * helper function for freeing netcred elements
2143 static void
2144 vfs_free_addrlist_af(struct radix_node_head **prnh)
2146 struct radix_node_head *rnh = *prnh;
2148 (*rnh->rnh_walktree) (rnh, vfs_free_netcred, rnh);
2149 kfree(rnh, M_RTABLE);
2150 *prnh = NULL;
2154 * helper function for freeing mask elements
2156 static void
2157 vfs_free_addrlist_masks(struct radix_node_head **prnh)
2159 struct radix_node_head *rnh = *prnh;
2161 (*rnh->rnh_walktree) (rnh, vfs_free_netcred_mask, rnh);
2162 kfree(rnh, M_RTABLE);
2163 *prnh = NULL;
2167 * Free the net address hash lists that are hanging off the mount points.
2169 static void
2170 vfs_free_addrlist(struct netexport *nep)
2172 NE_LOCK(nep);
2173 if (nep->ne_inethead != NULL)
2174 vfs_free_addrlist_af(&nep->ne_inethead);
2175 if (nep->ne_inet6head != NULL)
2176 vfs_free_addrlist_af(&nep->ne_inet6head);
2177 if (nep->ne_maskhead)
2178 vfs_free_addrlist_masks(&nep->ne_maskhead);
2179 NE_UNLOCK(nep);
2183 vfs_export(struct mount *mp, struct netexport *nep,
2184 const struct export_args *argp)
2186 int error;
2188 if (argp->ex_flags & MNT_DELEXPORT) {
2189 if (mp->mnt_flag & MNT_EXPUBLIC) {
2190 vfs_setpublicfs(NULL, NULL, NULL);
2191 mp->mnt_flag &= ~MNT_EXPUBLIC;
2193 vfs_free_addrlist(nep);
2194 mp->mnt_flag &= ~(MNT_EXPORTED | MNT_DEFEXPORTED);
2196 if (argp->ex_flags & MNT_EXPORTED) {
2197 if (argp->ex_flags & MNT_EXPUBLIC) {
2198 if ((error = vfs_setpublicfs(mp, nep, argp)) != 0)
2199 return (error);
2200 mp->mnt_flag |= MNT_EXPUBLIC;
2202 if ((error = vfs_hang_addrlist(mp, nep, argp)))
2203 return (error);
2204 mp->mnt_flag |= MNT_EXPORTED;
2206 return (0);
2211 * Set the publicly exported filesystem (WebNFS). Currently, only
2212 * one public filesystem is possible in the spec (RFC 2054 and 2055)
2215 vfs_setpublicfs(struct mount *mp, struct netexport *nep,
2216 const struct export_args *argp)
2218 int error;
2219 struct vnode *rvp;
2220 char *cp;
2223 * mp == NULL -> invalidate the current info, the FS is
2224 * no longer exported. May be called from either vfs_export
2225 * or unmount, so check if it hasn't already been done.
2227 if (mp == NULL) {
2228 if (nfs_pub.np_valid) {
2229 nfs_pub.np_valid = 0;
2230 if (nfs_pub.np_index != NULL) {
2231 kfree(nfs_pub.np_index, M_TEMP);
2232 nfs_pub.np_index = NULL;
2235 return (0);
2239 * Only one allowed at a time.
2241 if (nfs_pub.np_valid != 0 && mp != nfs_pub.np_mount)
2242 return (EBUSY);
2245 * Get real filehandle for root of exported FS.
2247 bzero((caddr_t)&nfs_pub.np_handle, sizeof(nfs_pub.np_handle));
2248 nfs_pub.np_handle.fh_fsid = mp->mnt_stat.f_fsid;
2250 if ((error = VFS_ROOT(mp, &rvp)))
2251 return (error);
2253 if ((error = VFS_VPTOFH(rvp, &nfs_pub.np_handle.fh_fid)))
2254 return (error);
2256 vput(rvp);
2259 * If an indexfile was specified, pull it in.
2261 if (argp->ex_indexfile != NULL) {
2262 int namelen;
2264 error = vn_get_namelen(rvp, &namelen);
2265 if (error)
2266 return (error);
2267 nfs_pub.np_index = kmalloc(namelen, M_TEMP, M_WAITOK);
2268 error = copyinstr(argp->ex_indexfile, nfs_pub.np_index,
2269 namelen, NULL);
2270 if (!error) {
2272 * Check for illegal filenames.
2274 for (cp = nfs_pub.np_index; *cp; cp++) {
2275 if (*cp == '/') {
2276 error = EINVAL;
2277 break;
2281 if (error) {
2282 kfree(nfs_pub.np_index, M_TEMP);
2283 return (error);
2287 nfs_pub.np_mount = mp;
2288 nfs_pub.np_valid = 1;
2289 return (0);
2292 struct netcred *
2293 vfs_export_lookup(struct mount *mp, struct netexport *nep,
2294 struct sockaddr *nam)
2296 struct netcred *np;
2297 struct radix_node_head *rnh;
2298 struct sockaddr *saddr;
2300 np = NULL;
2301 if (mp->mnt_flag & MNT_EXPORTED) {
2303 * Lookup in the export list first.
2305 NE_LOCK(nep);
2306 if (nam != NULL) {
2307 saddr = nam;
2308 switch (saddr->sa_family) {
2309 #ifdef INET
2310 case AF_INET:
2311 rnh = nep->ne_inethead;
2312 break;
2313 #endif
2314 #ifdef INET6
2315 case AF_INET6:
2316 rnh = nep->ne_inet6head;
2317 break;
2318 #endif
2319 default:
2320 rnh = NULL;
2322 if (rnh != NULL) {
2323 np = (struct netcred *)
2324 (*rnh->rnh_matchaddr)((char *)saddr,
2325 rnh);
2326 if (np && np->netc_rnodes->rn_flags & RNF_ROOT)
2327 np = NULL;
2330 NE_UNLOCK(nep);
2332 * If no address match, use the default if it exists.
2334 if (np == NULL && mp->mnt_flag & MNT_DEFEXPORTED)
2335 np = &nep->ne_defexported;
2337 return (np);
2341 * perform msync on all vnodes under a mount point. The mount point must
2342 * be locked. This code is also responsible for lazy-freeing unreferenced
2343 * vnodes whos VM objects no longer contain pages.
2345 * NOTE: MNT_WAIT still skips vnodes in the VXLOCK state.
2347 * NOTE: XXX VOP_PUTPAGES and friends requires that the vnode be locked,
2348 * but vnode_pager_putpages() doesn't lock the vnode. We have to do it
2349 * way up in this high level function.
2351 static int vfs_msync_scan1(struct mount *mp, struct vnode *vp, void *data);
2352 static int vfs_msync_scan2(struct mount *mp, struct vnode *vp, void *data);
2354 void
2355 vfs_msync(struct mount *mp, int flags)
2357 int vmsc_flags;
2360 * tmpfs sets this flag to prevent msync(), sync, and the
2361 * filesystem periodic syncer from trying to flush VM pages
2362 * to swap. Only pure memory pressure flushes tmpfs VM pages
2363 * to swap.
2365 if (mp->mnt_kern_flag & MNTK_NOMSYNC)
2366 return;
2369 * Ok, scan the vnodes for work. If the filesystem is using the
2370 * syncer thread feature we can use vsyncscan() instead of
2371 * vmntvnodescan(), which is much faster.
2373 vmsc_flags = VMSC_GETVP;
2374 if (flags != MNT_WAIT)
2375 vmsc_flags |= VMSC_NOWAIT;
2377 if (mp->mnt_kern_flag & MNTK_THR_SYNC) {
2378 vsyncscan(mp, vmsc_flags, vfs_msync_scan2,
2379 (void *)(intptr_t)flags);
2380 } else {
2381 vmntvnodescan(mp, vmsc_flags,
2382 vfs_msync_scan1, vfs_msync_scan2,
2383 (void *)(intptr_t)flags);
2388 * scan1 is a fast pre-check. There could be hundreds of thousands of
2389 * vnodes, we cannot afford to do anything heavy weight until we have a
2390 * fairly good indication that there is work to do.
2392 static
2394 vfs_msync_scan1(struct mount *mp, struct vnode *vp, void *data)
2396 int flags = (int)(intptr_t)data;
2398 if ((vp->v_flag & VRECLAIMED) == 0) {
2399 if (vp->v_auxrefs == 0 && VREFCNT(vp) <= 0 &&
2400 vp->v_object) {
2401 return(0); /* call scan2 */
2403 if ((mp->mnt_flag & MNT_RDONLY) == 0 &&
2404 (vp->v_flag & VOBJDIRTY) &&
2405 (flags == MNT_WAIT || vn_islocked(vp) == 0)) {
2406 return(0); /* call scan2 */
2411 * do not call scan2, continue the loop
2413 return(-1);
2417 * This callback is handed a locked vnode.
2419 static
2421 vfs_msync_scan2(struct mount *mp, struct vnode *vp, void *data)
2423 vm_object_t obj;
2424 int flags = (int)(intptr_t)data;
2426 if (vp->v_flag & VRECLAIMED)
2427 return(0);
2429 if ((mp->mnt_flag & MNT_RDONLY) == 0 && (vp->v_flag & VOBJDIRTY)) {
2430 if ((obj = vp->v_object) != NULL) {
2431 vm_object_page_clean(obj, 0, 0,
2432 flags == MNT_WAIT ? OBJPC_SYNC : OBJPC_NOSYNC);
2435 return(0);
2439 * Wake up anyone interested in vp because it is being revoked.
2441 void
2442 vn_gone(struct vnode *vp)
2444 lwkt_gettoken(&vp->v_token);
2445 KNOTE(&vp->v_pollinfo.vpi_kqinfo.ki_note, NOTE_REVOKE);
2446 lwkt_reltoken(&vp->v_token);
2450 * extract the cdev_t from a VBLK or VCHR. The vnode must have been opened
2451 * (or v_rdev might be NULL).
2453 cdev_t
2454 vn_todev(struct vnode *vp)
2456 if (vp->v_type != VBLK && vp->v_type != VCHR)
2457 return (NULL);
2458 KKASSERT(vp->v_rdev != NULL);
2459 return (vp->v_rdev);
2463 * Check if vnode represents a disk device. The vnode does not need to be
2464 * opened.
2466 * MPALMOSTSAFE
2469 vn_isdisk(struct vnode *vp, int *errp)
2471 cdev_t dev;
2473 if (vp->v_type != VCHR) {
2474 if (errp != NULL)
2475 *errp = ENOTBLK;
2476 return (0);
2479 dev = vp->v_rdev;
2481 if (dev == NULL) {
2482 if (errp != NULL)
2483 *errp = ENXIO;
2484 return (0);
2486 if (dev_is_good(dev) == 0) {
2487 if (errp != NULL)
2488 *errp = ENXIO;
2489 return (0);
2491 if ((dev_dflags(dev) & D_DISK) == 0) {
2492 if (errp != NULL)
2493 *errp = ENOTBLK;
2494 return (0);
2496 if (errp != NULL)
2497 *errp = 0;
2498 return (1);
2502 vn_get_namelen(struct vnode *vp, int *namelen)
2504 int error;
2505 register_t retval[2];
2507 error = VOP_PATHCONF(vp, _PC_NAME_MAX, retval);
2508 if (error)
2509 return (error);
2510 *namelen = (int)retval[0];
2511 return (0);
2515 vop_write_dirent(int *error, struct uio *uio, ino_t d_ino, uint8_t d_type,
2516 uint16_t d_namlen, const char *d_name)
2518 struct dirent *dp;
2519 size_t len;
2521 len = _DIRENT_RECLEN(d_namlen);
2522 if (len > uio->uio_resid)
2523 return(1);
2525 dp = kmalloc(len, M_TEMP, M_WAITOK | M_ZERO);
2527 dp->d_ino = d_ino;
2528 dp->d_namlen = d_namlen;
2529 dp->d_type = d_type;
2530 bcopy(d_name, dp->d_name, d_namlen);
2532 *error = uiomove((caddr_t)dp, len, uio);
2534 kfree(dp, M_TEMP);
2536 return(0);
2539 void
2540 vn_mark_atime(struct vnode *vp, struct thread *td)
2542 struct proc *p = td->td_proc;
2543 struct ucred *cred = p ? p->p_ucred : proc0.p_ucred;
2545 if ((vp->v_mount->mnt_flag & (MNT_NOATIME | MNT_RDONLY)) == 0) {
2546 VOP_MARKATIME(vp, cred);
2551 * Calculate the number of entries in an inode-related chained hash table.
2552 * With today's memory sizes, maxvnodes can wind up being a very large
2553 * number. There is no reason to waste memory, so tolerate some stacking.
2556 vfs_inodehashsize(void)
2558 int hsize;
2560 hsize = 32;
2561 while (hsize < maxvnodes)
2562 hsize <<= 1;
2563 while (hsize > maxvnodes * 2)
2564 hsize >>= 1; /* nominal 2x stacking */
2566 if (maxvnodes > 1024 * 1024)
2567 hsize >>= 1; /* nominal 8x stacking */
2569 if (maxvnodes > 128 * 1024)
2570 hsize >>= 1; /* nominal 4x stacking */
2572 if (hsize < 16)
2573 hsize = 16;
2575 return hsize;