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