xref: /freebsd/sys/ufs/ffs/ffs_vfsops.c (revision 4f0c9b76cf75724ef0b9c59bb8c182be24361d7c)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1989, 1991, 1993, 1994
5  *	The Regents of the University of California.  All rights reserved.
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  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  *
31  *	@(#)ffs_vfsops.c	8.31 (Berkeley) 5/20/95
32  */
33 
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
36 
37 #include "opt_quota.h"
38 #include "opt_ufs.h"
39 #include "opt_ffs.h"
40 #include "opt_ddb.h"
41 
42 #include <sys/param.h>
43 #include <sys/gsb_crc32.h>
44 #include <sys/systm.h>
45 #include <sys/namei.h>
46 #include <sys/priv.h>
47 #include <sys/proc.h>
48 #include <sys/taskqueue.h>
49 #include <sys/kernel.h>
50 #include <sys/ktr.h>
51 #include <sys/vnode.h>
52 #include <sys/mount.h>
53 #include <sys/bio.h>
54 #include <sys/buf.h>
55 #include <sys/conf.h>
56 #include <sys/fcntl.h>
57 #include <sys/ioccom.h>
58 #include <sys/malloc.h>
59 #include <sys/mutex.h>
60 #include <sys/rwlock.h>
61 #include <sys/sysctl.h>
62 #include <sys/vmmeter.h>
63 
64 #include <security/mac/mac_framework.h>
65 
66 #include <ufs/ufs/dir.h>
67 #include <ufs/ufs/extattr.h>
68 #include <ufs/ufs/gjournal.h>
69 #include <ufs/ufs/quota.h>
70 #include <ufs/ufs/ufsmount.h>
71 #include <ufs/ufs/inode.h>
72 #include <ufs/ufs/ufs_extern.h>
73 
74 #include <ufs/ffs/fs.h>
75 #include <ufs/ffs/ffs_extern.h>
76 
77 #include <vm/vm.h>
78 #include <vm/uma.h>
79 #include <vm/vm_page.h>
80 
81 #include <geom/geom.h>
82 #include <geom/geom_vfs.h>
83 
84 #include <ddb/ddb.h>
85 
86 static uma_zone_t uma_inode, uma_ufs1, uma_ufs2;
87 VFS_SMR_DECLARE;
88 
89 static int	ffs_mountfs(struct vnode *, struct mount *, struct thread *);
90 static void	ffs_oldfscompat_read(struct fs *, struct ufsmount *,
91 		    ufs2_daddr_t);
92 static void	ffs_ifree(struct ufsmount *ump, struct inode *ip);
93 static int	ffs_sync_lazy(struct mount *mp);
94 static int	ffs_use_bread(void *devfd, off_t loc, void **bufp, int size);
95 static int	ffs_use_bwrite(void *devfd, off_t loc, void *buf, int size);
96 
97 static vfs_init_t ffs_init;
98 static vfs_uninit_t ffs_uninit;
99 static vfs_extattrctl_t ffs_extattrctl;
100 static vfs_cmount_t ffs_cmount;
101 static vfs_unmount_t ffs_unmount;
102 static vfs_mount_t ffs_mount;
103 static vfs_statfs_t ffs_statfs;
104 static vfs_fhtovp_t ffs_fhtovp;
105 static vfs_sync_t ffs_sync;
106 
107 static struct vfsops ufs_vfsops = {
108 	.vfs_extattrctl =	ffs_extattrctl,
109 	.vfs_fhtovp =		ffs_fhtovp,
110 	.vfs_init =		ffs_init,
111 	.vfs_mount =		ffs_mount,
112 	.vfs_cmount =		ffs_cmount,
113 	.vfs_quotactl =		ufs_quotactl,
114 	.vfs_root =		vfs_cache_root,
115 	.vfs_cachedroot =	ufs_root,
116 	.vfs_statfs =		ffs_statfs,
117 	.vfs_sync =		ffs_sync,
118 	.vfs_uninit =		ffs_uninit,
119 	.vfs_unmount =		ffs_unmount,
120 	.vfs_vget =		ffs_vget,
121 	.vfs_susp_clean =	process_deferred_inactive,
122 };
123 
124 VFS_SET(ufs_vfsops, ufs, 0);
125 MODULE_VERSION(ufs, 1);
126 
127 static b_strategy_t ffs_geom_strategy;
128 static b_write_t ffs_bufwrite;
129 
130 static struct buf_ops ffs_ops = {
131 	.bop_name =	"FFS",
132 	.bop_write =	ffs_bufwrite,
133 	.bop_strategy =	ffs_geom_strategy,
134 	.bop_sync =	bufsync,
135 #ifdef NO_FFS_SNAPSHOT
136 	.bop_bdflush =	bufbdflush,
137 #else
138 	.bop_bdflush =	ffs_bdflush,
139 #endif
140 };
141 
142 /*
143  * Note that userquota and groupquota options are not currently used
144  * by UFS/FFS code and generally mount(8) does not pass those options
145  * from userland, but they can be passed by loader(8) via
146  * vfs.root.mountfrom.options.
147  */
148 static const char *ffs_opts[] = { "acls", "async", "noatime", "noclusterr",
149     "noclusterw", "noexec", "export", "force", "from", "groupquota",
150     "multilabel", "nfsv4acls", "snapshot", "nosuid", "suiddir",
151     "nosymfollow", "sync", "union", "userquota", "untrusted", NULL };
152 
153 static int ffs_enxio_enable = 1;
154 SYSCTL_DECL(_vfs_ffs);
155 SYSCTL_INT(_vfs_ffs, OID_AUTO, enxio_enable, CTLFLAG_RWTUN,
156     &ffs_enxio_enable, 0,
157     "enable mapping of other disk I/O errors to ENXIO");
158 
159 /*
160  * Return buffer with the contents of block "offset" from the beginning of
161  * directory "ip".  If "res" is non-zero, fill it in with a pointer to the
162  * remaining space in the directory.
163  */
164 static int
165 ffs_blkatoff(struct vnode *vp, off_t offset, char **res, struct buf **bpp)
166 {
167 	struct inode *ip;
168 	struct fs *fs;
169 	struct buf *bp;
170 	ufs_lbn_t lbn;
171 	int bsize, error;
172 
173 	ip = VTOI(vp);
174 	fs = ITOFS(ip);
175 	lbn = lblkno(fs, offset);
176 	bsize = blksize(fs, ip, lbn);
177 
178 	*bpp = NULL;
179 	error = bread(vp, lbn, bsize, NOCRED, &bp);
180 	if (error) {
181 		return (error);
182 	}
183 	if (res)
184 		*res = (char *)bp->b_data + blkoff(fs, offset);
185 	*bpp = bp;
186 	return (0);
187 }
188 
189 /*
190  * Load up the contents of an inode and copy the appropriate pieces
191  * to the incore copy.
192  */
193 static int
194 ffs_load_inode(struct buf *bp, struct inode *ip, struct fs *fs, ino_t ino)
195 {
196 	struct ufs1_dinode *dip1;
197 	struct ufs2_dinode *dip2;
198 	int error;
199 
200 	if (I_IS_UFS1(ip)) {
201 		dip1 = ip->i_din1;
202 		*dip1 =
203 		    *((struct ufs1_dinode *)bp->b_data + ino_to_fsbo(fs, ino));
204 		ip->i_mode = dip1->di_mode;
205 		ip->i_nlink = dip1->di_nlink;
206 		ip->i_effnlink = dip1->di_nlink;
207 		ip->i_size = dip1->di_size;
208 		ip->i_flags = dip1->di_flags;
209 		ip->i_gen = dip1->di_gen;
210 		ip->i_uid = dip1->di_uid;
211 		ip->i_gid = dip1->di_gid;
212 		return (0);
213 	}
214 	dip2 = ((struct ufs2_dinode *)bp->b_data + ino_to_fsbo(fs, ino));
215 	if ((error = ffs_verify_dinode_ckhash(fs, dip2)) != 0 &&
216 	    !ffs_fsfail_cleanup(ITOUMP(ip), error)) {
217 		printf("%s: inode %jd: check-hash failed\n", fs->fs_fsmnt,
218 		    (intmax_t)ino);
219 		return (error);
220 	}
221 	*ip->i_din2 = *dip2;
222 	dip2 = ip->i_din2;
223 	ip->i_mode = dip2->di_mode;
224 	ip->i_nlink = dip2->di_nlink;
225 	ip->i_effnlink = dip2->di_nlink;
226 	ip->i_size = dip2->di_size;
227 	ip->i_flags = dip2->di_flags;
228 	ip->i_gen = dip2->di_gen;
229 	ip->i_uid = dip2->di_uid;
230 	ip->i_gid = dip2->di_gid;
231 	return (0);
232 }
233 
234 /*
235  * Verify that a filesystem block number is a valid data block.
236  * This routine is only called on untrusted filesystems.
237  */
238 static int
239 ffs_check_blkno(struct mount *mp, ino_t inum, ufs2_daddr_t daddr, int blksize)
240 {
241 	struct fs *fs;
242 	struct ufsmount *ump;
243 	ufs2_daddr_t end_daddr;
244 	int cg, havemtx;
245 
246 	KASSERT((mp->mnt_flag & MNT_UNTRUSTED) != 0,
247 	    ("ffs_check_blkno called on a trusted file system"));
248 	ump = VFSTOUFS(mp);
249 	fs = ump->um_fs;
250 	cg = dtog(fs, daddr);
251 	end_daddr = daddr + numfrags(fs, blksize);
252 	/*
253 	 * Verify that the block number is a valid data block. Also check
254 	 * that it does not point to an inode block or a superblock. Accept
255 	 * blocks that are unalloacted (0) or part of snapshot metadata
256 	 * (BLK_NOCOPY or BLK_SNAP).
257 	 *
258 	 * Thus, the block must be in a valid range for the filesystem and
259 	 * either in the space before a backup superblock (except the first
260 	 * cylinder group where that space is used by the bootstrap code) or
261 	 * after the inode blocks and before the end of the cylinder group.
262 	 */
263 	if ((uint64_t)daddr <= BLK_SNAP ||
264 	    ((uint64_t)end_daddr <= fs->fs_size &&
265 	    ((cg > 0 && end_daddr <= cgsblock(fs, cg)) ||
266 	    (daddr >= cgdmin(fs, cg) &&
267 	    end_daddr <= cgbase(fs, cg) + fs->fs_fpg))))
268 		return (0);
269 	if ((havemtx = mtx_owned(UFS_MTX(ump))) == 0)
270 		UFS_LOCK(ump);
271 	if (ppsratecheck(&ump->um_last_integritymsg,
272 	    &ump->um_secs_integritymsg, 1)) {
273 		UFS_UNLOCK(ump);
274 		uprintf("\n%s: inode %jd, out-of-range indirect block "
275 		    "number %jd\n", mp->mnt_stat.f_mntonname, inum, daddr);
276 		if (havemtx)
277 			UFS_LOCK(ump);
278 	} else if (!havemtx)
279 		UFS_UNLOCK(ump);
280 	return (EINTEGRITY);
281 }
282 
283 /*
284  * On first ENXIO error, initiate an asynchronous forcible unmount.
285  * Used to unmount filesystems whose underlying media has gone away.
286  *
287  * Return true if a cleanup is in progress.
288  */
289 int
290 ffs_fsfail_cleanup(struct ufsmount *ump, int error)
291 {
292 	int retval;
293 
294 	UFS_LOCK(ump);
295 	retval = ffs_fsfail_cleanup_locked(ump, error);
296 	UFS_UNLOCK(ump);
297 	return (retval);
298 }
299 
300 int
301 ffs_fsfail_cleanup_locked(struct ufsmount *ump, int error)
302 {
303 	mtx_assert(UFS_MTX(ump), MA_OWNED);
304 	if (error == ENXIO && (ump->um_flags & UM_FSFAIL_CLEANUP) == 0) {
305 		ump->um_flags |= UM_FSFAIL_CLEANUP;
306 		/*
307 		 * Queue an async forced unmount.
308 		 */
309 		vfs_ref(ump->um_mountp);
310 		dounmount(ump->um_mountp,
311 		    MNT_FORCE | MNT_RECURSE | MNT_DEFERRED, curthread);
312 		printf("UFS: forcibly unmounting %s from %s\n",
313 		    ump->um_mountp->mnt_stat.f_mntfromname,
314 		    ump->um_mountp->mnt_stat.f_mntonname);
315 	}
316 	return ((ump->um_flags & UM_FSFAIL_CLEANUP) != 0);
317 }
318 
319 /*
320  * Wrapper used during ENXIO cleanup to allocate empty buffers when
321  * the kernel is unable to read the real one. They are needed so that
322  * the soft updates code can use them to unwind its dependencies.
323  */
324 int
325 ffs_breadz(struct ufsmount *ump, struct vnode *vp, daddr_t lblkno,
326     daddr_t dblkno, int size, daddr_t *rablkno, int *rabsize, int cnt,
327     struct ucred *cred, int flags, void (*ckhashfunc)(struct buf *),
328     struct buf **bpp)
329 {
330 	int error;
331 
332 	flags |= GB_CVTENXIO;
333 	error = breadn_flags(vp, lblkno, dblkno, size, rablkno, rabsize, cnt,
334 	    cred, flags, ckhashfunc, bpp);
335 	if (error != 0 && ffs_fsfail_cleanup(ump, error)) {
336 		error = getblkx(vp, lblkno, dblkno, size, 0, 0, flags, bpp);
337 		KASSERT(error == 0, ("getblkx failed"));
338 		vfs_bio_bzero_buf(*bpp, 0, size);
339 	}
340 	return (error);
341 }
342 
343 static int
344 ffs_mount(struct mount *mp)
345 {
346 	struct vnode *devvp, *odevvp;
347 	struct thread *td;
348 	struct ufsmount *ump = NULL;
349 	struct fs *fs;
350 	int error, flags;
351 	int error1 __diagused;
352 	uint64_t mntorflags, saved_mnt_flag;
353 	accmode_t accmode;
354 	struct nameidata ndp;
355 	char *fspec;
356 	bool mounted_softdep;
357 
358 	td = curthread;
359 	if (vfs_filteropt(mp->mnt_optnew, ffs_opts))
360 		return (EINVAL);
361 	if (uma_inode == NULL) {
362 		uma_inode = uma_zcreate("FFS inode",
363 		    sizeof(struct inode), NULL, NULL, NULL, NULL,
364 		    UMA_ALIGN_PTR, 0);
365 		uma_ufs1 = uma_zcreate("FFS1 dinode",
366 		    sizeof(struct ufs1_dinode), NULL, NULL, NULL, NULL,
367 		    UMA_ALIGN_PTR, 0);
368 		uma_ufs2 = uma_zcreate("FFS2 dinode",
369 		    sizeof(struct ufs2_dinode), NULL, NULL, NULL, NULL,
370 		    UMA_ALIGN_PTR, 0);
371 		VFS_SMR_ZONE_SET(uma_inode);
372 	}
373 
374 	vfs_deleteopt(mp->mnt_optnew, "groupquota");
375 	vfs_deleteopt(mp->mnt_optnew, "userquota");
376 
377 	fspec = vfs_getopts(mp->mnt_optnew, "from", &error);
378 	if (error)
379 		return (error);
380 
381 	mntorflags = 0;
382 	if (vfs_getopt(mp->mnt_optnew, "untrusted", NULL, NULL) == 0)
383 		mntorflags |= MNT_UNTRUSTED;
384 
385 	if (vfs_getopt(mp->mnt_optnew, "acls", NULL, NULL) == 0)
386 		mntorflags |= MNT_ACLS;
387 
388 	if (vfs_getopt(mp->mnt_optnew, "snapshot", NULL, NULL) == 0) {
389 		mntorflags |= MNT_SNAPSHOT;
390 		/*
391 		 * Once we have set the MNT_SNAPSHOT flag, do not
392 		 * persist "snapshot" in the options list.
393 		 */
394 		vfs_deleteopt(mp->mnt_optnew, "snapshot");
395 		vfs_deleteopt(mp->mnt_opt, "snapshot");
396 	}
397 
398 	if (vfs_getopt(mp->mnt_optnew, "nfsv4acls", NULL, NULL) == 0) {
399 		if (mntorflags & MNT_ACLS) {
400 			vfs_mount_error(mp,
401 			    "\"acls\" and \"nfsv4acls\" options "
402 			    "are mutually exclusive");
403 			return (EINVAL);
404 		}
405 		mntorflags |= MNT_NFS4ACLS;
406 	}
407 
408 	MNT_ILOCK(mp);
409 	mp->mnt_kern_flag &= ~MNTK_FPLOOKUP;
410 	mp->mnt_flag |= mntorflags;
411 	MNT_IUNLOCK(mp);
412 
413 	/*
414 	 * If this is a snapshot request, take the snapshot.
415 	 */
416 	if (mp->mnt_flag & MNT_SNAPSHOT)
417 		return (ffs_snapshot(mp, fspec));
418 
419 	/*
420 	 * Must not call namei() while owning busy ref.
421 	 */
422 	if (mp->mnt_flag & MNT_UPDATE)
423 		vfs_unbusy(mp);
424 
425 	/*
426 	 * Not an update, or updating the name: look up the name
427 	 * and verify that it refers to a sensible disk device.
428 	 */
429 	NDINIT(&ndp, LOOKUP, FOLLOW | LOCKLEAF, UIO_SYSSPACE, fspec);
430 	error = namei(&ndp);
431 	if ((mp->mnt_flag & MNT_UPDATE) != 0) {
432 		/*
433 		 * Unmount does not start if MNT_UPDATE is set.  Mount
434 		 * update busies mp before setting MNT_UPDATE.  We
435 		 * must be able to retain our busy ref successfully,
436 		 * without sleep.
437 		 */
438 		error1 = vfs_busy(mp, MBF_NOWAIT);
439 		MPASS(error1 == 0);
440 	}
441 	if (error != 0)
442 		return (error);
443 	NDFREE_PNBUF(&ndp);
444 	if (!vn_isdisk_error(ndp.ni_vp, &error)) {
445 		vput(ndp.ni_vp);
446 		return (error);
447 	}
448 
449 	/*
450 	 * If mount by non-root, then verify that user has necessary
451 	 * permissions on the device.
452 	 */
453 	accmode = VREAD;
454 	if ((mp->mnt_flag & MNT_RDONLY) == 0)
455 		accmode |= VWRITE;
456 	error = VOP_ACCESS(ndp.ni_vp, accmode, td->td_ucred, td);
457 	if (error)
458 		error = priv_check(td, PRIV_VFS_MOUNT_PERM);
459 	if (error) {
460 		vput(ndp.ni_vp);
461 		return (error);
462 	}
463 
464 	/*
465 	 * New mount
466 	 *
467 	 * We need the name for the mount point (also used for
468 	 * "last mounted on") copied in. If an error occurs,
469 	 * the mount point is discarded by the upper level code.
470 	 * Note that vfs_mount_alloc() populates f_mntonname for us.
471 	 */
472 	if ((mp->mnt_flag & MNT_UPDATE) == 0) {
473 		if ((error = ffs_mountfs(ndp.ni_vp, mp, td)) != 0) {
474 			vrele(ndp.ni_vp);
475 			return (error);
476 		}
477 	} else {
478 		/*
479 		 * When updating, check whether changing from read-only to
480 		 * read/write; if there is no device name, that's all we do.
481 		 */
482 		ump = VFSTOUFS(mp);
483 		fs = ump->um_fs;
484 		odevvp = ump->um_odevvp;
485 		devvp = ump->um_devvp;
486 
487 		/*
488 		 * If it's not the same vnode, or at least the same device
489 		 * then it's not correct.
490 		 */
491 		if (ndp.ni_vp->v_rdev != ump->um_odevvp->v_rdev)
492 			error = EINVAL; /* needs translation */
493 		vput(ndp.ni_vp);
494 		if (error)
495 			return (error);
496 		if (fs->fs_ronly == 0 &&
497 		    vfs_flagopt(mp->mnt_optnew, "ro", NULL, 0)) {
498 			/*
499 			 * Flush any dirty data and suspend filesystem.
500 			 */
501 			if ((error = vn_start_write(NULL, &mp, V_WAIT)) != 0)
502 				return (error);
503 			error = vfs_write_suspend_umnt(mp);
504 			if (error != 0)
505 				return (error);
506 
507 			fs->fs_ronly = 1;
508 			if (MOUNTEDSOFTDEP(mp)) {
509 				MNT_ILOCK(mp);
510 				mp->mnt_flag &= ~MNT_SOFTDEP;
511 				MNT_IUNLOCK(mp);
512 				mounted_softdep = true;
513 			} else
514 				mounted_softdep = false;
515 
516 			/*
517 			 * Check for and optionally get rid of files open
518 			 * for writing.
519 			 */
520 			flags = WRITECLOSE;
521 			if (mp->mnt_flag & MNT_FORCE)
522 				flags |= FORCECLOSE;
523 			if (mounted_softdep) {
524 				error = softdep_flushfiles(mp, flags, td);
525 			} else {
526 				error = ffs_flushfiles(mp, flags, td);
527 			}
528 			if (error) {
529 				fs->fs_ronly = 0;
530 				if (mounted_softdep) {
531 					MNT_ILOCK(mp);
532 					mp->mnt_flag |= MNT_SOFTDEP;
533 					MNT_IUNLOCK(mp);
534 				}
535 				vfs_write_resume(mp, 0);
536 				return (error);
537 			}
538 
539 			if (fs->fs_pendingblocks != 0 ||
540 			    fs->fs_pendinginodes != 0) {
541 				printf("WARNING: %s Update error: blocks %jd "
542 				    "files %d\n", fs->fs_fsmnt,
543 				    (intmax_t)fs->fs_pendingblocks,
544 				    fs->fs_pendinginodes);
545 				fs->fs_pendingblocks = 0;
546 				fs->fs_pendinginodes = 0;
547 			}
548 			if ((fs->fs_flags & (FS_UNCLEAN | FS_NEEDSFSCK)) == 0)
549 				fs->fs_clean = 1;
550 			if ((error = ffs_sbupdate(ump, MNT_WAIT, 0)) != 0) {
551 				fs->fs_ronly = 0;
552 				fs->fs_clean = 0;
553 				if (mounted_softdep) {
554 					MNT_ILOCK(mp);
555 					mp->mnt_flag |= MNT_SOFTDEP;
556 					MNT_IUNLOCK(mp);
557 				}
558 				vfs_write_resume(mp, 0);
559 				return (error);
560 			}
561 			if (mounted_softdep)
562 				softdep_unmount(mp);
563 			g_topology_lock();
564 			/*
565 			 * Drop our write and exclusive access.
566 			 */
567 			g_access(ump->um_cp, 0, -1, -1);
568 			g_topology_unlock();
569 			MNT_ILOCK(mp);
570 			mp->mnt_flag |= MNT_RDONLY;
571 			MNT_IUNLOCK(mp);
572 			/*
573 			 * Allow the writers to note that filesystem
574 			 * is ro now.
575 			 */
576 			vfs_write_resume(mp, 0);
577 		}
578 		if ((mp->mnt_flag & MNT_RELOAD) &&
579 		    (error = ffs_reload(mp, 0)) != 0)
580 			return (error);
581 		if (fs->fs_ronly &&
582 		    !vfs_flagopt(mp->mnt_optnew, "ro", NULL, 0)) {
583 			/*
584 			 * If upgrade to read-write by non-root, then verify
585 			 * that user has necessary permissions on the device.
586 			 */
587 			vn_lock(odevvp, LK_EXCLUSIVE | LK_RETRY);
588 			error = VOP_ACCESS(odevvp, VREAD | VWRITE,
589 			    td->td_ucred, td);
590 			if (error)
591 				error = priv_check(td, PRIV_VFS_MOUNT_PERM);
592 			VOP_UNLOCK(odevvp);
593 			if (error) {
594 				return (error);
595 			}
596 			fs->fs_flags &= ~FS_UNCLEAN;
597 			if (fs->fs_clean == 0) {
598 				fs->fs_flags |= FS_UNCLEAN;
599 				if ((mp->mnt_flag & MNT_FORCE) ||
600 				    ((fs->fs_flags &
601 				     (FS_SUJ | FS_NEEDSFSCK)) == 0 &&
602 				     (fs->fs_flags & FS_DOSOFTDEP))) {
603 					printf("WARNING: %s was not properly "
604 					   "dismounted\n", fs->fs_fsmnt);
605 				} else {
606 					vfs_mount_error(mp,
607 					   "R/W mount of %s denied. %s.%s",
608 					   fs->fs_fsmnt,
609 					   "Filesystem is not clean - run fsck",
610 					   (fs->fs_flags & FS_SUJ) == 0 ? "" :
611 					   " Forced mount will invalidate"
612 					   " journal contents");
613 					return (EPERM);
614 				}
615 			}
616 			g_topology_lock();
617 			/*
618 			 * Request exclusive write access.
619 			 */
620 			error = g_access(ump->um_cp, 0, 1, 1);
621 			g_topology_unlock();
622 			if (error)
623 				return (error);
624 			if ((error = vn_start_write(NULL, &mp, V_WAIT)) != 0)
625 				return (error);
626 			error = vfs_write_suspend_umnt(mp);
627 			if (error != 0)
628 				return (error);
629 			fs->fs_ronly = 0;
630 			MNT_ILOCK(mp);
631 			saved_mnt_flag = MNT_RDONLY;
632 			if (MOUNTEDSOFTDEP(mp) && (mp->mnt_flag &
633 			    MNT_ASYNC) != 0)
634 				saved_mnt_flag |= MNT_ASYNC;
635 			mp->mnt_flag &= ~saved_mnt_flag;
636 			MNT_IUNLOCK(mp);
637 			fs->fs_mtime = time_second;
638 			/* check to see if we need to start softdep */
639 			if ((fs->fs_flags & FS_DOSOFTDEP) &&
640 			    (error = softdep_mount(devvp, mp, fs, td->td_ucred))){
641 				fs->fs_ronly = 1;
642 				MNT_ILOCK(mp);
643 				mp->mnt_flag |= saved_mnt_flag;
644 				MNT_IUNLOCK(mp);
645 				vfs_write_resume(mp, 0);
646 				return (error);
647 			}
648 			fs->fs_clean = 0;
649 			if ((error = ffs_sbupdate(ump, MNT_WAIT, 0)) != 0) {
650 				fs->fs_ronly = 1;
651 				if ((fs->fs_flags & FS_DOSOFTDEP) != 0)
652 					softdep_unmount(mp);
653 				MNT_ILOCK(mp);
654 				mp->mnt_flag |= saved_mnt_flag;
655 				MNT_IUNLOCK(mp);
656 				vfs_write_resume(mp, 0);
657 				return (error);
658 			}
659 			if (fs->fs_snapinum[0] != 0)
660 				ffs_snapshot_mount(mp);
661 			vfs_write_resume(mp, 0);
662 		}
663 		/*
664 		 * Soft updates is incompatible with "async",
665 		 * so if we are doing softupdates stop the user
666 		 * from setting the async flag in an update.
667 		 * Softdep_mount() clears it in an initial mount
668 		 * or ro->rw remount.
669 		 */
670 		if (MOUNTEDSOFTDEP(mp)) {
671 			/* XXX: Reset too late ? */
672 			MNT_ILOCK(mp);
673 			mp->mnt_flag &= ~MNT_ASYNC;
674 			MNT_IUNLOCK(mp);
675 		}
676 		/*
677 		 * Keep MNT_ACLS flag if it is stored in superblock.
678 		 */
679 		if ((fs->fs_flags & FS_ACLS) != 0) {
680 			/* XXX: Set too late ? */
681 			MNT_ILOCK(mp);
682 			mp->mnt_flag |= MNT_ACLS;
683 			MNT_IUNLOCK(mp);
684 		}
685 
686 		if ((fs->fs_flags & FS_NFS4ACLS) != 0) {
687 			/* XXX: Set too late ? */
688 			MNT_ILOCK(mp);
689 			mp->mnt_flag |= MNT_NFS4ACLS;
690 			MNT_IUNLOCK(mp);
691 		}
692 
693 	}
694 
695 	MNT_ILOCK(mp);
696 	/*
697 	 * This is racy versus lookup, see ufs_fplookup_vexec for details.
698 	 */
699 	if ((mp->mnt_kern_flag & MNTK_FPLOOKUP) != 0)
700 		panic("MNTK_FPLOOKUP set on mount %p when it should not be", mp);
701 	if ((mp->mnt_flag & (MNT_ACLS | MNT_NFS4ACLS | MNT_UNION)) == 0)
702 		mp->mnt_kern_flag |= MNTK_FPLOOKUP;
703 	MNT_IUNLOCK(mp);
704 
705 	vfs_mountedfrom(mp, fspec);
706 	return (0);
707 }
708 
709 /*
710  * Compatibility with old mount system call.
711  */
712 
713 static int
714 ffs_cmount(struct mntarg *ma, void *data, uint64_t flags)
715 {
716 	struct ufs_args args;
717 	int error;
718 
719 	if (data == NULL)
720 		return (EINVAL);
721 	error = copyin(data, &args, sizeof args);
722 	if (error)
723 		return (error);
724 
725 	ma = mount_argsu(ma, "from", args.fspec, MAXPATHLEN);
726 	ma = mount_arg(ma, "export", &args.export, sizeof(args.export));
727 	error = kernel_mount(ma, flags);
728 
729 	return (error);
730 }
731 
732 /*
733  * Reload all incore data for a filesystem (used after running fsck on
734  * the root filesystem and finding things to fix). If the 'force' flag
735  * is 0, the filesystem must be mounted read-only.
736  *
737  * Things to do to update the mount:
738  *	1) invalidate all cached meta-data.
739  *	2) re-read superblock from disk.
740  *	3) re-read summary information from disk.
741  *	4) invalidate all inactive vnodes.
742  *	5) clear MNTK_SUSPEND2 and MNTK_SUSPENDED flags, allowing secondary
743  *	   writers, if requested.
744  *	6) invalidate all cached file data.
745  *	7) re-read inode data for all active vnodes.
746  */
747 int
748 ffs_reload(struct mount *mp, int flags)
749 {
750 	struct vnode *vp, *mvp, *devvp;
751 	struct inode *ip;
752 	void *space;
753 	struct buf *bp;
754 	struct fs *fs, *newfs;
755 	struct ufsmount *ump;
756 	ufs2_daddr_t sblockloc;
757 	int i, blks, error;
758 	u_long size;
759 	int32_t *lp;
760 
761 	ump = VFSTOUFS(mp);
762 
763 	MNT_ILOCK(mp);
764 	if ((mp->mnt_flag & MNT_RDONLY) == 0 && (flags & FFSR_FORCE) == 0) {
765 		MNT_IUNLOCK(mp);
766 		return (EINVAL);
767 	}
768 	MNT_IUNLOCK(mp);
769 
770 	/*
771 	 * Step 1: invalidate all cached meta-data.
772 	 */
773 	devvp = VFSTOUFS(mp)->um_devvp;
774 	vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
775 	if (vinvalbuf(devvp, 0, 0, 0) != 0)
776 		panic("ffs_reload: dirty1");
777 	VOP_UNLOCK(devvp);
778 
779 	/*
780 	 * Step 2: re-read superblock from disk.
781 	 */
782 	fs = VFSTOUFS(mp)->um_fs;
783 	if ((error = bread(devvp, btodb(fs->fs_sblockloc), fs->fs_sbsize,
784 	    NOCRED, &bp)) != 0)
785 		return (error);
786 	newfs = (struct fs *)bp->b_data;
787 	if ((newfs->fs_magic != FS_UFS1_MAGIC &&
788 	     newfs->fs_magic != FS_UFS2_MAGIC) ||
789 	    newfs->fs_bsize > MAXBSIZE ||
790 	    newfs->fs_bsize < sizeof(struct fs)) {
791 			brelse(bp);
792 			return (EIO);		/* XXX needs translation */
793 	}
794 	/*
795 	 * Preserve the summary information, read-only status, and
796 	 * superblock location by copying these fields into our new
797 	 * superblock before using it to update the existing superblock.
798 	 */
799 	newfs->fs_si = fs->fs_si;
800 	newfs->fs_ronly = fs->fs_ronly;
801 	sblockloc = fs->fs_sblockloc;
802 	bcopy(newfs, fs, (u_int)fs->fs_sbsize);
803 	brelse(bp);
804 	ump->um_bsize = fs->fs_bsize;
805 	ump->um_maxsymlinklen = fs->fs_maxsymlinklen;
806 	ffs_oldfscompat_read(fs, VFSTOUFS(mp), sblockloc);
807 	UFS_LOCK(ump);
808 	if (fs->fs_pendingblocks != 0 || fs->fs_pendinginodes != 0) {
809 		printf("WARNING: %s: reload pending error: blocks %jd "
810 		    "files %d\n", fs->fs_fsmnt, (intmax_t)fs->fs_pendingblocks,
811 		    fs->fs_pendinginodes);
812 		fs->fs_pendingblocks = 0;
813 		fs->fs_pendinginodes = 0;
814 	}
815 	UFS_UNLOCK(ump);
816 
817 	/*
818 	 * Step 3: re-read summary information from disk.
819 	 */
820 	size = fs->fs_cssize;
821 	blks = howmany(size, fs->fs_fsize);
822 	if (fs->fs_contigsumsize > 0)
823 		size += fs->fs_ncg * sizeof(int32_t);
824 	size += fs->fs_ncg * sizeof(u_int8_t);
825 	free(fs->fs_csp, M_UFSMNT);
826 	space = malloc(size, M_UFSMNT, M_WAITOK);
827 	fs->fs_csp = space;
828 	for (i = 0; i < blks; i += fs->fs_frag) {
829 		size = fs->fs_bsize;
830 		if (i + fs->fs_frag > blks)
831 			size = (blks - i) * fs->fs_fsize;
832 		error = bread(devvp, fsbtodb(fs, fs->fs_csaddr + i), size,
833 		    NOCRED, &bp);
834 		if (error)
835 			return (error);
836 		bcopy(bp->b_data, space, (u_int)size);
837 		space = (char *)space + size;
838 		brelse(bp);
839 	}
840 	/*
841 	 * We no longer know anything about clusters per cylinder group.
842 	 */
843 	if (fs->fs_contigsumsize > 0) {
844 		fs->fs_maxcluster = lp = space;
845 		for (i = 0; i < fs->fs_ncg; i++)
846 			*lp++ = fs->fs_contigsumsize;
847 		space = lp;
848 	}
849 	size = fs->fs_ncg * sizeof(u_int8_t);
850 	fs->fs_contigdirs = (u_int8_t *)space;
851 	bzero(fs->fs_contigdirs, size);
852 	if ((flags & FFSR_UNSUSPEND) != 0) {
853 		MNT_ILOCK(mp);
854 		mp->mnt_kern_flag &= ~(MNTK_SUSPENDED | MNTK_SUSPEND2);
855 		wakeup(&mp->mnt_flag);
856 		MNT_IUNLOCK(mp);
857 	}
858 
859 loop:
860 	MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
861 		/*
862 		 * Skip syncer vnode.
863 		 */
864 		if (vp->v_type == VNON) {
865 			VI_UNLOCK(vp);
866 			continue;
867 		}
868 		/*
869 		 * Step 4: invalidate all cached file data.
870 		 */
871 		if (vget(vp, LK_EXCLUSIVE | LK_INTERLOCK)) {
872 			MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
873 			goto loop;
874 		}
875 		if (vinvalbuf(vp, 0, 0, 0))
876 			panic("ffs_reload: dirty2");
877 		/*
878 		 * Step 5: re-read inode data for all active vnodes.
879 		 */
880 		ip = VTOI(vp);
881 		error =
882 		    bread(devvp, fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
883 		    (int)fs->fs_bsize, NOCRED, &bp);
884 		if (error) {
885 			vput(vp);
886 			MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
887 			return (error);
888 		}
889 		if ((error = ffs_load_inode(bp, ip, fs, ip->i_number)) != 0) {
890 			brelse(bp);
891 			vput(vp);
892 			MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
893 			return (error);
894 		}
895 		ip->i_effnlink = ip->i_nlink;
896 		brelse(bp);
897 		vput(vp);
898 	}
899 	return (0);
900 }
901 
902 /*
903  * Common code for mount and mountroot
904  */
905 static int
906 ffs_mountfs(struct vnode *odevvp, struct mount *mp, struct thread *td)
907 {
908 	struct ufsmount *ump;
909 	struct fs *fs;
910 	struct cdev *dev;
911 	int error, i, len, ronly;
912 	struct ucred *cred;
913 	struct g_consumer *cp;
914 	struct mount *nmp;
915 	struct vnode *devvp;
916 	int candelete, canspeedup, flags;
917 	off_t loc;
918 
919 	fs = NULL;
920 	ump = NULL;
921 	cred = td ? td->td_ucred : NOCRED;
922 	ronly = (mp->mnt_flag & MNT_RDONLY) != 0;
923 
924 	devvp = mntfs_allocvp(mp, odevvp);
925 	VOP_UNLOCK(odevvp);
926 	vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
927 	KASSERT(devvp->v_type == VCHR, ("reclaimed devvp"));
928 	dev = devvp->v_rdev;
929 	KASSERT(dev->si_snapdata == NULL, ("non-NULL snapshot data"));
930 	if (atomic_cmpset_acq_ptr((uintptr_t *)&dev->si_mountpt, 0,
931 	    (uintptr_t)mp) == 0) {
932 		mntfs_freevp(devvp);
933 		return (EBUSY);
934 	}
935 	g_topology_lock();
936 	error = g_vfs_open(devvp, &cp, "ffs", ronly ? 0 : 1);
937 	g_topology_unlock();
938 	if (error != 0) {
939 		atomic_store_rel_ptr((uintptr_t *)&dev->si_mountpt, 0);
940 		mntfs_freevp(devvp);
941 		return (error);
942 	}
943 	dev_ref(dev);
944 	devvp->v_bufobj.bo_ops = &ffs_ops;
945 	BO_LOCK(&odevvp->v_bufobj);
946 	odevvp->v_bufobj.bo_flag |= BO_NOBUFS;
947 	BO_UNLOCK(&odevvp->v_bufobj);
948 	VOP_UNLOCK(devvp);
949 	if (dev->si_iosize_max != 0)
950 		mp->mnt_iosize_max = dev->si_iosize_max;
951 	if (mp->mnt_iosize_max > maxphys)
952 		mp->mnt_iosize_max = maxphys;
953 	if ((SBLOCKSIZE % cp->provider->sectorsize) != 0) {
954 		error = EINVAL;
955 		vfs_mount_error(mp,
956 		    "Invalid sectorsize %d for superblock size %d",
957 		    cp->provider->sectorsize, SBLOCKSIZE);
958 		goto out;
959 	}
960 	/* fetch the superblock and summary information */
961 	loc = UFS_STDSB;
962 	flags = 0;
963 	if ((mp->mnt_flag & (MNT_ROOTFS | MNT_FORCE)) != 0)
964 		flags = UFS_NOHASHFAIL;
965 	if ((error = ffs_sbget(devvp, &fs, loc, flags, M_UFSMNT, ffs_use_bread))
966 	    != 0)
967 		goto out;
968 	fs->fs_flags &= ~FS_UNCLEAN;
969 	if (fs->fs_clean == 0) {
970 		fs->fs_flags |= FS_UNCLEAN;
971 		if (ronly || (mp->mnt_flag & MNT_FORCE) ||
972 		    ((fs->fs_flags & (FS_SUJ | FS_NEEDSFSCK)) == 0 &&
973 		     (fs->fs_flags & FS_DOSOFTDEP))) {
974 			printf("WARNING: %s was not properly dismounted\n",
975 			    fs->fs_fsmnt);
976 		} else {
977 			vfs_mount_error(mp, "R/W mount of %s denied. %s%s",
978 			    fs->fs_fsmnt, "Filesystem is not clean - run fsck.",
979 			    (fs->fs_flags & FS_SUJ) == 0 ? "" :
980 			    " Forced mount will invalidate journal contents");
981 			error = EPERM;
982 			goto out;
983 		}
984 		if ((fs->fs_pendingblocks != 0 || fs->fs_pendinginodes != 0) &&
985 		    (mp->mnt_flag & MNT_FORCE)) {
986 			printf("WARNING: %s: lost blocks %jd files %d\n",
987 			    fs->fs_fsmnt, (intmax_t)fs->fs_pendingblocks,
988 			    fs->fs_pendinginodes);
989 			fs->fs_pendingblocks = 0;
990 			fs->fs_pendinginodes = 0;
991 		}
992 	}
993 	if (fs->fs_pendingblocks != 0 || fs->fs_pendinginodes != 0) {
994 		printf("WARNING: %s: mount pending error: blocks %jd "
995 		    "files %d\n", fs->fs_fsmnt, (intmax_t)fs->fs_pendingblocks,
996 		    fs->fs_pendinginodes);
997 		fs->fs_pendingblocks = 0;
998 		fs->fs_pendinginodes = 0;
999 	}
1000 	if ((fs->fs_flags & FS_GJOURNAL) != 0) {
1001 #ifdef UFS_GJOURNAL
1002 		/*
1003 		 * Get journal provider name.
1004 		 */
1005 		len = 1024;
1006 		mp->mnt_gjprovider = malloc((u_long)len, M_UFSMNT, M_WAITOK);
1007 		if (g_io_getattr("GJOURNAL::provider", cp, &len,
1008 		    mp->mnt_gjprovider) == 0) {
1009 			mp->mnt_gjprovider = realloc(mp->mnt_gjprovider, len,
1010 			    M_UFSMNT, M_WAITOK);
1011 			MNT_ILOCK(mp);
1012 			mp->mnt_flag |= MNT_GJOURNAL;
1013 			MNT_IUNLOCK(mp);
1014 		} else {
1015 			if ((mp->mnt_flag & MNT_RDONLY) == 0)
1016 				printf("WARNING: %s: GJOURNAL flag on fs "
1017 				    "but no gjournal provider below\n",
1018 				    mp->mnt_stat.f_mntonname);
1019 			free(mp->mnt_gjprovider, M_UFSMNT);
1020 			mp->mnt_gjprovider = NULL;
1021 		}
1022 #else
1023 		printf("WARNING: %s: GJOURNAL flag on fs but no "
1024 		    "UFS_GJOURNAL support\n", mp->mnt_stat.f_mntonname);
1025 #endif
1026 	} else {
1027 		mp->mnt_gjprovider = NULL;
1028 	}
1029 	ump = malloc(sizeof *ump, M_UFSMNT, M_WAITOK | M_ZERO);
1030 	ump->um_cp = cp;
1031 	ump->um_bo = &devvp->v_bufobj;
1032 	ump->um_fs = fs;
1033 	if (fs->fs_magic == FS_UFS1_MAGIC) {
1034 		ump->um_fstype = UFS1;
1035 		ump->um_balloc = ffs_balloc_ufs1;
1036 	} else {
1037 		ump->um_fstype = UFS2;
1038 		ump->um_balloc = ffs_balloc_ufs2;
1039 	}
1040 	ump->um_blkatoff = ffs_blkatoff;
1041 	ump->um_truncate = ffs_truncate;
1042 	ump->um_update = ffs_update;
1043 	ump->um_valloc = ffs_valloc;
1044 	ump->um_vfree = ffs_vfree;
1045 	ump->um_ifree = ffs_ifree;
1046 	ump->um_rdonly = ffs_rdonly;
1047 	ump->um_snapgone = ffs_snapgone;
1048 	if ((mp->mnt_flag & MNT_UNTRUSTED) != 0)
1049 		ump->um_check_blkno = ffs_check_blkno;
1050 	else
1051 		ump->um_check_blkno = NULL;
1052 	mtx_init(UFS_MTX(ump), "FFS", "FFS Lock", MTX_DEF);
1053 	sx_init(&ump->um_checkpath_lock, "uchpth");
1054 	ffs_oldfscompat_read(fs, ump, fs->fs_sblockloc);
1055 	fs->fs_ronly = ronly;
1056 	fs->fs_active = NULL;
1057 	mp->mnt_data = ump;
1058 	mp->mnt_stat.f_fsid.val[0] = fs->fs_id[0];
1059 	mp->mnt_stat.f_fsid.val[1] = fs->fs_id[1];
1060 	nmp = NULL;
1061 	if (fs->fs_id[0] == 0 || fs->fs_id[1] == 0 ||
1062 	    (nmp = vfs_getvfs(&mp->mnt_stat.f_fsid))) {
1063 		if (nmp)
1064 			vfs_rel(nmp);
1065 		vfs_getnewfsid(mp);
1066 	}
1067 	ump->um_bsize = fs->fs_bsize;
1068 	ump->um_maxsymlinklen = fs->fs_maxsymlinklen;
1069 	MNT_ILOCK(mp);
1070 	mp->mnt_flag |= MNT_LOCAL;
1071 	MNT_IUNLOCK(mp);
1072 	if ((fs->fs_flags & FS_MULTILABEL) != 0) {
1073 #ifdef MAC
1074 		MNT_ILOCK(mp);
1075 		mp->mnt_flag |= MNT_MULTILABEL;
1076 		MNT_IUNLOCK(mp);
1077 #else
1078 		printf("WARNING: %s: multilabel flag on fs but "
1079 		    "no MAC support\n", mp->mnt_stat.f_mntonname);
1080 #endif
1081 	}
1082 	if ((fs->fs_flags & FS_ACLS) != 0) {
1083 #ifdef UFS_ACL
1084 		MNT_ILOCK(mp);
1085 
1086 		if (mp->mnt_flag & MNT_NFS4ACLS)
1087 			printf("WARNING: %s: ACLs flag on fs conflicts with "
1088 			    "\"nfsv4acls\" mount option; option ignored\n",
1089 			    mp->mnt_stat.f_mntonname);
1090 		mp->mnt_flag &= ~MNT_NFS4ACLS;
1091 		mp->mnt_flag |= MNT_ACLS;
1092 
1093 		MNT_IUNLOCK(mp);
1094 #else
1095 		printf("WARNING: %s: ACLs flag on fs but no ACLs support\n",
1096 		    mp->mnt_stat.f_mntonname);
1097 #endif
1098 	}
1099 	if ((fs->fs_flags & FS_NFS4ACLS) != 0) {
1100 #ifdef UFS_ACL
1101 		MNT_ILOCK(mp);
1102 
1103 		if (mp->mnt_flag & MNT_ACLS)
1104 			printf("WARNING: %s: NFSv4 ACLs flag on fs conflicts "
1105 			    "with \"acls\" mount option; option ignored\n",
1106 			    mp->mnt_stat.f_mntonname);
1107 		mp->mnt_flag &= ~MNT_ACLS;
1108 		mp->mnt_flag |= MNT_NFS4ACLS;
1109 
1110 		MNT_IUNLOCK(mp);
1111 #else
1112 		printf("WARNING: %s: NFSv4 ACLs flag on fs but no "
1113 		    "ACLs support\n", mp->mnt_stat.f_mntonname);
1114 #endif
1115 	}
1116 	if ((fs->fs_flags & FS_TRIM) != 0) {
1117 		len = sizeof(int);
1118 		if (g_io_getattr("GEOM::candelete", cp, &len,
1119 		    &candelete) == 0) {
1120 			if (candelete)
1121 				ump->um_flags |= UM_CANDELETE;
1122 			else
1123 				printf("WARNING: %s: TRIM flag on fs but disk "
1124 				    "does not support TRIM\n",
1125 				    mp->mnt_stat.f_mntonname);
1126 		} else {
1127 			printf("WARNING: %s: TRIM flag on fs but disk does "
1128 			    "not confirm that it supports TRIM\n",
1129 			    mp->mnt_stat.f_mntonname);
1130 		}
1131 		if (((ump->um_flags) & UM_CANDELETE) != 0) {
1132 			ump->um_trim_tq = taskqueue_create("trim", M_WAITOK,
1133 			    taskqueue_thread_enqueue, &ump->um_trim_tq);
1134 			taskqueue_start_threads(&ump->um_trim_tq, 1, PVFS,
1135 			    "%s trim", mp->mnt_stat.f_mntonname);
1136 			ump->um_trimhash = hashinit(MAXTRIMIO, M_TRIM,
1137 			    &ump->um_trimlisthashsize);
1138 		}
1139 	}
1140 
1141 	len = sizeof(int);
1142 	if (g_io_getattr("GEOM::canspeedup", cp, &len, &canspeedup) == 0) {
1143 		if (canspeedup)
1144 			ump->um_flags |= UM_CANSPEEDUP;
1145 	}
1146 
1147 	ump->um_mountp = mp;
1148 	ump->um_dev = dev;
1149 	ump->um_devvp = devvp;
1150 	ump->um_odevvp = odevvp;
1151 	ump->um_nindir = fs->fs_nindir;
1152 	ump->um_bptrtodb = fs->fs_fsbtodb;
1153 	ump->um_seqinc = fs->fs_frag;
1154 	for (i = 0; i < MAXQUOTAS; i++)
1155 		ump->um_quotas[i] = NULLVP;
1156 #ifdef UFS_EXTATTR
1157 	ufs_extattr_uepm_init(&ump->um_extattr);
1158 #endif
1159 	/*
1160 	 * Set FS local "last mounted on" information (NULL pad)
1161 	 */
1162 	bzero(fs->fs_fsmnt, MAXMNTLEN);
1163 	strlcpy(fs->fs_fsmnt, mp->mnt_stat.f_mntonname, MAXMNTLEN);
1164 	mp->mnt_stat.f_iosize = fs->fs_bsize;
1165 
1166 	if (mp->mnt_flag & MNT_ROOTFS) {
1167 		/*
1168 		 * Root mount; update timestamp in mount structure.
1169 		 * this will be used by the common root mount code
1170 		 * to update the system clock.
1171 		 */
1172 		mp->mnt_time = fs->fs_time;
1173 	}
1174 
1175 	if (ronly == 0) {
1176 		fs->fs_mtime = time_second;
1177 		if ((fs->fs_flags & FS_DOSOFTDEP) &&
1178 		    (error = softdep_mount(devvp, mp, fs, cred)) != 0) {
1179 			ffs_flushfiles(mp, FORCECLOSE, td);
1180 			goto out;
1181 		}
1182 		if (fs->fs_snapinum[0] != 0)
1183 			ffs_snapshot_mount(mp);
1184 		fs->fs_fmod = 1;
1185 		fs->fs_clean = 0;
1186 		(void) ffs_sbupdate(ump, MNT_WAIT, 0);
1187 	}
1188 	/*
1189 	 * Initialize filesystem state information in mount struct.
1190 	 */
1191 	MNT_ILOCK(mp);
1192 	mp->mnt_kern_flag |= MNTK_LOOKUP_SHARED | MNTK_EXTENDED_SHARED |
1193 	    MNTK_NO_IOPF | MNTK_UNMAPPED_BUFS | MNTK_USES_BCACHE;
1194 	MNT_IUNLOCK(mp);
1195 #ifdef UFS_EXTATTR
1196 #ifdef UFS_EXTATTR_AUTOSTART
1197 	/*
1198 	 *
1199 	 * Auto-starting does the following:
1200 	 *	- check for /.attribute in the fs, and extattr_start if so
1201 	 *	- for each file in .attribute, enable that file with
1202 	 * 	  an attribute of the same name.
1203 	 * Not clear how to report errors -- probably eat them.
1204 	 * This would all happen while the filesystem was busy/not
1205 	 * available, so would effectively be "atomic".
1206 	 */
1207 	(void) ufs_extattr_autostart(mp, td);
1208 #endif /* !UFS_EXTATTR_AUTOSTART */
1209 #endif /* !UFS_EXTATTR */
1210 	return (0);
1211 out:
1212 	if (fs != NULL) {
1213 		free(fs->fs_csp, M_UFSMNT);
1214 		free(fs->fs_si, M_UFSMNT);
1215 		free(fs, M_UFSMNT);
1216 	}
1217 	if (cp != NULL) {
1218 		g_topology_lock();
1219 		g_vfs_close(cp);
1220 		g_topology_unlock();
1221 	}
1222 	if (ump != NULL) {
1223 		mtx_destroy(UFS_MTX(ump));
1224 		sx_destroy(&ump->um_checkpath_lock);
1225 		if (mp->mnt_gjprovider != NULL) {
1226 			free(mp->mnt_gjprovider, M_UFSMNT);
1227 			mp->mnt_gjprovider = NULL;
1228 		}
1229 		MPASS(ump->um_softdep == NULL);
1230 		free(ump, M_UFSMNT);
1231 		mp->mnt_data = NULL;
1232 	}
1233 	BO_LOCK(&odevvp->v_bufobj);
1234 	odevvp->v_bufobj.bo_flag &= ~BO_NOBUFS;
1235 	BO_UNLOCK(&odevvp->v_bufobj);
1236 	atomic_store_rel_ptr((uintptr_t *)&dev->si_mountpt, 0);
1237 	vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
1238 	mntfs_freevp(devvp);
1239 	dev_rel(dev);
1240 	return (error);
1241 }
1242 
1243 /*
1244  * A read function for use by filesystem-layer routines.
1245  */
1246 static int
1247 ffs_use_bread(void *devfd, off_t loc, void **bufp, int size)
1248 {
1249 	struct buf *bp;
1250 	int error;
1251 
1252 	KASSERT(*bufp == NULL, ("ffs_use_bread: non-NULL *bufp %p\n", *bufp));
1253 	*bufp = malloc(size, M_UFSMNT, M_WAITOK);
1254 	if ((error = bread((struct vnode *)devfd, btodb(loc), size, NOCRED,
1255 	    &bp)) != 0)
1256 		return (error);
1257 	bcopy(bp->b_data, *bufp, size);
1258 	bp->b_flags |= B_INVAL | B_NOCACHE;
1259 	brelse(bp);
1260 	return (0);
1261 }
1262 
1263 static int bigcgs = 0;
1264 SYSCTL_INT(_debug, OID_AUTO, bigcgs, CTLFLAG_RW, &bigcgs, 0, "");
1265 
1266 /*
1267  * Sanity checks for loading old filesystem superblocks.
1268  * See ffs_oldfscompat_write below for unwound actions.
1269  *
1270  * XXX - Parts get retired eventually.
1271  * Unfortunately new bits get added.
1272  */
1273 static void
1274 ffs_oldfscompat_read(struct fs *fs,
1275 	struct ufsmount *ump,
1276 	ufs2_daddr_t sblockloc)
1277 {
1278 	off_t maxfilesize;
1279 
1280 	/*
1281 	 * If not yet done, update fs_flags location and value of fs_sblockloc.
1282 	 */
1283 	if ((fs->fs_old_flags & FS_FLAGS_UPDATED) == 0) {
1284 		fs->fs_flags = fs->fs_old_flags;
1285 		fs->fs_old_flags |= FS_FLAGS_UPDATED;
1286 		fs->fs_sblockloc = sblockloc;
1287 	}
1288 	/*
1289 	 * If not yet done, update UFS1 superblock with new wider fields.
1290 	 */
1291 	if (fs->fs_magic == FS_UFS1_MAGIC && fs->fs_maxbsize != fs->fs_bsize) {
1292 		fs->fs_maxbsize = fs->fs_bsize;
1293 		fs->fs_time = fs->fs_old_time;
1294 		fs->fs_size = fs->fs_old_size;
1295 		fs->fs_dsize = fs->fs_old_dsize;
1296 		fs->fs_csaddr = fs->fs_old_csaddr;
1297 		fs->fs_cstotal.cs_ndir = fs->fs_old_cstotal.cs_ndir;
1298 		fs->fs_cstotal.cs_nbfree = fs->fs_old_cstotal.cs_nbfree;
1299 		fs->fs_cstotal.cs_nifree = fs->fs_old_cstotal.cs_nifree;
1300 		fs->fs_cstotal.cs_nffree = fs->fs_old_cstotal.cs_nffree;
1301 	}
1302 	if (fs->fs_magic == FS_UFS1_MAGIC &&
1303 	    fs->fs_old_inodefmt < FS_44INODEFMT) {
1304 		fs->fs_maxfilesize = ((uint64_t)1 << 31) - 1;
1305 		fs->fs_qbmask = ~fs->fs_bmask;
1306 		fs->fs_qfmask = ~fs->fs_fmask;
1307 	}
1308 	if (fs->fs_magic == FS_UFS1_MAGIC) {
1309 		ump->um_savedmaxfilesize = fs->fs_maxfilesize;
1310 		maxfilesize = (uint64_t)0x80000000 * fs->fs_bsize - 1;
1311 		if (fs->fs_maxfilesize > maxfilesize)
1312 			fs->fs_maxfilesize = maxfilesize;
1313 	}
1314 	/* Compatibility for old filesystems */
1315 	if (fs->fs_avgfilesize <= 0)
1316 		fs->fs_avgfilesize = AVFILESIZ;
1317 	if (fs->fs_avgfpdir <= 0)
1318 		fs->fs_avgfpdir = AFPDIR;
1319 	if (bigcgs) {
1320 		fs->fs_save_cgsize = fs->fs_cgsize;
1321 		fs->fs_cgsize = fs->fs_bsize;
1322 	}
1323 }
1324 
1325 /*
1326  * Unwinding superblock updates for old filesystems.
1327  * See ffs_oldfscompat_read above for details.
1328  *
1329  * XXX - Parts get retired eventually.
1330  * Unfortunately new bits get added.
1331  */
1332 void
1333 ffs_oldfscompat_write(struct fs *fs, struct ufsmount *ump)
1334 {
1335 
1336 	/*
1337 	 * Copy back UFS2 updated fields that UFS1 inspects.
1338 	 */
1339 	if (fs->fs_magic == FS_UFS1_MAGIC) {
1340 		fs->fs_old_time = fs->fs_time;
1341 		fs->fs_old_cstotal.cs_ndir = fs->fs_cstotal.cs_ndir;
1342 		fs->fs_old_cstotal.cs_nbfree = fs->fs_cstotal.cs_nbfree;
1343 		fs->fs_old_cstotal.cs_nifree = fs->fs_cstotal.cs_nifree;
1344 		fs->fs_old_cstotal.cs_nffree = fs->fs_cstotal.cs_nffree;
1345 		fs->fs_maxfilesize = ump->um_savedmaxfilesize;
1346 	}
1347 	if (bigcgs) {
1348 		fs->fs_cgsize = fs->fs_save_cgsize;
1349 		fs->fs_save_cgsize = 0;
1350 	}
1351 }
1352 
1353 /*
1354  * unmount system call
1355  */
1356 static int
1357 ffs_unmount(struct mount *mp, int mntflags)
1358 {
1359 	struct thread *td;
1360 	struct ufsmount *ump = VFSTOUFS(mp);
1361 	struct fs *fs;
1362 	int error, flags, susp;
1363 #ifdef UFS_EXTATTR
1364 	int e_restart;
1365 #endif
1366 
1367 	flags = 0;
1368 	td = curthread;
1369 	fs = ump->um_fs;
1370 	if (mntflags & MNT_FORCE)
1371 		flags |= FORCECLOSE;
1372 	susp = fs->fs_ronly == 0;
1373 #ifdef UFS_EXTATTR
1374 	if ((error = ufs_extattr_stop(mp, td))) {
1375 		if (error != EOPNOTSUPP)
1376 			printf("WARNING: unmount %s: ufs_extattr_stop "
1377 			    "returned errno %d\n", mp->mnt_stat.f_mntonname,
1378 			    error);
1379 		e_restart = 0;
1380 	} else {
1381 		ufs_extattr_uepm_destroy(&ump->um_extattr);
1382 		e_restart = 1;
1383 	}
1384 #endif
1385 	if (susp) {
1386 		error = vfs_write_suspend_umnt(mp);
1387 		if (error != 0)
1388 			goto fail1;
1389 	}
1390 	if (MOUNTEDSOFTDEP(mp))
1391 		error = softdep_flushfiles(mp, flags, td);
1392 	else
1393 		error = ffs_flushfiles(mp, flags, td);
1394 	if (error != 0 && !ffs_fsfail_cleanup(ump, error))
1395 		goto fail;
1396 
1397 	UFS_LOCK(ump);
1398 	if (fs->fs_pendingblocks != 0 || fs->fs_pendinginodes != 0) {
1399 		printf("WARNING: unmount %s: pending error: blocks %jd "
1400 		    "files %d\n", fs->fs_fsmnt, (intmax_t)fs->fs_pendingblocks,
1401 		    fs->fs_pendinginodes);
1402 		fs->fs_pendingblocks = 0;
1403 		fs->fs_pendinginodes = 0;
1404 	}
1405 	UFS_UNLOCK(ump);
1406 	if (MOUNTEDSOFTDEP(mp))
1407 		softdep_unmount(mp);
1408 	MPASS(ump->um_softdep == NULL);
1409 	if (fs->fs_ronly == 0) {
1410 		fs->fs_clean = fs->fs_flags & (FS_UNCLEAN|FS_NEEDSFSCK) ? 0 : 1;
1411 		error = ffs_sbupdate(ump, MNT_WAIT, 0);
1412 		if (ffs_fsfail_cleanup(ump, error))
1413 			error = 0;
1414 		if (error != 0 && !ffs_fsfail_cleanup(ump, error)) {
1415 			fs->fs_clean = 0;
1416 			goto fail;
1417 		}
1418 	}
1419 	if (susp)
1420 		vfs_write_resume(mp, VR_START_WRITE);
1421 	if (ump->um_trim_tq != NULL) {
1422 		MPASS(ump->um_trim_inflight == 0);
1423 		taskqueue_free(ump->um_trim_tq);
1424 		free (ump->um_trimhash, M_TRIM);
1425 	}
1426 	vn_lock(ump->um_devvp, LK_EXCLUSIVE | LK_RETRY);
1427 	g_topology_lock();
1428 	g_vfs_close(ump->um_cp);
1429 	g_topology_unlock();
1430 	BO_LOCK(&ump->um_odevvp->v_bufobj);
1431 	ump->um_odevvp->v_bufobj.bo_flag &= ~BO_NOBUFS;
1432 	BO_UNLOCK(&ump->um_odevvp->v_bufobj);
1433 	atomic_store_rel_ptr((uintptr_t *)&ump->um_dev->si_mountpt, 0);
1434 	mntfs_freevp(ump->um_devvp);
1435 	vrele(ump->um_odevvp);
1436 	dev_rel(ump->um_dev);
1437 	mtx_destroy(UFS_MTX(ump));
1438 	sx_destroy(&ump->um_checkpath_lock);
1439 	if (mp->mnt_gjprovider != NULL) {
1440 		free(mp->mnt_gjprovider, M_UFSMNT);
1441 		mp->mnt_gjprovider = NULL;
1442 	}
1443 	free(fs->fs_csp, M_UFSMNT);
1444 	free(fs->fs_si, M_UFSMNT);
1445 	free(fs, M_UFSMNT);
1446 	free(ump, M_UFSMNT);
1447 	mp->mnt_data = NULL;
1448 	MNT_ILOCK(mp);
1449 	mp->mnt_flag &= ~MNT_LOCAL;
1450 	MNT_IUNLOCK(mp);
1451 	if (td->td_su == mp) {
1452 		td->td_su = NULL;
1453 		vfs_rel(mp);
1454 	}
1455 	return (error);
1456 
1457 fail:
1458 	if (susp)
1459 		vfs_write_resume(mp, VR_START_WRITE);
1460 fail1:
1461 #ifdef UFS_EXTATTR
1462 	if (e_restart) {
1463 		ufs_extattr_uepm_init(&ump->um_extattr);
1464 #ifdef UFS_EXTATTR_AUTOSTART
1465 		(void) ufs_extattr_autostart(mp, td);
1466 #endif
1467 	}
1468 #endif
1469 
1470 	return (error);
1471 }
1472 
1473 /*
1474  * Flush out all the files in a filesystem.
1475  */
1476 int
1477 ffs_flushfiles(struct mount *mp, int flags, struct thread *td)
1478 {
1479 	struct ufsmount *ump;
1480 	int qerror, error;
1481 
1482 	ump = VFSTOUFS(mp);
1483 	qerror = 0;
1484 #ifdef QUOTA
1485 	if (mp->mnt_flag & MNT_QUOTA) {
1486 		int i;
1487 		error = vflush(mp, 0, SKIPSYSTEM|flags, td);
1488 		if (error)
1489 			return (error);
1490 		for (i = 0; i < MAXQUOTAS; i++) {
1491 			error = quotaoff(td, mp, i);
1492 			if (error != 0) {
1493 				if ((flags & EARLYFLUSH) == 0)
1494 					return (error);
1495 				else
1496 					qerror = error;
1497 			}
1498 		}
1499 
1500 		/*
1501 		 * Here we fall through to vflush again to ensure that
1502 		 * we have gotten rid of all the system vnodes, unless
1503 		 * quotas must not be closed.
1504 		 */
1505 	}
1506 #endif
1507 	/* devvp is not locked there */
1508 	if (ump->um_devvp->v_vflag & VV_COPYONWRITE) {
1509 		if ((error = vflush(mp, 0, SKIPSYSTEM | flags, td)) != 0)
1510 			return (error);
1511 		ffs_snapshot_unmount(mp);
1512 		flags |= FORCECLOSE;
1513 		/*
1514 		 * Here we fall through to vflush again to ensure
1515 		 * that we have gotten rid of all the system vnodes.
1516 		 */
1517 	}
1518 
1519 	/*
1520 	 * Do not close system files if quotas were not closed, to be
1521 	 * able to sync the remaining dquots.  The freeblks softupdate
1522 	 * workitems might hold a reference on a dquot, preventing
1523 	 * quotaoff() from completing.  Next round of
1524 	 * softdep_flushworklist() iteration should process the
1525 	 * blockers, allowing the next run of quotaoff() to finally
1526 	 * flush held dquots.
1527 	 *
1528 	 * Otherwise, flush all the files.
1529 	 */
1530 	if (qerror == 0 && (error = vflush(mp, 0, flags, td)) != 0)
1531 		return (error);
1532 
1533 	/*
1534 	 * If this is a forcible unmount and there were any files that
1535 	 * were unlinked but still open, then vflush() will have
1536 	 * truncated and freed those files, which might have started
1537 	 * some trim work.  Wait here for any trims to complete
1538 	 * and process the blkfrees which follow the trims.
1539 	 * This may create more dirty devvp buffers and softdep deps.
1540 	 */
1541 	if (ump->um_trim_tq != NULL) {
1542 		while (ump->um_trim_inflight != 0)
1543 			pause("ufsutr", hz);
1544 		taskqueue_drain_all(ump->um_trim_tq);
1545 	}
1546 
1547 	/*
1548 	 * Flush filesystem metadata.
1549 	 */
1550 	vn_lock(ump->um_devvp, LK_EXCLUSIVE | LK_RETRY);
1551 	error = VOP_FSYNC(ump->um_devvp, MNT_WAIT, td);
1552 	VOP_UNLOCK(ump->um_devvp);
1553 	return (error);
1554 }
1555 
1556 /*
1557  * Get filesystem statistics.
1558  */
1559 static int
1560 ffs_statfs(struct mount *mp, struct statfs *sbp)
1561 {
1562 	struct ufsmount *ump;
1563 	struct fs *fs;
1564 
1565 	ump = VFSTOUFS(mp);
1566 	fs = ump->um_fs;
1567 	if (fs->fs_magic != FS_UFS1_MAGIC && fs->fs_magic != FS_UFS2_MAGIC)
1568 		panic("ffs_statfs");
1569 	sbp->f_version = STATFS_VERSION;
1570 	sbp->f_bsize = fs->fs_fsize;
1571 	sbp->f_iosize = fs->fs_bsize;
1572 	sbp->f_blocks = fs->fs_dsize;
1573 	UFS_LOCK(ump);
1574 	sbp->f_bfree = fs->fs_cstotal.cs_nbfree * fs->fs_frag +
1575 	    fs->fs_cstotal.cs_nffree + dbtofsb(fs, fs->fs_pendingblocks);
1576 	sbp->f_bavail = freespace(fs, fs->fs_minfree) +
1577 	    dbtofsb(fs, fs->fs_pendingblocks);
1578 	sbp->f_files =  fs->fs_ncg * fs->fs_ipg - UFS_ROOTINO;
1579 	sbp->f_ffree = fs->fs_cstotal.cs_nifree + fs->fs_pendinginodes;
1580 	UFS_UNLOCK(ump);
1581 	sbp->f_namemax = UFS_MAXNAMLEN;
1582 	return (0);
1583 }
1584 
1585 static bool
1586 sync_doupdate(struct inode *ip)
1587 {
1588 
1589 	return ((ip->i_flag & (IN_ACCESS | IN_CHANGE | IN_MODIFIED |
1590 	    IN_UPDATE)) != 0);
1591 }
1592 
1593 static int
1594 ffs_sync_lazy_filter(struct vnode *vp, void *arg __unused)
1595 {
1596 	struct inode *ip;
1597 
1598 	/*
1599 	 * Flags are safe to access because ->v_data invalidation
1600 	 * is held off by listmtx.
1601 	 */
1602 	if (vp->v_type == VNON)
1603 		return (false);
1604 	ip = VTOI(vp);
1605 	if (!sync_doupdate(ip) && (vp->v_iflag & VI_OWEINACT) == 0)
1606 		return (false);
1607 	return (true);
1608 }
1609 
1610 /*
1611  * For a lazy sync, we only care about access times, quotas and the
1612  * superblock.  Other filesystem changes are already converted to
1613  * cylinder group blocks or inode blocks updates and are written to
1614  * disk by syncer.
1615  */
1616 static int
1617 ffs_sync_lazy(struct mount *mp)
1618 {
1619 	struct vnode *mvp, *vp;
1620 	struct inode *ip;
1621 	int allerror, error;
1622 
1623 	allerror = 0;
1624 	if ((mp->mnt_flag & MNT_NOATIME) != 0) {
1625 #ifdef QUOTA
1626 		qsync(mp);
1627 #endif
1628 		goto sbupdate;
1629 	}
1630 	MNT_VNODE_FOREACH_LAZY(vp, mp, mvp, ffs_sync_lazy_filter, NULL) {
1631 		if (vp->v_type == VNON) {
1632 			VI_UNLOCK(vp);
1633 			continue;
1634 		}
1635 		ip = VTOI(vp);
1636 
1637 		/*
1638 		 * The IN_ACCESS flag is converted to IN_MODIFIED by
1639 		 * ufs_close() and ufs_getattr() by the calls to
1640 		 * ufs_itimes_locked(), without subsequent UFS_UPDATE().
1641 		 * Test also all the other timestamp flags too, to pick up
1642 		 * any other cases that could be missed.
1643 		 */
1644 		if (!sync_doupdate(ip) && (vp->v_iflag & VI_OWEINACT) == 0) {
1645 			VI_UNLOCK(vp);
1646 			continue;
1647 		}
1648 		if ((error = vget(vp, LK_EXCLUSIVE | LK_NOWAIT | LK_INTERLOCK)) != 0)
1649 			continue;
1650 #ifdef QUOTA
1651 		qsyncvp(vp);
1652 #endif
1653 		if (sync_doupdate(ip))
1654 			error = ffs_update(vp, 0);
1655 		if (error != 0)
1656 			allerror = error;
1657 		vput(vp);
1658 	}
1659 sbupdate:
1660 	if (VFSTOUFS(mp)->um_fs->fs_fmod != 0 &&
1661 	    (error = ffs_sbupdate(VFSTOUFS(mp), MNT_LAZY, 0)) != 0)
1662 		allerror = error;
1663 	return (allerror);
1664 }
1665 
1666 /*
1667  * Go through the disk queues to initiate sandbagged IO;
1668  * go through the inodes to write those that have been modified;
1669  * initiate the writing of the super block if it has been modified.
1670  *
1671  * Note: we are always called with the filesystem marked busy using
1672  * vfs_busy().
1673  */
1674 static int
1675 ffs_sync(struct mount *mp, int waitfor)
1676 {
1677 	struct vnode *mvp, *vp, *devvp;
1678 	struct thread *td;
1679 	struct inode *ip;
1680 	struct ufsmount *ump = VFSTOUFS(mp);
1681 	struct fs *fs;
1682 	int error, count, lockreq, allerror = 0;
1683 	int suspend;
1684 	int suspended;
1685 	int secondary_writes;
1686 	int secondary_accwrites;
1687 	int softdep_deps;
1688 	int softdep_accdeps;
1689 	struct bufobj *bo;
1690 
1691 	suspend = 0;
1692 	suspended = 0;
1693 	td = curthread;
1694 	fs = ump->um_fs;
1695 	if (fs->fs_fmod != 0 && fs->fs_ronly != 0)
1696 		panic("%s: ffs_sync: modification on read-only filesystem",
1697 		    fs->fs_fsmnt);
1698 	if (waitfor == MNT_LAZY) {
1699 		if (!rebooting)
1700 			return (ffs_sync_lazy(mp));
1701 		waitfor = MNT_NOWAIT;
1702 	}
1703 
1704 	/*
1705 	 * Write back each (modified) inode.
1706 	 */
1707 	lockreq = LK_EXCLUSIVE | LK_NOWAIT;
1708 	if (waitfor == MNT_SUSPEND) {
1709 		suspend = 1;
1710 		waitfor = MNT_WAIT;
1711 	}
1712 	if (waitfor == MNT_WAIT)
1713 		lockreq = LK_EXCLUSIVE;
1714 	lockreq |= LK_INTERLOCK | LK_SLEEPFAIL;
1715 loop:
1716 	/* Grab snapshot of secondary write counts */
1717 	MNT_ILOCK(mp);
1718 	secondary_writes = mp->mnt_secondary_writes;
1719 	secondary_accwrites = mp->mnt_secondary_accwrites;
1720 	MNT_IUNLOCK(mp);
1721 
1722 	/* Grab snapshot of softdep dependency counts */
1723 	softdep_get_depcounts(mp, &softdep_deps, &softdep_accdeps);
1724 
1725 	MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
1726 		/*
1727 		 * Depend on the vnode interlock to keep things stable enough
1728 		 * for a quick test.  Since there might be hundreds of
1729 		 * thousands of vnodes, we cannot afford even a subroutine
1730 		 * call unless there's a good chance that we have work to do.
1731 		 */
1732 		if (vp->v_type == VNON) {
1733 			VI_UNLOCK(vp);
1734 			continue;
1735 		}
1736 		ip = VTOI(vp);
1737 		if ((ip->i_flag &
1738 		    (IN_ACCESS | IN_CHANGE | IN_MODIFIED | IN_UPDATE)) == 0 &&
1739 		    vp->v_bufobj.bo_dirty.bv_cnt == 0) {
1740 			VI_UNLOCK(vp);
1741 			continue;
1742 		}
1743 		if ((error = vget(vp, lockreq)) != 0) {
1744 			if (error == ENOENT || error == ENOLCK) {
1745 				MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
1746 				goto loop;
1747 			}
1748 			continue;
1749 		}
1750 #ifdef QUOTA
1751 		qsyncvp(vp);
1752 #endif
1753 		for (;;) {
1754 			error = ffs_syncvnode(vp, waitfor, 0);
1755 			if (error == ERELOOKUP)
1756 				continue;
1757 			if (error != 0)
1758 				allerror = error;
1759 			break;
1760 		}
1761 		vput(vp);
1762 	}
1763 	/*
1764 	 * Force stale filesystem control information to be flushed.
1765 	 */
1766 	if (waitfor == MNT_WAIT || rebooting) {
1767 		if ((error = softdep_flushworklist(ump->um_mountp, &count, td)))
1768 			allerror = error;
1769 		if (ffs_fsfail_cleanup(ump, allerror))
1770 			allerror = 0;
1771 		/* Flushed work items may create new vnodes to clean */
1772 		if (allerror == 0 && count)
1773 			goto loop;
1774 	}
1775 
1776 	devvp = ump->um_devvp;
1777 	bo = &devvp->v_bufobj;
1778 	BO_LOCK(bo);
1779 	if (bo->bo_numoutput > 0 || bo->bo_dirty.bv_cnt > 0) {
1780 		BO_UNLOCK(bo);
1781 		vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
1782 		error = VOP_FSYNC(devvp, waitfor, td);
1783 		VOP_UNLOCK(devvp);
1784 		if (MOUNTEDSOFTDEP(mp) && (error == 0 || error == EAGAIN))
1785 			error = ffs_sbupdate(ump, waitfor, 0);
1786 		if (error != 0)
1787 			allerror = error;
1788 		if (ffs_fsfail_cleanup(ump, allerror))
1789 			allerror = 0;
1790 		if (allerror == 0 && waitfor == MNT_WAIT)
1791 			goto loop;
1792 	} else if (suspend != 0) {
1793 		if (softdep_check_suspend(mp,
1794 					  devvp,
1795 					  softdep_deps,
1796 					  softdep_accdeps,
1797 					  secondary_writes,
1798 					  secondary_accwrites) != 0) {
1799 			MNT_IUNLOCK(mp);
1800 			goto loop;	/* More work needed */
1801 		}
1802 		mtx_assert(MNT_MTX(mp), MA_OWNED);
1803 		mp->mnt_kern_flag |= MNTK_SUSPEND2 | MNTK_SUSPENDED;
1804 		MNT_IUNLOCK(mp);
1805 		suspended = 1;
1806 	} else
1807 		BO_UNLOCK(bo);
1808 	/*
1809 	 * Write back modified superblock.
1810 	 */
1811 	if (fs->fs_fmod != 0 &&
1812 	    (error = ffs_sbupdate(ump, waitfor, suspended)) != 0)
1813 		allerror = error;
1814 	if (ffs_fsfail_cleanup(ump, allerror))
1815 		allerror = 0;
1816 	return (allerror);
1817 }
1818 
1819 int
1820 ffs_vget(struct mount *mp, ino_t ino, int flags, struct vnode **vpp)
1821 {
1822 	return (ffs_vgetf(mp, ino, flags, vpp, 0));
1823 }
1824 
1825 int
1826 ffs_vgetf(struct mount *mp,
1827 	ino_t ino,
1828 	int flags,
1829 	struct vnode **vpp,
1830 	int ffs_flags)
1831 {
1832 	struct fs *fs;
1833 	struct inode *ip;
1834 	struct ufsmount *ump;
1835 	struct buf *bp;
1836 	struct vnode *vp;
1837 	daddr_t dbn;
1838 	int error;
1839 
1840 	MPASS((ffs_flags & (FFSV_REPLACE | FFSV_REPLACE_DOOMED)) == 0 ||
1841 	    (flags & LK_EXCLUSIVE) != 0);
1842 
1843 	error = vfs_hash_get(mp, ino, flags, curthread, vpp, NULL, NULL);
1844 	if (error != 0)
1845 		return (error);
1846 	if (*vpp != NULL) {
1847 		if ((ffs_flags & FFSV_REPLACE) == 0 ||
1848 		    ((ffs_flags & FFSV_REPLACE_DOOMED) == 0 ||
1849 		    !VN_IS_DOOMED(*vpp)))
1850 			return (0);
1851 		vgone(*vpp);
1852 		vput(*vpp);
1853 	}
1854 
1855 	/*
1856 	 * We must promote to an exclusive lock for vnode creation.  This
1857 	 * can happen if lookup is passed LOCKSHARED.
1858 	 */
1859 	if ((flags & LK_TYPE_MASK) == LK_SHARED) {
1860 		flags &= ~LK_TYPE_MASK;
1861 		flags |= LK_EXCLUSIVE;
1862 	}
1863 
1864 	/*
1865 	 * We do not lock vnode creation as it is believed to be too
1866 	 * expensive for such rare case as simultaneous creation of vnode
1867 	 * for same ino by different processes. We just allow them to race
1868 	 * and check later to decide who wins. Let the race begin!
1869 	 */
1870 
1871 	ump = VFSTOUFS(mp);
1872 	fs = ump->um_fs;
1873 	ip = uma_zalloc_smr(uma_inode, M_WAITOK | M_ZERO);
1874 
1875 	/* Allocate a new vnode/inode. */
1876 	error = getnewvnode("ufs", mp, fs->fs_magic == FS_UFS1_MAGIC ?
1877 	    &ffs_vnodeops1 : &ffs_vnodeops2, &vp);
1878 	if (error) {
1879 		*vpp = NULL;
1880 		uma_zfree_smr(uma_inode, ip);
1881 		return (error);
1882 	}
1883 	/*
1884 	 * FFS supports recursive locking.
1885 	 */
1886 	lockmgr(vp->v_vnlock, LK_EXCLUSIVE | LK_NOWITNESS, NULL);
1887 	VN_LOCK_AREC(vp);
1888 	vp->v_data = ip;
1889 	vp->v_bufobj.bo_bsize = fs->fs_bsize;
1890 	ip->i_vnode = vp;
1891 	ip->i_ump = ump;
1892 	ip->i_number = ino;
1893 	ip->i_ea_refs = 0;
1894 	ip->i_nextclustercg = -1;
1895 	ip->i_flag = fs->fs_magic == FS_UFS1_MAGIC ? 0 : IN_UFS2;
1896 	ip->i_mode = 0; /* ensure error cases below throw away vnode */
1897 	cluster_init_vn(&ip->i_clusterw);
1898 #ifdef DIAGNOSTIC
1899 	ufs_init_trackers(ip);
1900 #endif
1901 #ifdef QUOTA
1902 	{
1903 		int i;
1904 		for (i = 0; i < MAXQUOTAS; i++)
1905 			ip->i_dquot[i] = NODQUOT;
1906 	}
1907 #endif
1908 
1909 	if (ffs_flags & FFSV_FORCEINSMQ)
1910 		vp->v_vflag |= VV_FORCEINSMQ;
1911 	error = insmntque(vp, mp);
1912 	if (error != 0) {
1913 		uma_zfree_smr(uma_inode, ip);
1914 		*vpp = NULL;
1915 		return (error);
1916 	}
1917 	vp->v_vflag &= ~VV_FORCEINSMQ;
1918 	error = vfs_hash_insert(vp, ino, flags, curthread, vpp, NULL, NULL);
1919 	if (error != 0)
1920 		return (error);
1921 	if (*vpp != NULL) {
1922 		/*
1923 		 * Calls from ffs_valloc() (i.e. FFSV_REPLACE set)
1924 		 * operate on empty inode, which must not be found by
1925 		 * other threads until fully filled.  Vnode for empty
1926 		 * inode must be not re-inserted on the hash by other
1927 		 * thread, after removal by us at the beginning.
1928 		 */
1929 		MPASS((ffs_flags & FFSV_REPLACE) == 0);
1930 		return (0);
1931 	}
1932 
1933 	/* Read in the disk contents for the inode, copy into the inode. */
1934 	dbn = fsbtodb(fs, ino_to_fsba(fs, ino));
1935 	error = ffs_breadz(ump, ump->um_devvp, dbn, dbn, (int)fs->fs_bsize,
1936 	    NULL, NULL, 0, NOCRED, 0, NULL, &bp);
1937 	if (error != 0) {
1938 		/*
1939 		 * The inode does not contain anything useful, so it would
1940 		 * be misleading to leave it on its hash chain. With mode
1941 		 * still zero, it will be unlinked and returned to the free
1942 		 * list by vput().
1943 		 */
1944 		vgone(vp);
1945 		vput(vp);
1946 		*vpp = NULL;
1947 		return (error);
1948 	}
1949 	if (I_IS_UFS1(ip))
1950 		ip->i_din1 = uma_zalloc(uma_ufs1, M_WAITOK);
1951 	else
1952 		ip->i_din2 = uma_zalloc(uma_ufs2, M_WAITOK);
1953 	if ((error = ffs_load_inode(bp, ip, fs, ino)) != 0) {
1954 		bqrelse(bp);
1955 		vgone(vp);
1956 		vput(vp);
1957 		*vpp = NULL;
1958 		return (error);
1959 	}
1960 	if (DOINGSOFTDEP(vp) && (!fs->fs_ronly ||
1961 	    (ffs_flags & FFSV_FORCEINODEDEP) != 0))
1962 		softdep_load_inodeblock(ip);
1963 	else
1964 		ip->i_effnlink = ip->i_nlink;
1965 	bqrelse(bp);
1966 
1967 	/*
1968 	 * Initialize the vnode from the inode, check for aliases.
1969 	 * Note that the underlying vnode may have changed.
1970 	 */
1971 	error = ufs_vinit(mp, I_IS_UFS1(ip) ? &ffs_fifoops1 : &ffs_fifoops2,
1972 	    &vp);
1973 	if (error) {
1974 		vgone(vp);
1975 		vput(vp);
1976 		*vpp = NULL;
1977 		return (error);
1978 	}
1979 
1980 	/*
1981 	 * Finish inode initialization.
1982 	 */
1983 	if (vp->v_type != VFIFO) {
1984 		/* FFS supports shared locking for all files except fifos. */
1985 		VN_LOCK_ASHARE(vp);
1986 	}
1987 
1988 	/*
1989 	 * Set up a generation number for this inode if it does not
1990 	 * already have one. This should only happen on old filesystems.
1991 	 */
1992 	if (ip->i_gen == 0) {
1993 		while (ip->i_gen == 0)
1994 			ip->i_gen = arc4random();
1995 		if ((vp->v_mount->mnt_flag & MNT_RDONLY) == 0) {
1996 			UFS_INODE_SET_FLAG(ip, IN_MODIFIED);
1997 			DIP_SET(ip, i_gen, ip->i_gen);
1998 		}
1999 	}
2000 #ifdef MAC
2001 	if ((mp->mnt_flag & MNT_MULTILABEL) && ip->i_mode) {
2002 		/*
2003 		 * If this vnode is already allocated, and we're running
2004 		 * multi-label, attempt to perform a label association
2005 		 * from the extended attributes on the inode.
2006 		 */
2007 		error = mac_vnode_associate_extattr(mp, vp);
2008 		if (error) {
2009 			/* ufs_inactive will release ip->i_devvp ref. */
2010 			vgone(vp);
2011 			vput(vp);
2012 			*vpp = NULL;
2013 			return (error);
2014 		}
2015 	}
2016 #endif
2017 
2018 	*vpp = vp;
2019 	return (0);
2020 }
2021 
2022 /*
2023  * File handle to vnode
2024  *
2025  * Have to be really careful about stale file handles:
2026  * - check that the inode number is valid
2027  * - for UFS2 check that the inode number is initialized
2028  * - call ffs_vget() to get the locked inode
2029  * - check for an unallocated inode (i_mode == 0)
2030  * - check that the given client host has export rights and return
2031  *   those rights via. exflagsp and credanonp
2032  */
2033 static int
2034 ffs_fhtovp(struct mount *mp, struct fid *fhp, int flags, struct vnode **vpp)
2035 {
2036 	struct ufid *ufhp;
2037 
2038 	ufhp = (struct ufid *)fhp;
2039 	return (ffs_inotovp(mp, ufhp->ufid_ino, ufhp->ufid_gen, flags,
2040 	    vpp, 0));
2041 }
2042 
2043 int
2044 ffs_inotovp(struct mount *mp,
2045 	ino_t ino,
2046 	u_int64_t gen,
2047 	int lflags,
2048 	struct vnode **vpp,
2049 	int ffs_flags)
2050 {
2051 	struct ufsmount *ump;
2052 	struct vnode *nvp;
2053 	struct inode *ip;
2054 	struct fs *fs;
2055 	struct cg *cgp;
2056 	struct buf *bp;
2057 	u_int cg;
2058 	int error;
2059 
2060 	ump = VFSTOUFS(mp);
2061 	fs = ump->um_fs;
2062 	*vpp = NULL;
2063 
2064 	if (ino < UFS_ROOTINO || ino >= fs->fs_ncg * fs->fs_ipg)
2065 		return (ESTALE);
2066 
2067 	/*
2068 	 * Need to check if inode is initialized because UFS2 does lazy
2069 	 * initialization and nfs_fhtovp can offer arbitrary inode numbers.
2070 	 */
2071 	if (fs->fs_magic == FS_UFS2_MAGIC) {
2072 		cg = ino_to_cg(fs, ino);
2073 		error = ffs_getcg(fs, ump->um_devvp, cg, 0, &bp, &cgp);
2074 		if (error != 0)
2075 			return (error);
2076 		if (ino >= cg * fs->fs_ipg + cgp->cg_initediblk) {
2077 			brelse(bp);
2078 			return (ESTALE);
2079 		}
2080 		brelse(bp);
2081 	}
2082 
2083 	error = ffs_vgetf(mp, ino, lflags, &nvp, ffs_flags);
2084 	if (error != 0)
2085 		return (error);
2086 
2087 	ip = VTOI(nvp);
2088 	if (ip->i_mode == 0 || ip->i_gen != gen || ip->i_effnlink <= 0) {
2089 		if (ip->i_mode == 0)
2090 			vgone(nvp);
2091 		vput(nvp);
2092 		return (ESTALE);
2093 	}
2094 
2095 	vnode_create_vobject(nvp, DIP(ip, i_size), curthread);
2096 	*vpp = nvp;
2097 	return (0);
2098 }
2099 
2100 /*
2101  * Initialize the filesystem.
2102  */
2103 static int
2104 ffs_init(struct vfsconf *vfsp)
2105 {
2106 
2107 	ffs_susp_initialize();
2108 	softdep_initialize();
2109 	return (ufs_init(vfsp));
2110 }
2111 
2112 /*
2113  * Undo the work of ffs_init().
2114  */
2115 static int
2116 ffs_uninit(struct vfsconf *vfsp)
2117 {
2118 	int ret;
2119 
2120 	ret = ufs_uninit(vfsp);
2121 	softdep_uninitialize();
2122 	ffs_susp_uninitialize();
2123 	taskqueue_drain_all(taskqueue_thread);
2124 	return (ret);
2125 }
2126 
2127 /*
2128  * Structure used to pass information from ffs_sbupdate to its
2129  * helper routine ffs_use_bwrite.
2130  */
2131 struct devfd {
2132 	struct ufsmount	*ump;
2133 	struct buf	*sbbp;
2134 	int		 waitfor;
2135 	int		 suspended;
2136 	int		 error;
2137 };
2138 
2139 /*
2140  * Write a superblock and associated information back to disk.
2141  */
2142 int
2143 ffs_sbupdate(struct ufsmount *ump, int waitfor, int suspended)
2144 {
2145 	struct fs *fs;
2146 	struct buf *sbbp;
2147 	struct devfd devfd;
2148 
2149 	fs = ump->um_fs;
2150 	if (fs->fs_ronly == 1 &&
2151 	    (ump->um_mountp->mnt_flag & (MNT_RDONLY | MNT_UPDATE)) !=
2152 	    (MNT_RDONLY | MNT_UPDATE))
2153 		panic("ffs_sbupdate: write read-only filesystem");
2154 	/*
2155 	 * We use the superblock's buf to serialize calls to ffs_sbupdate().
2156 	 */
2157 	sbbp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
2158 	    (int)fs->fs_sbsize, 0, 0, 0);
2159 	/*
2160 	 * Initialize info needed for write function.
2161 	 */
2162 	devfd.ump = ump;
2163 	devfd.sbbp = sbbp;
2164 	devfd.waitfor = waitfor;
2165 	devfd.suspended = suspended;
2166 	devfd.error = 0;
2167 	return (ffs_sbput(&devfd, fs, fs->fs_sblockloc, ffs_use_bwrite));
2168 }
2169 
2170 /*
2171  * Write function for use by filesystem-layer routines.
2172  */
2173 static int
2174 ffs_use_bwrite(void *devfd, off_t loc, void *buf, int size)
2175 {
2176 	struct devfd *devfdp;
2177 	struct ufsmount *ump;
2178 	struct buf *bp;
2179 	struct fs *fs;
2180 	int error;
2181 
2182 	devfdp = devfd;
2183 	ump = devfdp->ump;
2184 	fs = ump->um_fs;
2185 	/*
2186 	 * Writing the superblock summary information.
2187 	 */
2188 	if (loc != fs->fs_sblockloc) {
2189 		bp = getblk(ump->um_devvp, btodb(loc), size, 0, 0, 0);
2190 		bcopy(buf, bp->b_data, (u_int)size);
2191 		if (devfdp->suspended)
2192 			bp->b_flags |= B_VALIDSUSPWRT;
2193 		if (devfdp->waitfor != MNT_WAIT)
2194 			bawrite(bp);
2195 		else if ((error = bwrite(bp)) != 0)
2196 			devfdp->error = error;
2197 		return (0);
2198 	}
2199 	/*
2200 	 * Writing the superblock itself. We need to do special checks for it.
2201 	 */
2202 	bp = devfdp->sbbp;
2203 	if (ffs_fsfail_cleanup(ump, devfdp->error))
2204 		devfdp->error = 0;
2205 	if (devfdp->error != 0) {
2206 		brelse(bp);
2207 		return (devfdp->error);
2208 	}
2209 	if (fs->fs_magic == FS_UFS1_MAGIC && fs->fs_sblockloc != SBLOCK_UFS1 &&
2210 	    (fs->fs_old_flags & FS_FLAGS_UPDATED) == 0) {
2211 		printf("WARNING: %s: correcting fs_sblockloc from %jd to %d\n",
2212 		    fs->fs_fsmnt, fs->fs_sblockloc, SBLOCK_UFS1);
2213 		fs->fs_sblockloc = SBLOCK_UFS1;
2214 	}
2215 	if (fs->fs_magic == FS_UFS2_MAGIC && fs->fs_sblockloc != SBLOCK_UFS2 &&
2216 	    (fs->fs_old_flags & FS_FLAGS_UPDATED) == 0) {
2217 		printf("WARNING: %s: correcting fs_sblockloc from %jd to %d\n",
2218 		    fs->fs_fsmnt, fs->fs_sblockloc, SBLOCK_UFS2);
2219 		fs->fs_sblockloc = SBLOCK_UFS2;
2220 	}
2221 	if (MOUNTEDSOFTDEP(ump->um_mountp))
2222 		softdep_setup_sbupdate(ump, (struct fs *)bp->b_data, bp);
2223 	UFS_LOCK(ump);
2224 	bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
2225 	UFS_UNLOCK(ump);
2226 	fs = (struct fs *)bp->b_data;
2227 	fs->fs_fmod = 0;
2228 	ffs_oldfscompat_write(fs, ump);
2229 	fs->fs_si = NULL;
2230 	/* Recalculate the superblock hash */
2231 	fs->fs_ckhash = ffs_calc_sbhash(fs);
2232 	if (devfdp->suspended)
2233 		bp->b_flags |= B_VALIDSUSPWRT;
2234 	if (devfdp->waitfor != MNT_WAIT)
2235 		bawrite(bp);
2236 	else if ((error = bwrite(bp)) != 0)
2237 		devfdp->error = error;
2238 	return (devfdp->error);
2239 }
2240 
2241 static int
2242 ffs_extattrctl(struct mount *mp, int cmd, struct vnode *filename_vp,
2243 	int attrnamespace, const char *attrname)
2244 {
2245 
2246 #ifdef UFS_EXTATTR
2247 	return (ufs_extattrctl(mp, cmd, filename_vp, attrnamespace,
2248 	    attrname));
2249 #else
2250 	return (vfs_stdextattrctl(mp, cmd, filename_vp, attrnamespace,
2251 	    attrname));
2252 #endif
2253 }
2254 
2255 static void
2256 ffs_ifree(struct ufsmount *ump, struct inode *ip)
2257 {
2258 
2259 	if (ump->um_fstype == UFS1 && ip->i_din1 != NULL)
2260 		uma_zfree(uma_ufs1, ip->i_din1);
2261 	else if (ip->i_din2 != NULL)
2262 		uma_zfree(uma_ufs2, ip->i_din2);
2263 	uma_zfree_smr(uma_inode, ip);
2264 }
2265 
2266 static int dobkgrdwrite = 1;
2267 SYSCTL_INT(_debug, OID_AUTO, dobkgrdwrite, CTLFLAG_RW, &dobkgrdwrite, 0,
2268     "Do background writes (honoring the BV_BKGRDWRITE flag)?");
2269 
2270 /*
2271  * Complete a background write started from bwrite.
2272  */
2273 static void
2274 ffs_backgroundwritedone(struct buf *bp)
2275 {
2276 	struct bufobj *bufobj;
2277 	struct buf *origbp;
2278 
2279 #ifdef SOFTUPDATES
2280 	if (!LIST_EMPTY(&bp->b_dep) && (bp->b_ioflags & BIO_ERROR) != 0)
2281 		softdep_handle_error(bp);
2282 #endif
2283 
2284 	/*
2285 	 * Find the original buffer that we are writing.
2286 	 */
2287 	bufobj = bp->b_bufobj;
2288 	BO_LOCK(bufobj);
2289 	if ((origbp = gbincore(bp->b_bufobj, bp->b_lblkno)) == NULL)
2290 		panic("backgroundwritedone: lost buffer");
2291 
2292 	/*
2293 	 * We should mark the cylinder group buffer origbp as
2294 	 * dirty, to not lose the failed write.
2295 	 */
2296 	if ((bp->b_ioflags & BIO_ERROR) != 0)
2297 		origbp->b_vflags |= BV_BKGRDERR;
2298 	BO_UNLOCK(bufobj);
2299 	/*
2300 	 * Process dependencies then return any unfinished ones.
2301 	 */
2302 	if (!LIST_EMPTY(&bp->b_dep) && (bp->b_ioflags & BIO_ERROR) == 0)
2303 		buf_complete(bp);
2304 #ifdef SOFTUPDATES
2305 	if (!LIST_EMPTY(&bp->b_dep))
2306 		softdep_move_dependencies(bp, origbp);
2307 #endif
2308 	/*
2309 	 * This buffer is marked B_NOCACHE so when it is released
2310 	 * by biodone it will be tossed.  Clear B_IOSTARTED in case of error.
2311 	 */
2312 	bp->b_flags |= B_NOCACHE;
2313 	bp->b_flags &= ~(B_CACHE | B_IOSTARTED);
2314 	pbrelvp(bp);
2315 
2316 	/*
2317 	 * Prevent brelse() from trying to keep and re-dirtying bp on
2318 	 * errors. It causes b_bufobj dereference in
2319 	 * bdirty()/reassignbuf(), and b_bufobj was cleared in
2320 	 * pbrelvp() above.
2321 	 */
2322 	if ((bp->b_ioflags & BIO_ERROR) != 0)
2323 		bp->b_flags |= B_INVAL;
2324 	bufdone(bp);
2325 	BO_LOCK(bufobj);
2326 	/*
2327 	 * Clear the BV_BKGRDINPROG flag in the original buffer
2328 	 * and awaken it if it is waiting for the write to complete.
2329 	 * If BV_BKGRDINPROG is not set in the original buffer it must
2330 	 * have been released and re-instantiated - which is not legal.
2331 	 */
2332 	KASSERT((origbp->b_vflags & BV_BKGRDINPROG),
2333 	    ("backgroundwritedone: lost buffer2"));
2334 	origbp->b_vflags &= ~BV_BKGRDINPROG;
2335 	if (origbp->b_vflags & BV_BKGRDWAIT) {
2336 		origbp->b_vflags &= ~BV_BKGRDWAIT;
2337 		wakeup(&origbp->b_xflags);
2338 	}
2339 	BO_UNLOCK(bufobj);
2340 }
2341 
2342 /*
2343  * Write, release buffer on completion.  (Done by iodone
2344  * if async).  Do not bother writing anything if the buffer
2345  * is invalid.
2346  *
2347  * Note that we set B_CACHE here, indicating that buffer is
2348  * fully valid and thus cacheable.  This is true even of NFS
2349  * now so we set it generally.  This could be set either here
2350  * or in biodone() since the I/O is synchronous.  We put it
2351  * here.
2352  */
2353 static int
2354 ffs_bufwrite(struct buf *bp)
2355 {
2356 	struct buf *newbp;
2357 	struct cg *cgp;
2358 
2359 	CTR3(KTR_BUF, "bufwrite(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2360 	if (bp->b_flags & B_INVAL) {
2361 		brelse(bp);
2362 		return (0);
2363 	}
2364 
2365 	if (!BUF_ISLOCKED(bp))
2366 		panic("bufwrite: buffer is not busy???");
2367 	/*
2368 	 * If a background write is already in progress, delay
2369 	 * writing this block if it is asynchronous. Otherwise
2370 	 * wait for the background write to complete.
2371 	 */
2372 	BO_LOCK(bp->b_bufobj);
2373 	if (bp->b_vflags & BV_BKGRDINPROG) {
2374 		if (bp->b_flags & B_ASYNC) {
2375 			BO_UNLOCK(bp->b_bufobj);
2376 			bdwrite(bp);
2377 			return (0);
2378 		}
2379 		bp->b_vflags |= BV_BKGRDWAIT;
2380 		msleep(&bp->b_xflags, BO_LOCKPTR(bp->b_bufobj), PRIBIO,
2381 		    "bwrbg", 0);
2382 		if (bp->b_vflags & BV_BKGRDINPROG)
2383 			panic("bufwrite: still writing");
2384 	}
2385 	bp->b_vflags &= ~BV_BKGRDERR;
2386 	BO_UNLOCK(bp->b_bufobj);
2387 
2388 	/*
2389 	 * If this buffer is marked for background writing and we
2390 	 * do not have to wait for it, make a copy and write the
2391 	 * copy so as to leave this buffer ready for further use.
2392 	 *
2393 	 * This optimization eats a lot of memory.  If we have a page
2394 	 * or buffer shortfall we can't do it.
2395 	 */
2396 	if (dobkgrdwrite && (bp->b_xflags & BX_BKGRDWRITE) &&
2397 	    (bp->b_flags & B_ASYNC) &&
2398 	    !vm_page_count_severe() &&
2399 	    !buf_dirty_count_severe()) {
2400 		KASSERT(bp->b_iodone == NULL,
2401 		    ("bufwrite: needs chained iodone (%p)", bp->b_iodone));
2402 
2403 		/* get a new block */
2404 		newbp = geteblk(bp->b_bufsize, GB_NOWAIT_BD);
2405 		if (newbp == NULL)
2406 			goto normal_write;
2407 
2408 		KASSERT(buf_mapped(bp), ("Unmapped cg"));
2409 		memcpy(newbp->b_data, bp->b_data, bp->b_bufsize);
2410 		BO_LOCK(bp->b_bufobj);
2411 		bp->b_vflags |= BV_BKGRDINPROG;
2412 		BO_UNLOCK(bp->b_bufobj);
2413 		newbp->b_xflags |=
2414 		    (bp->b_xflags & BX_FSPRIV) | BX_BKGRDMARKER;
2415 		newbp->b_lblkno = bp->b_lblkno;
2416 		newbp->b_blkno = bp->b_blkno;
2417 		newbp->b_offset = bp->b_offset;
2418 		newbp->b_iodone = ffs_backgroundwritedone;
2419 		newbp->b_flags |= B_ASYNC;
2420 		newbp->b_flags &= ~B_INVAL;
2421 		pbgetvp(bp->b_vp, newbp);
2422 
2423 #ifdef SOFTUPDATES
2424 		/*
2425 		 * Move over the dependencies.  If there are rollbacks,
2426 		 * leave the parent buffer dirtied as it will need to
2427 		 * be written again.
2428 		 */
2429 		if (LIST_EMPTY(&bp->b_dep) ||
2430 		    softdep_move_dependencies(bp, newbp) == 0)
2431 			bundirty(bp);
2432 #else
2433 		bundirty(bp);
2434 #endif
2435 
2436 		/*
2437 		 * Initiate write on the copy, release the original.  The
2438 		 * BKGRDINPROG flag prevents it from going away until
2439 		 * the background write completes. We have to recalculate
2440 		 * its check hash in case the buffer gets freed and then
2441 		 * reconstituted from the buffer cache during a later read.
2442 		 */
2443 		if ((bp->b_xflags & BX_CYLGRP) != 0) {
2444 			cgp = (struct cg *)bp->b_data;
2445 			cgp->cg_ckhash = 0;
2446 			cgp->cg_ckhash =
2447 			    calculate_crc32c(~0L, bp->b_data, bp->b_bcount);
2448 		}
2449 		bqrelse(bp);
2450 		bp = newbp;
2451 	} else
2452 		/* Mark the buffer clean */
2453 		bundirty(bp);
2454 
2455 	/* Let the normal bufwrite do the rest for us */
2456 normal_write:
2457 	/*
2458 	 * If we are writing a cylinder group, update its time.
2459 	 */
2460 	if ((bp->b_xflags & BX_CYLGRP) != 0) {
2461 		cgp = (struct cg *)bp->b_data;
2462 		cgp->cg_old_time = cgp->cg_time = time_second;
2463 	}
2464 	return (bufwrite(bp));
2465 }
2466 
2467 static void
2468 ffs_geom_strategy(struct bufobj *bo, struct buf *bp)
2469 {
2470 	struct vnode *vp;
2471 	struct buf *tbp;
2472 	int error, nocopy;
2473 
2474 	/*
2475 	 * This is the bufobj strategy for the private VCHR vnodes
2476 	 * used by FFS to access the underlying storage device.
2477 	 * We override the default bufobj strategy and thus bypass
2478 	 * VOP_STRATEGY() for these vnodes.
2479 	 */
2480 	vp = bo2vnode(bo);
2481 	KASSERT(bp->b_vp == NULL || bp->b_vp->v_type != VCHR ||
2482 	    bp->b_vp->v_rdev == NULL ||
2483 	    bp->b_vp->v_rdev->si_mountpt == NULL ||
2484 	    VFSTOUFS(bp->b_vp->v_rdev->si_mountpt) == NULL ||
2485 	    vp == VFSTOUFS(bp->b_vp->v_rdev->si_mountpt)->um_devvp,
2486 	    ("ffs_geom_strategy() with wrong vp"));
2487 	if (bp->b_iocmd == BIO_WRITE) {
2488 		if ((bp->b_flags & B_VALIDSUSPWRT) == 0 &&
2489 		    bp->b_vp != NULL && bp->b_vp->v_mount != NULL &&
2490 		    (bp->b_vp->v_mount->mnt_kern_flag & MNTK_SUSPENDED) != 0)
2491 			panic("ffs_geom_strategy: bad I/O");
2492 		nocopy = bp->b_flags & B_NOCOPY;
2493 		bp->b_flags &= ~(B_VALIDSUSPWRT | B_NOCOPY);
2494 		if ((vp->v_vflag & VV_COPYONWRITE) && nocopy == 0 &&
2495 		    vp->v_rdev->si_snapdata != NULL) {
2496 			if ((bp->b_flags & B_CLUSTER) != 0) {
2497 				runningbufwakeup(bp);
2498 				TAILQ_FOREACH(tbp, &bp->b_cluster.cluster_head,
2499 					      b_cluster.cluster_entry) {
2500 					error = ffs_copyonwrite(vp, tbp);
2501 					if (error != 0 &&
2502 					    error != EOPNOTSUPP) {
2503 						bp->b_error = error;
2504 						bp->b_ioflags |= BIO_ERROR;
2505 						bp->b_flags &= ~B_BARRIER;
2506 						bufdone(bp);
2507 						return;
2508 					}
2509 				}
2510 				bp->b_runningbufspace = bp->b_bufsize;
2511 				atomic_add_long(&runningbufspace,
2512 					       bp->b_runningbufspace);
2513 			} else {
2514 				error = ffs_copyonwrite(vp, bp);
2515 				if (error != 0 && error != EOPNOTSUPP) {
2516 					bp->b_error = error;
2517 					bp->b_ioflags |= BIO_ERROR;
2518 					bp->b_flags &= ~B_BARRIER;
2519 					bufdone(bp);
2520 					return;
2521 				}
2522 			}
2523 		}
2524 #ifdef SOFTUPDATES
2525 		if ((bp->b_flags & B_CLUSTER) != 0) {
2526 			TAILQ_FOREACH(tbp, &bp->b_cluster.cluster_head,
2527 				      b_cluster.cluster_entry) {
2528 				if (!LIST_EMPTY(&tbp->b_dep))
2529 					buf_start(tbp);
2530 			}
2531 		} else {
2532 			if (!LIST_EMPTY(&bp->b_dep))
2533 				buf_start(bp);
2534 		}
2535 
2536 #endif
2537 		/*
2538 		 * Check for metadata that needs check-hashes and update them.
2539 		 */
2540 		switch (bp->b_xflags & BX_FSPRIV) {
2541 		case BX_CYLGRP:
2542 			((struct cg *)bp->b_data)->cg_ckhash = 0;
2543 			((struct cg *)bp->b_data)->cg_ckhash =
2544 			    calculate_crc32c(~0L, bp->b_data, bp->b_bcount);
2545 			break;
2546 
2547 		case BX_SUPERBLOCK:
2548 		case BX_INODE:
2549 		case BX_INDIR:
2550 		case BX_DIR:
2551 			printf("Check-hash write is unimplemented!!!\n");
2552 			break;
2553 
2554 		case 0:
2555 			break;
2556 
2557 		default:
2558 			printf("multiple buffer types 0x%b\n",
2559 			    (u_int)(bp->b_xflags & BX_FSPRIV),
2560 			    PRINT_UFS_BUF_XFLAGS);
2561 			break;
2562 		}
2563 	}
2564 	if (bp->b_iocmd != BIO_READ && ffs_enxio_enable)
2565 		bp->b_xflags |= BX_CVTENXIO;
2566 	g_vfs_strategy(bo, bp);
2567 }
2568 
2569 int
2570 ffs_own_mount(const struct mount *mp)
2571 {
2572 
2573 	if (mp->mnt_op == &ufs_vfsops)
2574 		return (1);
2575 	return (0);
2576 }
2577 
2578 #ifdef	DDB
2579 #ifdef SOFTUPDATES
2580 
2581 /* defined in ffs_softdep.c */
2582 extern void db_print_ffs(struct ufsmount *ump);
2583 
2584 DB_SHOW_COMMAND(ffs, db_show_ffs)
2585 {
2586 	struct mount *mp;
2587 	struct ufsmount *ump;
2588 
2589 	if (have_addr) {
2590 		ump = VFSTOUFS((struct mount *)addr);
2591 		db_print_ffs(ump);
2592 		return;
2593 	}
2594 
2595 	TAILQ_FOREACH(mp, &mountlist, mnt_list) {
2596 		if (!strcmp(mp->mnt_stat.f_fstypename, ufs_vfsconf.vfc_name))
2597 			db_print_ffs(VFSTOUFS(mp));
2598 	}
2599 }
2600 
2601 #endif	/* SOFTUPDATES */
2602 #endif	/* DDB */
2603