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