xref: /dragonfly/sys/kern/vfs_mount.c (revision 5b3debc4)
1 /*
2  * Copyright (c) 2004,2013 The DragonFly Project.  All rights reserved.
3  *
4  * This code is derived from software contributed to The DragonFly Project
5  * by Matthew Dillon <dillon@backplane.com>
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in
15  *    the documentation and/or other materials provided with the
16  *    distribution.
17  * 3. Neither the name of The DragonFly Project nor the names of its
18  *    contributors may be used to endorse or promote products derived
19  *    from this software without specific, prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
25  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
27  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
31  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  * Copyright (c) 1989, 1993
35  *	The Regents of the University of California.  All rights reserved.
36  * (c) UNIX System Laboratories, Inc.
37  * All or some portions of this file are derived from material licensed
38  * to the University of California by American Telephone and Telegraph
39  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
40  * the permission of UNIX System Laboratories, Inc.
41  *
42  * Redistribution and use in source and binary forms, with or without
43  * modification, are permitted provided that the following conditions
44  * are met:
45  * 1. Redistributions of source code must retain the above copyright
46  *    notice, this list of conditions and the following disclaimer.
47  * 2. Redistributions in binary form must reproduce the above copyright
48  *    notice, this list of conditions and the following disclaimer in the
49  *    documentation and/or other materials provided with the distribution.
50  * 3. Neither the name of the University nor the names of its contributors
51  *    may be used to endorse or promote products derived from this software
52  *    without specific prior written permission.
53  *
54  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
55  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
56  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
57  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
58  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
59  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
60  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
61  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
62  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
63  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
64  * SUCH DAMAGE.
65  */
66 
67 /*
68  * External virtual filesystem routines
69  */
70 
71 #include <sys/param.h>
72 #include <sys/systm.h>
73 #include <sys/kernel.h>
74 #include <sys/malloc.h>
75 #include <sys/mount.h>
76 #include <sys/proc.h>
77 #include <sys/vnode.h>
78 #include <sys/buf.h>
79 #include <sys/eventhandler.h>
80 #include <sys/kthread.h>
81 #include <sys/sysctl.h>
82 
83 #include <machine/limits.h>
84 
85 #include <sys/buf2.h>
86 #include <sys/thread2.h>
87 
88 #include <vm/vm.h>
89 #include <vm/vm_object.h>
90 
91 struct mountscan_info {
92 	TAILQ_ENTRY(mountscan_info) msi_entry;
93 	int msi_how;
94 	struct mount *msi_node;
95 };
96 
97 struct vmntvnodescan_info {
98 	TAILQ_ENTRY(vmntvnodescan_info) entry;
99 	struct vnode *vp;
100 };
101 
102 struct vnlru_info {
103 	int	pass;
104 };
105 
106 static int vnlru_nowhere = 0;
107 SYSCTL_INT(_debug, OID_AUTO, vnlru_nowhere, CTLFLAG_RD,
108 	    &vnlru_nowhere, 0,
109 	    "Number of times the vnlru process ran without success");
110 
111 
112 static struct lwkt_token mntid_token;
113 static struct mount dummymount;
114 
115 /* note: mountlist exported to pstat */
116 struct mntlist mountlist = TAILQ_HEAD_INITIALIZER(mountlist);
117 static TAILQ_HEAD(,mountscan_info) mountscan_list;
118 static struct lwkt_token mountlist_token;
119 
120 static TAILQ_HEAD(,bio_ops) bio_ops_list = TAILQ_HEAD_INITIALIZER(bio_ops_list);
121 
122 /*
123  * Called from vfsinit()
124  */
125 void
126 vfs_mount_init(void)
127 {
128 	lwkt_token_init(&mountlist_token, "mntlist");
129 	lwkt_token_init(&mntid_token, "mntid");
130 	TAILQ_INIT(&mountscan_list);
131 	mount_init(&dummymount);
132 	dummymount.mnt_flag |= MNT_RDONLY;
133 	dummymount.mnt_kern_flag |= MNTK_ALL_MPSAFE;
134 }
135 
136 /*
137  * Support function called to remove a vnode from the mountlist and
138  * deal with side effects for scans in progress.
139  *
140  * Target mnt_token is held on call.
141  */
142 static void
143 vremovevnodemnt(struct vnode *vp)
144 {
145         struct vmntvnodescan_info *info;
146 	struct mount *mp = vp->v_mount;
147 
148 	TAILQ_FOREACH(info, &mp->mnt_vnodescan_list, entry) {
149 		if (info->vp == vp)
150 			info->vp = TAILQ_NEXT(vp, v_nmntvnodes);
151 	}
152 	TAILQ_REMOVE(&vp->v_mount->mnt_nvnodelist, vp, v_nmntvnodes);
153 }
154 
155 /*
156  * Allocate a new vnode and associate it with a tag, mount point, and
157  * operations vector.
158  *
159  * A VX locked and refd vnode is returned.  The caller should setup the
160  * remaining fields and vx_put() or, if he wishes to leave a vref,
161  * vx_unlock() the vnode.
162  */
163 int
164 getnewvnode(enum vtagtype tag, struct mount *mp,
165 		struct vnode **vpp, int lktimeout, int lkflags)
166 {
167 	struct vnode *vp;
168 
169 	KKASSERT(mp != NULL);
170 
171 	vp = allocvnode(lktimeout, lkflags);
172 	vp->v_tag = tag;
173 	vp->v_data = NULL;
174 
175 	/*
176 	 * By default the vnode is assigned the mount point's normal
177 	 * operations vector.
178 	 */
179 	vp->v_ops = &mp->mnt_vn_use_ops;
180 	vp->v_pbuf_count = nswbuf_kva / NSWBUF_SPLIT;
181 
182 	/*
183 	 * Placing the vnode on the mount point's queue makes it visible.
184 	 * VNON prevents it from being messed with, however.
185 	 */
186 	insmntque(vp, mp);
187 
188 	/*
189 	 * A VX locked & refd vnode is returned.
190 	 */
191 	*vpp = vp;
192 	return (0);
193 }
194 
195 /*
196  * This function creates vnodes with special operations vectors.  The
197  * mount point is optional.
198  *
199  * This routine is being phased out but is still used by vfs_conf to
200  * create vnodes for devices prior to the root mount (with mp == NULL).
201  */
202 int
203 getspecialvnode(enum vtagtype tag, struct mount *mp,
204 		struct vop_ops **ops,
205 		struct vnode **vpp, int lktimeout, int lkflags)
206 {
207 	struct vnode *vp;
208 
209 	vp = allocvnode(lktimeout, lkflags);
210 	vp->v_tag = tag;
211 	vp->v_data = NULL;
212 	vp->v_ops = ops;
213 
214 	if (mp == NULL)
215 		mp = &dummymount;
216 
217 	/*
218 	 * Placing the vnode on the mount point's queue makes it visible.
219 	 * VNON prevents it from being messed with, however.
220 	 */
221 	insmntque(vp, mp);
222 
223 	/*
224 	 * A VX locked & refd vnode is returned.
225 	 */
226 	*vpp = vp;
227 	return (0);
228 }
229 
230 /*
231  * Interlock against an unmount, return 0 on success, non-zero on failure.
232  *
233  * The passed flag may be 0 or LK_NOWAIT and is only used if an unmount
234  * is in-progress.
235  *
236  * If no unmount is in-progress LK_NOWAIT is ignored.  No other flag bits
237  * are used.  A shared locked will be obtained and the filesystem will not
238  * be unmountable until the lock is released.
239  */
240 int
241 vfs_busy(struct mount *mp, int flags)
242 {
243 	int lkflags;
244 
245 	atomic_add_int(&mp->mnt_refs, 1);
246 	lwkt_gettoken(&mp->mnt_token);
247 	if (mp->mnt_kern_flag & MNTK_UNMOUNT) {
248 		if (flags & LK_NOWAIT) {
249 			lwkt_reltoken(&mp->mnt_token);
250 			atomic_add_int(&mp->mnt_refs, -1);
251 			return (ENOENT);
252 		}
253 		/* XXX not MP safe */
254 		mp->mnt_kern_flag |= MNTK_MWAIT;
255 
256 		/*
257 		 * Since all busy locks are shared except the exclusive
258 		 * lock granted when unmounting, the only place that a
259 		 * wakeup needs to be done is at the release of the
260 		 * exclusive lock at the end of dounmount.
261 		 *
262 		 * WARNING! mp can potentially go away once we release
263 		 *	    our ref.
264 		 */
265 		tsleep((caddr_t)mp, 0, "vfs_busy", 0);
266 		lwkt_reltoken(&mp->mnt_token);
267 		atomic_add_int(&mp->mnt_refs, -1);
268 		return (ENOENT);
269 	}
270 	lkflags = LK_SHARED;
271 	if (lockmgr(&mp->mnt_lock, lkflags))
272 		panic("vfs_busy: unexpected lock failure");
273 	lwkt_reltoken(&mp->mnt_token);
274 	return (0);
275 }
276 
277 /*
278  * Free a busy filesystem.
279  *
280  * Once refs is decremented the mount point can potentially get ripped
281  * out from under us, but we want to clean up our refs before unlocking
282  * so do a hold/drop around the whole mess.
283  *
284  * This is not in the critical path (I hope).
285  */
286 void
287 vfs_unbusy(struct mount *mp)
288 {
289 	mount_hold(mp);
290 	atomic_add_int(&mp->mnt_refs, -1);
291 	lockmgr(&mp->mnt_lock, LK_RELEASE);
292 	mount_drop(mp);
293 }
294 
295 /*
296  * Lookup a filesystem type, and if found allocate and initialize
297  * a mount structure for it.
298  *
299  * Devname is usually updated by mount(8) after booting.
300  */
301 int
302 vfs_rootmountalloc(char *fstypename, char *devname, struct mount **mpp)
303 {
304 	struct vfsconf *vfsp;
305 	struct mount *mp;
306 
307 	if (fstypename == NULL)
308 		return (ENODEV);
309 
310 	vfsp = vfsconf_find_by_name(fstypename);
311 	if (vfsp == NULL)
312 		return (ENODEV);
313 	mp = kmalloc(sizeof(struct mount), M_MOUNT, M_WAITOK | M_ZERO);
314 	mount_init(mp);
315 	lockinit(&mp->mnt_lock, "vfslock", VLKTIMEOUT, 0);
316 
317 	vfs_busy(mp, 0);
318 	mp->mnt_vfc = vfsp;
319 	mp->mnt_op = vfsp->vfc_vfsops;
320 	mp->mnt_pbuf_count = nswbuf_kva / NSWBUF_SPLIT;
321 	vfsp->vfc_refcount++;
322 	mp->mnt_stat.f_type = vfsp->vfc_typenum;
323 	mp->mnt_flag |= MNT_RDONLY;
324 	mp->mnt_flag |= vfsp->vfc_flags & MNT_VISFLAGMASK;
325 	strncpy(mp->mnt_stat.f_fstypename, vfsp->vfc_name, MFSNAMELEN);
326 	copystr(devname, mp->mnt_stat.f_mntfromname, MNAMELEN - 1, 0);
327 
328 	/*
329 	 * Pre-set MPSAFE flags for VFS_MOUNT() call.
330 	 */
331 	if (vfsp->vfc_flags & VFCF_MPSAFE)
332 		mp->mnt_kern_flag |= MNTK_ALL_MPSAFE;
333 
334 	*mpp = mp;
335 
336 	return (0);
337 }
338 
339 /*
340  * Basic mount structure initialization
341  */
342 void
343 mount_init(struct mount *mp)
344 {
345 	lockinit(&mp->mnt_lock, "vfslock", hz*5, 0);
346 	lwkt_token_init(&mp->mnt_token, "permnt");
347 
348 	TAILQ_INIT(&mp->mnt_vnodescan_list);
349 	TAILQ_INIT(&mp->mnt_nvnodelist);
350 	TAILQ_INIT(&mp->mnt_reservedvnlist);
351 	TAILQ_INIT(&mp->mnt_jlist);
352 	mp->mnt_nvnodelistsize = 0;
353 	mp->mnt_flag = 0;
354 	mp->mnt_hold = 1;		/* hold for umount last drop */
355 	mp->mnt_iosize_max = MAXPHYS;
356 	vn_syncer_thr_create(mp);
357 }
358 
359 void
360 mount_hold(struct mount *mp)
361 {
362 	atomic_add_int(&mp->mnt_hold, 1);
363 }
364 
365 void
366 mount_drop(struct mount *mp)
367 {
368 	if (atomic_fetchadd_int(&mp->mnt_hold, -1) == 1) {
369 		KKASSERT(mp->mnt_refs == 0);
370 		kfree(mp, M_MOUNT);
371 	}
372 }
373 
374 /*
375  * Lookup a mount point by filesystem identifier.
376  *
377  * If not NULL, the returned mp is held and the caller is expected to drop
378  * it via mount_drop().
379  */
380 struct mount *
381 vfs_getvfs(fsid_t *fsid)
382 {
383 	struct mount *mp;
384 
385 	lwkt_gettoken_shared(&mountlist_token);
386 	TAILQ_FOREACH(mp, &mountlist, mnt_list) {
387 		if (mp->mnt_stat.f_fsid.val[0] == fsid->val[0] &&
388 		    mp->mnt_stat.f_fsid.val[1] == fsid->val[1]) {
389 			mount_hold(mp);
390 			break;
391 		}
392 	}
393 	lwkt_reltoken(&mountlist_token);
394 	return (mp);
395 }
396 
397 /*
398  * Get a new unique fsid.  Try to make its val[0] unique, since this value
399  * will be used to create fake device numbers for stat().  Also try (but
400  * not so hard) make its val[0] unique mod 2^16, since some emulators only
401  * support 16-bit device numbers.  We end up with unique val[0]'s for the
402  * first 2^16 calls and unique val[0]'s mod 2^16 for the first 2^8 calls.
403  *
404  * Keep in mind that several mounts may be running in parallel.  Starting
405  * the search one past where the previous search terminated is both a
406  * micro-optimization and a defense against returning the same fsid to
407  * different mounts.
408  */
409 void
410 vfs_getnewfsid(struct mount *mp)
411 {
412 	static u_int16_t mntid_base;
413 	struct mount *mptmp;
414 	fsid_t tfsid;
415 	int mtype;
416 
417 	lwkt_gettoken(&mntid_token);
418 	mtype = mp->mnt_vfc->vfc_typenum;
419 	tfsid.val[1] = mtype;
420 	mtype = (mtype & 0xFF) << 24;
421 	for (;;) {
422 		tfsid.val[0] = makeudev(255,
423 		    mtype | ((mntid_base & 0xFF00) << 8) | (mntid_base & 0xFF));
424 		mntid_base++;
425 		mptmp = vfs_getvfs(&tfsid);
426 		if (mptmp == NULL)
427 			break;
428 		mount_drop(mptmp);
429 	}
430 	mp->mnt_stat.f_fsid.val[0] = tfsid.val[0];
431 	mp->mnt_stat.f_fsid.val[1] = tfsid.val[1];
432 	lwkt_reltoken(&mntid_token);
433 }
434 
435 /*
436  * Set the FSID for a new mount point to the template.  Adjust
437  * the FSID to avoid collisions.
438  */
439 int
440 vfs_setfsid(struct mount *mp, fsid_t *template)
441 {
442 	struct mount *mptmp;
443 	int didmunge = 0;
444 
445 	bzero(&mp->mnt_stat.f_fsid, sizeof(mp->mnt_stat.f_fsid));
446 
447 	lwkt_gettoken(&mntid_token);
448 	for (;;) {
449 		mptmp = vfs_getvfs(template);
450 		if (mptmp == NULL)
451 			break;
452 		mount_drop(mptmp);
453 		didmunge = 1;
454 		++template->val[1];
455 	}
456 	mp->mnt_stat.f_fsid = *template;
457 	lwkt_reltoken(&mntid_token);
458 
459 	return(didmunge);
460 }
461 
462 /*
463  * This routine is called when we have too many vnodes.  It attempts
464  * to free <count> vnodes and will potentially free vnodes that still
465  * have VM backing store (VM backing store is typically the cause
466  * of a vnode blowout so we want to do this).  Therefore, this operation
467  * is not considered cheap.
468  *
469  * A number of conditions may prevent a vnode from being reclaimed.
470  * the buffer cache may have references on the vnode, a directory
471  * vnode may still have references due to the namei cache representing
472  * underlying files, or the vnode may be in active use.   It is not
473  * desireable to reuse such vnodes.  These conditions may cause the
474  * number of vnodes to reach some minimum value regardless of what
475  * you set kern.maxvnodes to.  Do not set kern.maxvnodes too low.
476  */
477 
478 /*
479  * Attempt to recycle vnodes in a context that is always safe to block.
480  * Calling vlrurecycle() from the bowels of file system code has some
481  * interesting deadlock problems.
482  */
483 static struct thread *vnlruthread;
484 
485 static void
486 vnlru_proc(void)
487 {
488 	struct thread *td = curthread;
489 
490 	EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc, td,
491 			      SHUTDOWN_PRI_FIRST);
492 
493 	for (;;) {
494 		int ncached;
495 
496 		kproc_suspend_loop();
497 
498 		/*
499 		 * Try to free some vnodes if we have too many.  Trigger based
500 		 * on potentially freeable vnodes but calculate the count
501 		 * based on total vnodes.
502 		 *
503 		 * (long) -> deal with 64 bit machines, intermediate overflow
504 		 */
505 		ncached = countcachedvnodes(1);
506 		if (numvnodes >= maxvnodes * 9 / 10 &&
507 		    ncached + inactivevnodes >= maxvnodes * 5 / 10) {
508 			int count = numvnodes - maxvnodes * 9 / 10;
509 
510 			if (count > (ncached + inactivevnodes) / 100)
511 				count = (ncached + inactivevnodes) / 100;
512 			if (count < 5)
513 				count = 5;
514 			freesomevnodes(count);
515 		}
516 
517 		/*
518 		 * Do non-critical-path (more robust) cache cleaning,
519 		 * even if vnode counts are nominal, to try to avoid
520 		 * having to do it in the critical path.
521 		 */
522 		cache_hysteresis(0);
523 
524 		/*
525 		 * Nothing to do if most of our vnodes are already on
526 		 * the free list.
527 		 */
528 		ncached = countcachedvnodes(1);
529 		if (numvnodes <= maxvnodes * 9 / 10 ||
530 		    ncached + inactivevnodes <= maxvnodes * 5 / 10) {
531 			tsleep(vnlruthread, 0, "vlruwt", hz);
532 			continue;
533 		}
534 	}
535 }
536 
537 /*
538  * MOUNTLIST FUNCTIONS
539  */
540 
541 /*
542  * mountlist_insert (MP SAFE)
543  *
544  * Add a new mount point to the mount list.
545  */
546 void
547 mountlist_insert(struct mount *mp, int how)
548 {
549 	lwkt_gettoken(&mountlist_token);
550 	if (how == MNTINS_FIRST)
551 		TAILQ_INSERT_HEAD(&mountlist, mp, mnt_list);
552 	else
553 		TAILQ_INSERT_TAIL(&mountlist, mp, mnt_list);
554 	lwkt_reltoken(&mountlist_token);
555 }
556 
557 /*
558  * mountlist_interlock (MP SAFE)
559  *
560  * Execute the specified interlock function with the mountlist token
561  * held.  The function will be called in a serialized fashion verses
562  * other functions called through this mechanism.
563  *
564  * The function is expected to be very short-lived.
565  */
566 int
567 mountlist_interlock(int (*callback)(struct mount *), struct mount *mp)
568 {
569 	int error;
570 
571 	lwkt_gettoken(&mountlist_token);
572 	error = callback(mp);
573 	lwkt_reltoken(&mountlist_token);
574 	return (error);
575 }
576 
577 /*
578  * mountlist_boot_getfirst (DURING BOOT ONLY)
579  *
580  * This function returns the first mount on the mountlist, which is
581  * expected to be the root mount.  Since no interlocks are obtained
582  * this function is only safe to use during booting.
583  */
584 
585 struct mount *
586 mountlist_boot_getfirst(void)
587 {
588 	return(TAILQ_FIRST(&mountlist));
589 }
590 
591 /*
592  * mountlist_remove (MP SAFE)
593  *
594  * Remove a node from the mountlist.  If this node is the next scan node
595  * for any active mountlist scans, the active mountlist scan will be
596  * adjusted to skip the node, thus allowing removals during mountlist
597  * scans.
598  */
599 void
600 mountlist_remove(struct mount *mp)
601 {
602 	struct mountscan_info *msi;
603 
604 	lwkt_gettoken(&mountlist_token);
605 	TAILQ_FOREACH(msi, &mountscan_list, msi_entry) {
606 		if (msi->msi_node == mp) {
607 			if (msi->msi_how & MNTSCAN_FORWARD)
608 				msi->msi_node = TAILQ_NEXT(mp, mnt_list);
609 			else
610 				msi->msi_node = TAILQ_PREV(mp, mntlist,
611 							   mnt_list);
612 		}
613 	}
614 	TAILQ_REMOVE(&mountlist, mp, mnt_list);
615 	lwkt_reltoken(&mountlist_token);
616 }
617 
618 /*
619  * mountlist_exists (MP SAFE)
620  *
621  * Checks if a node exists in the mountlist.
622  * This function is mainly used by VFS quota code to check if a
623  * cached nullfs struct mount pointer is still valid at use time
624  *
625  * FIXME: there is no warranty the mp passed to that function
626  * will be the same one used by VFS_ACCOUNT() later
627  */
628 int
629 mountlist_exists(struct mount *mp)
630 {
631 	int node_exists = 0;
632 	struct mount* lmp;
633 
634 	lwkt_gettoken_shared(&mountlist_token);
635 	TAILQ_FOREACH(lmp, &mountlist, mnt_list) {
636 		if (lmp == mp) {
637 			node_exists = 1;
638 			break;
639 		}
640 	}
641 	lwkt_reltoken(&mountlist_token);
642 
643 	return(node_exists);
644 }
645 
646 /*
647  * mountlist_scan
648  *
649  * Safely scan the mount points on the mount list.  Each mountpoint
650  * is held across the callback.  The callback is responsible for
651  * acquiring any further tokens or locks.
652  *
653  * Unless otherwise specified each mount point will be busied prior to the
654  * callback and unbusied afterwords.  The callback may safely remove any
655  * mount point without interfering with the scan.  If the current callback
656  * mount is removed the scanner will not attempt to unbusy it.
657  *
658  * If a mount node cannot be busied it is silently skipped.
659  *
660  * The callback return value is aggregated and a total is returned.  A return
661  * value of < 0 is not aggregated and will terminate the scan.
662  *
663  * MNTSCAN_FORWARD	- the mountlist is scanned in the forward direction
664  * MNTSCAN_REVERSE	- the mountlist is scanned in reverse
665  * MNTSCAN_NOBUSY	- the scanner will make the callback without busying
666  *			  the mount node.
667  *
668  * NOTE: mountlist_token is not held across the callback.
669  */
670 int
671 mountlist_scan(int (*callback)(struct mount *, void *), void *data, int how)
672 {
673 	struct mountscan_info info;
674 	struct mount *mp;
675 	int count;
676 	int res;
677 
678 	lwkt_gettoken(&mountlist_token);
679 	info.msi_how = how;
680 	info.msi_node = NULL;	/* paranoia */
681 	TAILQ_INSERT_TAIL(&mountscan_list, &info, msi_entry);
682 	lwkt_reltoken(&mountlist_token);
683 
684 	res = 0;
685 	lwkt_gettoken_shared(&mountlist_token);
686 
687 	if (how & MNTSCAN_FORWARD) {
688 		info.msi_node = TAILQ_FIRST(&mountlist);
689 		while ((mp = info.msi_node) != NULL) {
690 			mount_hold(mp);
691 			if (how & MNTSCAN_NOBUSY) {
692 				lwkt_reltoken(&mountlist_token);
693 				count = callback(mp, data);
694 				lwkt_gettoken_shared(&mountlist_token);
695 			} else if (vfs_busy(mp, LK_NOWAIT) == 0) {
696 				lwkt_reltoken(&mountlist_token);
697 				count = callback(mp, data);
698 				lwkt_gettoken_shared(&mountlist_token);
699 				if (mp == info.msi_node)
700 					vfs_unbusy(mp);
701 			} else {
702 				count = 0;
703 			}
704 			mount_drop(mp);
705 			if (count < 0)
706 				break;
707 			res += count;
708 			if (mp == info.msi_node)
709 				info.msi_node = TAILQ_NEXT(mp, mnt_list);
710 		}
711 	} else if (how & MNTSCAN_REVERSE) {
712 		info.msi_node = TAILQ_LAST(&mountlist, mntlist);
713 		while ((mp = info.msi_node) != NULL) {
714 			mount_hold(mp);
715 			if (how & MNTSCAN_NOBUSY) {
716 				lwkt_reltoken(&mountlist_token);
717 				count = callback(mp, data);
718 				lwkt_gettoken_shared(&mountlist_token);
719 			} else if (vfs_busy(mp, LK_NOWAIT) == 0) {
720 				lwkt_reltoken(&mountlist_token);
721 				count = callback(mp, data);
722 				lwkt_gettoken_shared(&mountlist_token);
723 				if (mp == info.msi_node)
724 					vfs_unbusy(mp);
725 			} else {
726 				count = 0;
727 			}
728 			mount_drop(mp);
729 			if (count < 0)
730 				break;
731 			res += count;
732 			if (mp == info.msi_node)
733 				info.msi_node = TAILQ_PREV(mp, mntlist,
734 							   mnt_list);
735 		}
736 	}
737 	lwkt_reltoken(&mountlist_token);
738 
739 	lwkt_gettoken(&mountlist_token);
740 	TAILQ_REMOVE(&mountscan_list, &info, msi_entry);
741 	lwkt_reltoken(&mountlist_token);
742 
743 	return(res);
744 }
745 
746 /*
747  * MOUNT RELATED VNODE FUNCTIONS
748  */
749 
750 static struct kproc_desc vnlru_kp = {
751 	"vnlru",
752 	vnlru_proc,
753 	&vnlruthread
754 };
755 SYSINIT(vnlru, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start, &vnlru_kp);
756 
757 /*
758  * Move a vnode from one mount queue to another.
759  */
760 void
761 insmntque(struct vnode *vp, struct mount *mp)
762 {
763 	struct mount *omp;
764 
765 	/*
766 	 * Delete from old mount point vnode list, if on one.
767 	 */
768 	if ((omp = vp->v_mount) != NULL) {
769 		lwkt_gettoken(&omp->mnt_token);
770 		KKASSERT(omp == vp->v_mount);
771 		KASSERT(omp->mnt_nvnodelistsize > 0,
772 			("bad mount point vnode list size"));
773 		vremovevnodemnt(vp);
774 		omp->mnt_nvnodelistsize--;
775 		lwkt_reltoken(&omp->mnt_token);
776 	}
777 
778 	/*
779 	 * Insert into list of vnodes for the new mount point, if available.
780 	 * The 'end' of the LRU list is the vnode prior to mp->mnt_syncer.
781 	 */
782 	if (mp == NULL) {
783 		vp->v_mount = NULL;
784 		return;
785 	}
786 	lwkt_gettoken(&mp->mnt_token);
787 	vp->v_mount = mp;
788 	if (mp->mnt_syncer) {
789 		TAILQ_INSERT_BEFORE(mp->mnt_syncer, vp, v_nmntvnodes);
790 	} else {
791 		TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
792 	}
793 	mp->mnt_nvnodelistsize++;
794 	lwkt_reltoken(&mp->mnt_token);
795 }
796 
797 
798 /*
799  * Scan the vnodes under a mount point and issue appropriate callbacks.
800  *
801  * The fastfunc() callback is called with just the mountlist token held
802  * (no vnode lock).  It may not block and the vnode may be undergoing
803  * modifications while the caller is processing it.  The vnode will
804  * not be entirely destroyed, however, due to the fact that the mountlist
805  * token is held.  A return value < 0 skips to the next vnode without calling
806  * the slowfunc(), a return value > 0 terminates the loop.
807  *
808  * WARNING! The fastfunc() should not indirect through vp->v_object, the vp
809  *	    data structure is unstable when called from fastfunc().
810  *
811  * The slowfunc() callback is called after the vnode has been successfully
812  * locked based on passed flags.  The vnode is skipped if it gets rearranged
813  * or destroyed while blocking on the lock.  A non-zero return value from
814  * the slow function terminates the loop.  The slow function is allowed to
815  * arbitrarily block.  The scanning code guarentees consistency of operation
816  * even if the slow function deletes or moves the node, or blocks and some
817  * other thread deletes or moves the node.
818  */
819 int
820 vmntvnodescan(
821     struct mount *mp,
822     int flags,
823     int (*fastfunc)(struct mount *mp, struct vnode *vp, void *data),
824     int (*slowfunc)(struct mount *mp, struct vnode *vp, void *data),
825     void *data
826 ) {
827 	struct vmntvnodescan_info info;
828 	struct vnode *vp;
829 	int r = 0;
830 	int maxcount = mp->mnt_nvnodelistsize * 2;
831 	int stopcount = 0;
832 	int count = 0;
833 
834 	lwkt_gettoken(&mp->mnt_token);
835 
836 	/*
837 	 * If asked to do one pass stop after iterating available vnodes.
838 	 * Under heavy loads new vnodes can be added while we are scanning,
839 	 * so this isn't perfect.  Create a slop factor of 2x.
840 	 */
841 	if (flags & VMSC_ONEPASS)
842 		stopcount = mp->mnt_nvnodelistsize;
843 
844 	info.vp = TAILQ_FIRST(&mp->mnt_nvnodelist);
845 	TAILQ_INSERT_TAIL(&mp->mnt_vnodescan_list, &info, entry);
846 
847 	while ((vp = info.vp) != NULL) {
848 		if (--maxcount == 0) {
849 			kprintf("Warning: excessive fssync iteration\n");
850 			maxcount = mp->mnt_nvnodelistsize * 2;
851 		}
852 
853 		/*
854 		 * Skip if visible but not ready, or special (e.g.
855 		 * mp->mnt_syncer)
856 		 */
857 		if (vp->v_type == VNON)
858 			goto next;
859 		KKASSERT(vp->v_mount == mp);
860 
861 		/*
862 		 * Quick test.  A negative return continues the loop without
863 		 * calling the slow test.  0 continues onto the slow test.
864 		 * A positive number aborts the loop.
865 		 */
866 		if (fastfunc) {
867 			if ((r = fastfunc(mp, vp, data)) < 0) {
868 				r = 0;
869 				goto next;
870 			}
871 			if (r)
872 				break;
873 		}
874 
875 		/*
876 		 * Get a vxlock on the vnode, retry if it has moved or isn't
877 		 * in the mountlist where we expect it.
878 		 */
879 		if (slowfunc) {
880 			int error;
881 
882 			switch(flags & (VMSC_GETVP|VMSC_GETVX|VMSC_NOWAIT)) {
883 			case VMSC_GETVP:
884 				error = vget(vp, LK_EXCLUSIVE);
885 				break;
886 			case VMSC_GETVP|VMSC_NOWAIT:
887 				error = vget(vp, LK_EXCLUSIVE|LK_NOWAIT);
888 				break;
889 			case VMSC_GETVX:
890 				vx_get(vp);
891 				error = 0;
892 				break;
893 			default:
894 				error = 0;
895 				break;
896 			}
897 			if (error)
898 				goto next;
899 			/*
900 			 * Do not call the slow function if the vnode is
901 			 * invalid or if it was ripped out from under us
902 			 * while we (potentially) blocked.
903 			 */
904 			if (info.vp == vp && vp->v_type != VNON)
905 				r = slowfunc(mp, vp, data);
906 
907 			/*
908 			 * Cleanup
909 			 */
910 			switch(flags & (VMSC_GETVP|VMSC_GETVX|VMSC_NOWAIT)) {
911 			case VMSC_GETVP:
912 			case VMSC_GETVP|VMSC_NOWAIT:
913 				vput(vp);
914 				break;
915 			case VMSC_GETVX:
916 				vx_put(vp);
917 				break;
918 			default:
919 				break;
920 			}
921 			if (r != 0)
922 				break;
923 		}
924 
925 next:
926 		/*
927 		 * Yield after some processing.  Depending on the number
928 		 * of vnodes, we might wind up running for a long time.
929 		 * Because threads are not preemptable, time critical
930 		 * userland processes might starve.  Give them a chance
931 		 * now and then.
932 		 */
933 		if (++count == 10000) {
934 			/*
935 			 * We really want to yield a bit, so we simply
936 			 * sleep a tick
937 			 */
938 			tsleep(mp, 0, "vnodescn", 1);
939 			count = 0;
940 		}
941 
942 		/*
943 		 * If doing one pass this decrements to zero.  If it starts
944 		 * at zero it is effectively unlimited for the purposes of
945 		 * this loop.
946 		 */
947 		if (--stopcount == 0)
948 			break;
949 
950 		/*
951 		 * Iterate.  If the vnode was ripped out from under us
952 		 * info.vp will already point to the next vnode, otherwise
953 		 * we have to obtain the next valid vnode ourselves.
954 		 */
955 		if (info.vp == vp)
956 			info.vp = TAILQ_NEXT(vp, v_nmntvnodes);
957 	}
958 
959 	TAILQ_REMOVE(&mp->mnt_vnodescan_list, &info, entry);
960 	lwkt_reltoken(&mp->mnt_token);
961 	return(r);
962 }
963 
964 /*
965  * Remove any vnodes in the vnode table belonging to mount point mp.
966  *
967  * If FORCECLOSE is not specified, there should not be any active ones,
968  * return error if any are found (nb: this is a user error, not a
969  * system error). If FORCECLOSE is specified, detach any active vnodes
970  * that are found.
971  *
972  * If WRITECLOSE is set, only flush out regular file vnodes open for
973  * writing.
974  *
975  * SKIPSYSTEM causes any vnodes marked VSYSTEM to be skipped.
976  *
977  * `rootrefs' specifies the base reference count for the root vnode
978  * of this filesystem. The root vnode is considered busy if its
979  * v_refcnt exceeds this value. On a successful return, vflush()
980  * will call vrele() on the root vnode exactly rootrefs times.
981  * If the SKIPSYSTEM or WRITECLOSE flags are specified, rootrefs must
982  * be zero.
983  */
984 #ifdef DIAGNOSTIC
985 static int busyprt = 0;		/* print out busy vnodes */
986 SYSCTL_INT(_debug, OID_AUTO, busyprt, CTLFLAG_RW, &busyprt, 0, "");
987 #endif
988 
989 static int vflush_scan(struct mount *mp, struct vnode *vp, void *data);
990 
991 struct vflush_info {
992 	int flags;
993 	int busy;
994 	thread_t td;
995 };
996 
997 int
998 vflush(struct mount *mp, int rootrefs, int flags)
999 {
1000 	struct thread *td = curthread;	/* XXX */
1001 	struct vnode *rootvp = NULL;
1002 	int error;
1003 	struct vflush_info vflush_info;
1004 
1005 	if (rootrefs > 0) {
1006 		KASSERT((flags & (SKIPSYSTEM | WRITECLOSE)) == 0,
1007 		    ("vflush: bad args"));
1008 		/*
1009 		 * Get the filesystem root vnode. We can vput() it
1010 		 * immediately, since with rootrefs > 0, it won't go away.
1011 		 */
1012 		if ((error = VFS_ROOT(mp, &rootvp)) != 0) {
1013 			if ((flags & FORCECLOSE) == 0)
1014 				return (error);
1015 			rootrefs = 0;
1016 			/* continue anyway */
1017 		}
1018 		if (rootrefs)
1019 			vput(rootvp);
1020 	}
1021 
1022 	vflush_info.busy = 0;
1023 	vflush_info.flags = flags;
1024 	vflush_info.td = td;
1025 	vmntvnodescan(mp, VMSC_GETVX, NULL, vflush_scan, &vflush_info);
1026 
1027 	if (rootrefs > 0 && (flags & FORCECLOSE) == 0) {
1028 		/*
1029 		 * If just the root vnode is busy, and if its refcount
1030 		 * is equal to `rootrefs', then go ahead and kill it.
1031 		 */
1032 		KASSERT(vflush_info.busy > 0, ("vflush: not busy"));
1033 		KASSERT(VREFCNT(rootvp) >= rootrefs, ("vflush: rootrefs"));
1034 		if (vflush_info.busy == 1 && VREFCNT(rootvp) == rootrefs) {
1035 			vx_lock(rootvp);
1036 			vgone_vxlocked(rootvp);
1037 			vx_unlock(rootvp);
1038 			vflush_info.busy = 0;
1039 		}
1040 	}
1041 	if (vflush_info.busy)
1042 		return (EBUSY);
1043 	for (; rootrefs > 0; rootrefs--)
1044 		vrele(rootvp);
1045 	return (0);
1046 }
1047 
1048 /*
1049  * The scan callback is made with an VX locked vnode.
1050  */
1051 static int
1052 vflush_scan(struct mount *mp, struct vnode *vp, void *data)
1053 {
1054 	struct vflush_info *info = data;
1055 	struct vattr vattr;
1056 	int flags = info->flags;
1057 
1058 	/*
1059 	 * Generally speaking try to deactivate on 0 refs (catch-all)
1060 	 */
1061 	atomic_set_int(&vp->v_refcnt, VREF_FINALIZE);
1062 
1063 	/*
1064 	 * Skip over a vnodes marked VSYSTEM.
1065 	 */
1066 	if ((flags & SKIPSYSTEM) && (vp->v_flag & VSYSTEM)) {
1067 		return(0);
1068 	}
1069 
1070 	/*
1071 	 * Do not force-close VCHR or VBLK vnodes
1072 	 */
1073 	if (vp->v_type == VCHR || vp->v_type == VBLK)
1074 		flags &= ~(WRITECLOSE|FORCECLOSE);
1075 
1076 	/*
1077 	 * If WRITECLOSE is set, flush out unlinked but still open
1078 	 * files (even if open only for reading) and regular file
1079 	 * vnodes open for writing.
1080 	 */
1081 	if ((flags & WRITECLOSE) &&
1082 	    (vp->v_type == VNON ||
1083 	    (VOP_GETATTR(vp, &vattr) == 0 &&
1084 	    vattr.va_nlink > 0)) &&
1085 	    (vp->v_writecount == 0 || vp->v_type != VREG)) {
1086 		return(0);
1087 	}
1088 
1089 	/*
1090 	 * If we are the only holder (refcnt of 1) or the vnode is in
1091 	 * termination (refcnt < 0), we can vgone the vnode.
1092 	 */
1093 	if (VREFCNT(vp) <= 1) {
1094 		vgone_vxlocked(vp);
1095 		return(0);
1096 	}
1097 
1098 	/*
1099 	 * If FORCECLOSE is set, forcibly destroy the vnode and then move
1100 	 * it to a dummymount structure so vop_*() functions don't deref
1101 	 * a NULL pointer.
1102 	 */
1103 	if (flags & FORCECLOSE) {
1104 		vhold(vp);
1105 		vgone_vxlocked(vp);
1106 		if (vp->v_mount == NULL)
1107 			insmntque(vp, &dummymount);
1108 		vdrop(vp);
1109 		return(0);
1110 	}
1111 	if (vp->v_type == VCHR || vp->v_type == VBLK)
1112 		kprintf("vflush: Warning, cannot destroy busy device vnode\n");
1113 #ifdef DIAGNOSTIC
1114 	if (busyprt)
1115 		vprint("vflush: busy vnode", vp);
1116 #endif
1117 	++info->busy;
1118 	return(0);
1119 }
1120 
1121 void
1122 add_bio_ops(struct bio_ops *ops)
1123 {
1124 	TAILQ_INSERT_TAIL(&bio_ops_list, ops, entry);
1125 }
1126 
1127 void
1128 rem_bio_ops(struct bio_ops *ops)
1129 {
1130 	TAILQ_REMOVE(&bio_ops_list, ops, entry);
1131 }
1132 
1133 /*
1134  * This calls the bio_ops io_sync function either for a mount point
1135  * or generally.
1136  *
1137  * WARNING: softdeps is weirdly coded and just isn't happy unless
1138  * io_sync is called with a NULL mount from the general syncing code.
1139  */
1140 void
1141 bio_ops_sync(struct mount *mp)
1142 {
1143 	struct bio_ops *ops;
1144 
1145 	if (mp) {
1146 		if ((ops = mp->mnt_bioops) != NULL)
1147 			ops->io_sync(mp);
1148 	} else {
1149 		TAILQ_FOREACH(ops, &bio_ops_list, entry) {
1150 			ops->io_sync(NULL);
1151 		}
1152 	}
1153 }
1154 
1155 /*
1156  * Lookup a mount point by nch
1157  */
1158 struct mount *
1159 mount_get_by_nc(struct namecache *ncp)
1160 {
1161 	struct mount *mp = NULL;
1162 
1163 	lwkt_gettoken_shared(&mountlist_token);
1164 	TAILQ_FOREACH(mp, &mountlist, mnt_list) {
1165 		if (ncp == mp->mnt_ncmountpt.ncp)
1166 			break;
1167 	}
1168 	lwkt_reltoken(&mountlist_token);
1169 
1170 	return (mp);
1171 }
1172 
1173