xref: /linux/fs/xfs/xfs_mount.c (revision 3577cfd738e29b3d54cdb10c45a56730346dfe8b)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (c) 2000-2005 Silicon Graphics, Inc.
4  * All Rights Reserved.
5  */
6 #include "xfs_platform.h"
7 #include "xfs_fs.h"
8 #include "xfs_shared.h"
9 #include "xfs_format.h"
10 #include "xfs_log_format.h"
11 #include "xfs_trans_resv.h"
12 #include "xfs_bit.h"
13 #include "xfs_sb.h"
14 #include "xfs_mount.h"
15 #include "xfs_inode.h"
16 #include "xfs_dir2.h"
17 #include "xfs_ialloc.h"
18 #include "xfs_alloc.h"
19 #include "xfs_rtalloc.h"
20 #include "xfs_bmap.h"
21 #include "xfs_trans.h"
22 #include "xfs_trans_priv.h"
23 #include "xfs_log.h"
24 #include "xfs_log_priv.h"
25 #include "xfs_error.h"
26 #include "xfs_quota.h"
27 #include "xfs_fsops.h"
28 #include "xfs_icache.h"
29 #include "xfs_sysfs.h"
30 #include "xfs_rmap_btree.h"
31 #include "xfs_refcount_btree.h"
32 #include "xfs_reflink.h"
33 #include "xfs_extent_busy.h"
34 #include "xfs_health.h"
35 #include "xfs_trace.h"
36 #include "xfs_ag.h"
37 #include "xfs_rtbitmap.h"
38 #include "xfs_metafile.h"
39 #include "xfs_rtgroup.h"
40 #include "xfs_rtrmap_btree.h"
41 #include "xfs_rtrefcount_btree.h"
42 #include "scrub/stats.h"
43 #include "xfs_zone_alloc.h"
44 #include "xfs_healthmon.h"
45 
46 static DEFINE_MUTEX(xfs_uuid_table_mutex);
47 static int xfs_uuid_table_size;
48 static uuid_t *xfs_uuid_table;
49 
50 void
xfs_uuid_table_free(void)51 xfs_uuid_table_free(void)
52 {
53 	if (xfs_uuid_table_size == 0)
54 		return;
55 	kfree(xfs_uuid_table);
56 	xfs_uuid_table = NULL;
57 	xfs_uuid_table_size = 0;
58 }
59 
60 /*
61  * See if the UUID is unique among mounted XFS filesystems.
62  * Mount fails if UUID is nil or a FS with the same UUID is already mounted.
63  */
64 STATIC int
xfs_uuid_mount(struct xfs_mount * mp)65 xfs_uuid_mount(
66 	struct xfs_mount	*mp)
67 {
68 	uuid_t			*uuid = &mp->m_sb.sb_uuid;
69 	int			hole, i;
70 
71 	/* Publish UUID in struct super_block */
72 	super_set_uuid(mp->m_super, uuid->b, sizeof(*uuid));
73 
74 	if (xfs_has_nouuid(mp))
75 		return 0;
76 
77 	if (uuid_is_null(uuid)) {
78 		xfs_warn(mp, "Filesystem has null UUID - can't mount");
79 		return -EINVAL;
80 	}
81 
82 	mutex_lock(&xfs_uuid_table_mutex);
83 	for (i = 0, hole = -1; i < xfs_uuid_table_size; i++) {
84 		if (uuid_is_null(&xfs_uuid_table[i])) {
85 			hole = i;
86 			continue;
87 		}
88 		if (uuid_equal(uuid, &xfs_uuid_table[i]))
89 			goto out_duplicate;
90 	}
91 
92 	if (hole < 0) {
93 		xfs_uuid_table = krealloc(xfs_uuid_table,
94 			(xfs_uuid_table_size + 1) * sizeof(*xfs_uuid_table),
95 			GFP_KERNEL | __GFP_NOFAIL);
96 		hole = xfs_uuid_table_size++;
97 	}
98 	xfs_uuid_table[hole] = *uuid;
99 	mutex_unlock(&xfs_uuid_table_mutex);
100 
101 	return 0;
102 
103  out_duplicate:
104 	mutex_unlock(&xfs_uuid_table_mutex);
105 	xfs_warn(mp, "Filesystem has duplicate UUID %pU - can't mount", uuid);
106 	return -EINVAL;
107 }
108 
109 STATIC void
xfs_uuid_unmount(struct xfs_mount * mp)110 xfs_uuid_unmount(
111 	struct xfs_mount	*mp)
112 {
113 	uuid_t			*uuid = &mp->m_sb.sb_uuid;
114 	int			i;
115 
116 	if (xfs_has_nouuid(mp))
117 		return;
118 
119 	mutex_lock(&xfs_uuid_table_mutex);
120 	for (i = 0; i < xfs_uuid_table_size; i++) {
121 		if (uuid_is_null(&xfs_uuid_table[i]))
122 			continue;
123 		if (!uuid_equal(uuid, &xfs_uuid_table[i]))
124 			continue;
125 		memset(&xfs_uuid_table[i], 0, sizeof(uuid_t));
126 		break;
127 	}
128 	ASSERT(i < xfs_uuid_table_size);
129 	mutex_unlock(&xfs_uuid_table_mutex);
130 }
131 
132 /*
133  * Check size of device based on the (data/realtime) block count.
134  * Note: this check is used by the growfs code as well as mount.
135  */
136 int
xfs_sb_validate_fsb_count(xfs_sb_t * sbp,uint64_t nblocks)137 xfs_sb_validate_fsb_count(
138 	xfs_sb_t	*sbp,
139 	uint64_t	nblocks)
140 {
141 	uint64_t		max_bytes;
142 
143 	ASSERT(sbp->sb_blocklog >= BBSHIFT);
144 
145 	if (check_shl_overflow(nblocks, sbp->sb_blocklog, &max_bytes))
146 		return -EFBIG;
147 
148 	/* Limited by ULONG_MAX of page cache index */
149 	if (max_bytes >> PAGE_SHIFT > ULONG_MAX)
150 		return -EFBIG;
151 	return 0;
152 }
153 
154 /*
155  * xfs_readsb
156  *
157  * Does the initial read of the superblock.
158  */
159 int
xfs_readsb(struct xfs_mount * mp,int flags)160 xfs_readsb(
161 	struct xfs_mount *mp,
162 	int		flags)
163 {
164 	unsigned int	sector_size;
165 	struct xfs_buf	*bp;
166 	struct xfs_sb	*sbp = &mp->m_sb;
167 	int		error;
168 	int		loud = !(flags & XFS_MFSI_QUIET);
169 	const struct xfs_buf_ops *buf_ops;
170 
171 	ASSERT(mp->m_sb_bp == NULL);
172 	ASSERT(mp->m_ddev_targp != NULL);
173 
174 	/*
175 	 * In the first pass, use the device sector size to just read enough
176 	 * of the superblock to extract the XFS sector size.
177 	 *
178 	 * The device sector size must be smaller than or equal to the XFS
179 	 * sector size and thus we can always read the superblock.  Once we know
180 	 * the XFS sector size, re-read it and run the buffer verifier.
181 	 */
182 	sector_size = mp->m_ddev_targp->bt_logical_sectorsize;
183 	buf_ops = NULL;
184 
185 reread:
186 	error = xfs_buf_read_uncached(mp->m_ddev_targp, XFS_SB_DADDR,
187 				      BTOBB(sector_size), &bp, buf_ops);
188 	if (error) {
189 		if (loud)
190 			xfs_warn(mp, "SB validate failed with error %d.", error);
191 		/* bad CRC means corrupted metadata */
192 		if (error == -EFSBADCRC)
193 			error = -EFSCORRUPTED;
194 		return error;
195 	}
196 
197 	/*
198 	 * Initialize the mount structure from the superblock.
199 	 */
200 	xfs_sb_from_disk(sbp, bp->b_addr);
201 
202 	/*
203 	 * If we haven't validated the superblock, do so now before we try
204 	 * to check the sector size and reread the superblock appropriately.
205 	 */
206 	if (sbp->sb_magicnum != XFS_SB_MAGIC) {
207 		if (loud)
208 			xfs_warn(mp, "Invalid superblock magic number");
209 		error = -EINVAL;
210 		goto release_buf;
211 	}
212 
213 	/*
214 	 * We must be able to do sector-sized and sector-aligned IO.
215 	 */
216 	if (sector_size > sbp->sb_sectsize) {
217 		if (loud)
218 			xfs_warn(mp, "device supports %u byte sectors (not %u)",
219 				sector_size, sbp->sb_sectsize);
220 		error = -ENOSYS;
221 		goto release_buf;
222 	}
223 
224 	if (buf_ops == NULL) {
225 		/*
226 		 * Re-read the superblock so the buffer is correctly sized,
227 		 * and properly verified.
228 		 */
229 		xfs_buf_relse(bp);
230 		sector_size = sbp->sb_sectsize;
231 		buf_ops = loud ? &xfs_sb_buf_ops : &xfs_sb_quiet_buf_ops;
232 		goto reread;
233 	}
234 
235 	mp->m_features |= xfs_sb_version_to_features(sbp);
236 	xfs_reinit_percpu_counters(mp);
237 
238 	/*
239 	 * If logged xattrs are enabled after log recovery finishes, then set
240 	 * the opstate so that log recovery will work properly.
241 	 */
242 	if (xfs_sb_version_haslogxattrs(&mp->m_sb))
243 		xfs_set_using_logged_xattrs(mp);
244 
245 	/* no need to be quiet anymore, so reset the buf ops */
246 	bp->b_ops = &xfs_sb_buf_ops;
247 
248 	/*
249 	 * Keep a pointer of the sb buffer around instead of caching it in the
250 	 * buffer cache because we access it frequently.
251 	 */
252 	mp->m_sb_bp = bp;
253 	xfs_buf_unlock(bp);
254 	return 0;
255 
256 release_buf:
257 	xfs_buf_relse(bp);
258 	return error;
259 }
260 
261 /*
262  * If the sunit/swidth change would move the precomputed root inode value, we
263  * must reject the ondisk change because repair will stumble over that.
264  * However, we allow the mount to proceed because we never rejected this
265  * combination before.  Returns true to update the sb, false otherwise.
266  */
267 static inline int
xfs_check_new_dalign(struct xfs_mount * mp,int new_dalign,bool * update_sb)268 xfs_check_new_dalign(
269 	struct xfs_mount	*mp,
270 	int			new_dalign,
271 	bool			*update_sb)
272 {
273 	struct xfs_sb		*sbp = &mp->m_sb;
274 	xfs_ino_t		calc_ino;
275 
276 	calc_ino = xfs_ialloc_calc_rootino(mp, new_dalign);
277 	trace_xfs_check_new_dalign(mp, new_dalign, calc_ino);
278 
279 	if (sbp->sb_rootino == calc_ino) {
280 		*update_sb = true;
281 		return 0;
282 	}
283 
284 	xfs_warn(mp,
285 "Cannot change stripe alignment; would require moving root inode.");
286 
287 	/*
288 	 * XXX: Next time we add a new incompat feature, this should start
289 	 * returning -EINVAL to fail the mount.  Until then, spit out a warning
290 	 * that we're ignoring the administrator's instructions.
291 	 */
292 	xfs_warn(mp, "Skipping superblock stripe alignment update.");
293 	*update_sb = false;
294 	return 0;
295 }
296 
297 /*
298  * If we were provided with new sunit/swidth values as mount options, make sure
299  * that they pass basic alignment and superblock feature checks, and convert
300  * them into the same units (FSB) that everything else expects.  This step
301  * /must/ be done before computing the inode geometry.
302  */
303 STATIC int
xfs_validate_new_dalign(struct xfs_mount * mp)304 xfs_validate_new_dalign(
305 	struct xfs_mount	*mp)
306 {
307 	if (mp->m_dalign == 0)
308 		return 0;
309 
310 	/*
311 	 * If stripe unit and stripe width are not multiples
312 	 * of the fs blocksize turn off alignment.
313 	 */
314 	if ((BBTOB(mp->m_dalign) & mp->m_blockmask) ||
315 	    (BBTOB(mp->m_swidth) & mp->m_blockmask)) {
316 		xfs_warn(mp,
317 	"alignment check failed: sunit/swidth vs. blocksize(%d)",
318 			mp->m_sb.sb_blocksize);
319 		return -EINVAL;
320 	}
321 
322 	/*
323 	 * Convert the stripe unit and width to FSBs.
324 	 */
325 	mp->m_dalign = XFS_BB_TO_FSBT(mp, mp->m_dalign);
326 	if (mp->m_dalign && (mp->m_sb.sb_agblocks % mp->m_dalign)) {
327 		xfs_warn(mp,
328 	"alignment check failed: sunit/swidth vs. agsize(%d)",
329 			mp->m_sb.sb_agblocks);
330 		return -EINVAL;
331 	}
332 
333 	if (!mp->m_dalign) {
334 		xfs_warn(mp,
335 	"alignment check failed: sunit(%d) less than bsize(%d)",
336 			mp->m_dalign, mp->m_sb.sb_blocksize);
337 		return -EINVAL;
338 	}
339 
340 	mp->m_swidth = XFS_BB_TO_FSBT(mp, mp->m_swidth);
341 
342 	if (!xfs_has_dalign(mp)) {
343 		xfs_warn(mp,
344 "cannot change alignment: superblock does not support data alignment");
345 		return -EINVAL;
346 	}
347 
348 	return 0;
349 }
350 
351 /* Update alignment values based on mount options and sb values. */
352 STATIC int
xfs_update_alignment(struct xfs_mount * mp)353 xfs_update_alignment(
354 	struct xfs_mount	*mp)
355 {
356 	struct xfs_sb		*sbp = &mp->m_sb;
357 
358 	if (mp->m_dalign) {
359 		bool		update_sb;
360 		int		error;
361 
362 		if (sbp->sb_unit == mp->m_dalign &&
363 		    sbp->sb_width == mp->m_swidth)
364 			return 0;
365 
366 		error = xfs_check_new_dalign(mp, mp->m_dalign, &update_sb);
367 		if (error || !update_sb)
368 			return error;
369 
370 		sbp->sb_unit = mp->m_dalign;
371 		sbp->sb_width = mp->m_swidth;
372 		mp->m_update_sb = true;
373 	} else if (!xfs_has_noalign(mp) && xfs_has_dalign(mp)) {
374 		mp->m_dalign = sbp->sb_unit;
375 		mp->m_swidth = sbp->sb_width;
376 	}
377 
378 	return 0;
379 }
380 
381 /*
382  * precalculate the low space thresholds for dynamic speculative preallocation.
383  */
384 void
xfs_set_low_space_thresholds(struct xfs_mount * mp)385 xfs_set_low_space_thresholds(
386 	struct xfs_mount	*mp)
387 {
388 	uint64_t		dblocks = mp->m_sb.sb_dblocks;
389 	uint64_t		rtexts = mp->m_sb.sb_rextents;
390 	int			i;
391 
392 	do_div(dblocks, 100);
393 	do_div(rtexts, 100);
394 
395 	for (i = 0; i < XFS_LOWSP_MAX; i++) {
396 		mp->m_low_space[i] = dblocks * (i + 1);
397 		mp->m_low_rtexts[i] = rtexts * (i + 1);
398 	}
399 }
400 
401 /*
402  * Check that the data (and log if separate) is an ok size.
403  */
404 STATIC int
xfs_check_sizes(struct xfs_mount * mp)405 xfs_check_sizes(
406 	struct xfs_mount *mp)
407 {
408 	struct xfs_buf	*bp;
409 	xfs_daddr_t	d;
410 	int		error;
411 
412 	d = (xfs_daddr_t)XFS_FSB_TO_BB(mp, mp->m_sb.sb_dblocks);
413 	if (XFS_BB_TO_FSB(mp, d) != mp->m_sb.sb_dblocks) {
414 		xfs_warn(mp, "filesystem size mismatch detected");
415 		return -EFBIG;
416 	}
417 	error = xfs_buf_read_uncached(mp->m_ddev_targp,
418 					d - XFS_FSS_TO_BB(mp, 1),
419 					XFS_FSS_TO_BB(mp, 1), &bp, NULL);
420 	if (error) {
421 		xfs_warn(mp, "last sector read failed");
422 		return error;
423 	}
424 	xfs_buf_relse(bp);
425 
426 	if (mp->m_logdev_targp == mp->m_ddev_targp)
427 		return 0;
428 
429 	d = (xfs_daddr_t)XFS_FSB_TO_BB(mp, mp->m_sb.sb_logblocks);
430 	if (XFS_BB_TO_FSB(mp, d) != mp->m_sb.sb_logblocks) {
431 		xfs_warn(mp, "log size mismatch detected");
432 		return -EFBIG;
433 	}
434 	error = xfs_buf_read_uncached(mp->m_logdev_targp,
435 					d - XFS_FSB_TO_BB(mp, 1),
436 					XFS_FSB_TO_BB(mp, 1), &bp, NULL);
437 	if (error) {
438 		xfs_warn(mp, "log device read failed");
439 		return error;
440 	}
441 	xfs_buf_relse(bp);
442 	return 0;
443 }
444 
445 /*
446  * Clear the quotaflags in memory and in the superblock.
447  */
448 int
xfs_mount_reset_sbqflags(struct xfs_mount * mp)449 xfs_mount_reset_sbqflags(
450 	struct xfs_mount	*mp)
451 {
452 	mp->m_qflags = 0;
453 
454 	/* It is OK to look at sb_qflags in the mount path without m_sb_lock. */
455 	if (mp->m_sb.sb_qflags == 0)
456 		return 0;
457 	spin_lock(&mp->m_sb_lock);
458 	mp->m_sb.sb_qflags = 0;
459 	spin_unlock(&mp->m_sb_lock);
460 
461 	if (!xfs_fs_writable(mp, SB_FREEZE_WRITE))
462 		return 0;
463 
464 	return xfs_sync_sb(mp, false);
465 }
466 
467 static const char *const xfs_free_pool_name[] = {
468 	[XC_FREE_BLOCKS]	= "free blocks",
469 	[XC_FREE_RTEXTENTS]	= "free rt extents",
470 	[XC_FREE_RTAVAILABLE]	= "available rt extents",
471 };
472 
473 uint64_t
xfs_default_resblks(struct xfs_mount * mp,enum xfs_free_counter ctr)474 xfs_default_resblks(
475 	struct xfs_mount	*mp,
476 	enum xfs_free_counter	ctr)
477 {
478 	switch (ctr) {
479 	case XC_FREE_BLOCKS:
480 		/*
481 		 * Default to 5% or 8192 FSBs of space reserved, whichever is
482 		 * smaller.
483 		 *
484 		 * This is intended to cover concurrent allocation transactions
485 		 * when we initially hit ENOSPC.  These each require a 4 block
486 		 * reservation. Hence by default we cover roughly 2000
487 		 * concurrent allocation reservations.
488 		 */
489 		return min(div_u64(mp->m_sb.sb_dblocks, 20), 8192ULL);
490 	case XC_FREE_RTEXTENTS:
491 	case XC_FREE_RTAVAILABLE:
492 		if (IS_ENABLED(CONFIG_XFS_RT) && xfs_has_zoned(mp))
493 			return xfs_zoned_default_resblks(mp, ctr);
494 		return 0;
495 	default:
496 		ASSERT(0);
497 		return 0;
498 	}
499 }
500 
501 /* Ensure the summary counts are correct. */
502 STATIC int
xfs_check_summary_counts(struct xfs_mount * mp)503 xfs_check_summary_counts(
504 	struct xfs_mount	*mp)
505 {
506 	int			error = 0;
507 
508 	/*
509 	 * The AG0 superblock verifier rejects in-progress filesystems,
510 	 * so we should never see the flag set this far into mounting.
511 	 */
512 	if (mp->m_sb.sb_inprogress) {
513 		xfs_err(mp, "sb_inprogress set after log recovery??");
514 		WARN_ON(1);
515 		return -EFSCORRUPTED;
516 	}
517 
518 	/*
519 	 * Now the log is mounted, we know if it was an unclean shutdown or
520 	 * not. If it was, with the first phase of recovery has completed, we
521 	 * have consistent AG blocks on disk. We have not recovered EFIs yet,
522 	 * but they are recovered transactionally in the second recovery phase
523 	 * later.
524 	 *
525 	 * If the log was clean when we mounted, we can check the summary
526 	 * counters.  If any of them are obviously incorrect, we can recompute
527 	 * them from the AGF headers in the next step.
528 	 */
529 	if (xfs_is_clean(mp) &&
530 	    (mp->m_sb.sb_fdblocks > mp->m_sb.sb_dblocks ||
531 	     !xfs_verify_icount(mp, mp->m_sb.sb_icount) ||
532 	     mp->m_sb.sb_ifree > mp->m_sb.sb_icount))
533 		xfs_fs_mark_sick(mp, XFS_SICK_FS_COUNTERS);
534 
535 	/*
536 	 * We can safely re-initialise incore superblock counters from the
537 	 * per-ag data. These may not be correct if the filesystem was not
538 	 * cleanly unmounted, so we waited for recovery to finish before doing
539 	 * this.
540 	 *
541 	 * If the filesystem was cleanly unmounted or the previous check did
542 	 * not flag anything weird, then we can trust the values in the
543 	 * superblock to be correct and we don't need to do anything here.
544 	 * Otherwise, recalculate the summary counters.
545 	 */
546 	if ((xfs_has_lazysbcount(mp) && !xfs_is_clean(mp)) ||
547 	    xfs_fs_has_sickness(mp, XFS_SICK_FS_COUNTERS)) {
548 		error = xfs_initialize_perag_data(mp, mp->m_sb.sb_agcount);
549 		if (error)
550 			return error;
551 	}
552 
553 	/*
554 	 * Older kernels misused sb_frextents to reflect both incore
555 	 * reservations made by running transactions and the actual count of
556 	 * free rt extents in the ondisk metadata.  Transactions committed
557 	 * during runtime can therefore contain a superblock update that
558 	 * undercounts the number of free rt extents tracked in the rt bitmap.
559 	 * A clean unmount record will have the correct frextents value since
560 	 * there can be no other transactions running at that point.
561 	 *
562 	 * If we're mounting the rt volume after recovering the log, recompute
563 	 * frextents from the rtbitmap file to fix the inconsistency.
564 	 */
565 	if (xfs_has_realtime(mp) && !xfs_has_zoned(mp) && !xfs_is_clean(mp)) {
566 		error = xfs_rtalloc_reinit_frextents(mp);
567 		if (error)
568 			return error;
569 	}
570 
571 	return 0;
572 }
573 
574 static void
xfs_unmount_check(struct xfs_mount * mp)575 xfs_unmount_check(
576 	struct xfs_mount	*mp)
577 {
578 	if (xfs_is_shutdown(mp))
579 		return;
580 
581 	if (percpu_counter_sum(&mp->m_ifree) >
582 			percpu_counter_sum(&mp->m_icount)) {
583 		xfs_alert(mp, "ifree/icount mismatch at unmount");
584 		xfs_fs_mark_sick(mp, XFS_SICK_FS_COUNTERS);
585 	}
586 }
587 
588 /*
589  * Flush and reclaim dirty inodes in preparation for unmount. Inodes and
590  * internal inode structures can be sitting in the CIL and AIL at this point,
591  * so we need to unpin them, write them back and/or reclaim them before unmount
592  * can proceed.  In other words, callers are required to have inactivated all
593  * inodes.
594  *
595  * An inode cluster that has been freed can have its buffer still pinned in
596  * memory because the transaction is still sitting in a iclog. The stale inodes
597  * on that buffer will be pinned to the buffer until the transaction hits the
598  * disk and the callbacks run. Pushing the AIL will skip the stale inodes and
599  * may never see the pinned buffer, so nothing will push out the iclog and
600  * unpin the buffer.
601  *
602  * Hence we need to force the log to unpin everything first. However, log
603  * forces don't wait for the discards they issue to complete, so we have to
604  * explicitly wait for them to complete here as well.
605  *
606  * Then we can tell the world we are unmounting so that error handling knows
607  * that the filesystem is going away and we should error out anything that we
608  * have been retrying in the background.  This will prevent never-ending
609  * retries in AIL pushing from hanging the unmount.
610  *
611  * Stop inodegc and background reclaim before pushing the AIL so that they
612  * are not running while the AIL is being flushed. Then push the AIL to
613  * clean all the remaining dirty objects and reclaim the remaining inodes.
614  */
615 static void
xfs_unmount_flush_inodes(struct xfs_mount * mp)616 xfs_unmount_flush_inodes(
617 	struct xfs_mount	*mp)
618 {
619 	xfs_log_force(mp, XFS_LOG_SYNC);
620 	xfs_extent_busy_wait_all(mp);
621 	flush_workqueue(xfs_discard_wq);
622 
623 	xfs_set_unmounting(mp);
624 
625 	xfs_inodegc_stop(mp);
626 	cancel_delayed_work_sync(&mp->m_reclaim_work);
627 	xfs_ail_push_all_sync(mp->m_ail);
628 	xfs_reclaim_inodes(mp);
629 	xfs_health_unmount(mp);
630 	xfs_healthmon_unmount(mp);
631 }
632 
633 static void
xfs_mount_setup_inode_geom(struct xfs_mount * mp)634 xfs_mount_setup_inode_geom(
635 	struct xfs_mount	*mp)
636 {
637 	struct xfs_ino_geometry *igeo = M_IGEO(mp);
638 
639 	igeo->attr_fork_offset = xfs_bmap_compute_attr_offset(mp);
640 	ASSERT(igeo->attr_fork_offset < XFS_LITINO(mp));
641 
642 	xfs_ialloc_setup_geometry(mp);
643 }
644 
645 /* Mount the metadata directory tree root. */
646 STATIC int
xfs_mount_setup_metadir(struct xfs_mount * mp)647 xfs_mount_setup_metadir(
648 	struct xfs_mount	*mp)
649 {
650 	int			error;
651 
652 	/* Load the metadata directory root inode into memory. */
653 	error = xfs_metafile_iget(mp, mp->m_sb.sb_metadirino, XFS_METAFILE_DIR,
654 			&mp->m_metadirip);
655 	if (error)
656 		xfs_warn(mp, "Failed to load metadir root directory, error %d",
657 				error);
658 	return error;
659 }
660 
661 /* Compute maximum possible height for per-AG btree types for this fs. */
662 static inline void
xfs_agbtree_compute_maxlevels(struct xfs_mount * mp)663 xfs_agbtree_compute_maxlevels(
664 	struct xfs_mount	*mp)
665 {
666 	unsigned int		levels;
667 
668 	levels = max(mp->m_alloc_maxlevels, M_IGEO(mp)->inobt_maxlevels);
669 	levels = max(levels, mp->m_rmap_maxlevels);
670 	mp->m_agbtree_maxlevels = max(levels, mp->m_refc_maxlevels);
671 }
672 
673 /* Maximum atomic write IO size that the kernel allows. */
xfs_calc_atomic_write_max(struct xfs_mount * mp)674 static inline xfs_extlen_t xfs_calc_atomic_write_max(struct xfs_mount *mp)
675 {
676 	return rounddown_pow_of_two(XFS_B_TO_FSB(mp, MAX_RW_COUNT));
677 }
678 
679 /*
680  * If the underlying device advertises atomic write support, limit the size of
681  * atomic writes to the greatest power-of-two factor of the group size so
682  * that every atomic write unit aligns with the start of every group.  This is
683  * required so that the allocations for an atomic write will always be
684  * aligned compatibly with the alignment requirements of the storage.
685  *
686  * If the device doesn't advertise atomic writes, then there are no alignment
687  * restrictions and the largest out-of-place write we can do ourselves is the
688  * number of blocks that user files can allocate from any group.
689  */
690 static xfs_extlen_t
xfs_calc_group_awu_max(struct xfs_mount * mp,enum xfs_group_type type)691 xfs_calc_group_awu_max(
692 	struct xfs_mount	*mp,
693 	enum xfs_group_type	type)
694 {
695 	struct xfs_groups	*g = &mp->m_groups[type];
696 	struct xfs_buftarg	*btp = xfs_group_type_buftarg(mp, type);
697 
698 	if (g->blocks == 0)
699 		return 0;
700 	if (btp && btp->bt_awu_min > 0)
701 		return max_pow_of_two_factor(g->blocks);
702 	return rounddown_pow_of_two(g->blocks);
703 }
704 
705 /* Compute the maximum atomic write unit size for each section. */
706 static inline void
xfs_calc_atomic_write_unit_max(struct xfs_mount * mp,enum xfs_group_type type)707 xfs_calc_atomic_write_unit_max(
708 	struct xfs_mount	*mp,
709 	enum xfs_group_type	type)
710 {
711 	struct xfs_groups	*g = &mp->m_groups[type];
712 
713 	const xfs_extlen_t	max_write = xfs_calc_atomic_write_max(mp);
714 	const xfs_extlen_t	max_ioend = xfs_reflink_max_atomic_cow(mp);
715 	const xfs_extlen_t	max_gsize = xfs_calc_group_awu_max(mp, type);
716 
717 	g->awu_max = min3(max_write, max_ioend, max_gsize);
718 	trace_xfs_calc_atomic_write_unit_max(mp, type, max_write, max_ioend,
719 			max_gsize, g->awu_max);
720 }
721 
722 /*
723  * Try to set the atomic write maximum to a new value that we got from
724  * userspace via mount option.
725  */
726 int
xfs_set_max_atomic_write_opt(struct xfs_mount * mp,unsigned long long new_max_bytes)727 xfs_set_max_atomic_write_opt(
728 	struct xfs_mount	*mp,
729 	unsigned long long	new_max_bytes)
730 {
731 	const xfs_filblks_t	new_max_fsbs = XFS_B_TO_FSBT(mp, new_max_bytes);
732 	const xfs_extlen_t	max_write = xfs_calc_atomic_write_max(mp);
733 	const xfs_extlen_t	max_group =
734 		max(mp->m_groups[XG_TYPE_AG].blocks,
735 		    mp->m_groups[XG_TYPE_RTG].blocks);
736 	const xfs_extlen_t	max_group_write =
737 		max(xfs_calc_group_awu_max(mp, XG_TYPE_AG),
738 		    xfs_calc_group_awu_max(mp, XG_TYPE_RTG));
739 	int			error;
740 
741 	if (new_max_bytes == 0)
742 		goto set_limit;
743 
744 	ASSERT(max_write <= U32_MAX);
745 
746 	/* generic_atomic_write_valid enforces power of two length */
747 	if (!is_power_of_2(new_max_bytes)) {
748 		xfs_warn(mp,
749  "max atomic write size of %llu bytes is not a power of 2",
750 				new_max_bytes);
751 		return -EINVAL;
752 	}
753 
754 	if (new_max_bytes & mp->m_blockmask) {
755 		xfs_warn(mp,
756  "max atomic write size of %llu bytes not aligned with fsblock",
757 				new_max_bytes);
758 		return -EINVAL;
759 	}
760 
761 	if (new_max_fsbs > max_write) {
762 		xfs_warn(mp,
763  "max atomic write size of %lluk cannot be larger than max write size %lluk",
764 				new_max_bytes >> 10,
765 				XFS_FSB_TO_B(mp, max_write) >> 10);
766 		return -EINVAL;
767 	}
768 
769 	if (new_max_fsbs > max_group) {
770 		xfs_warn(mp,
771  "max atomic write size of %lluk cannot be larger than allocation group size %lluk",
772 				new_max_bytes >> 10,
773 				XFS_FSB_TO_B(mp, max_group) >> 10);
774 		return -EINVAL;
775 	}
776 
777 	if (new_max_fsbs > max_group_write) {
778 		xfs_warn(mp,
779  "max atomic write size of %lluk cannot be larger than max allocation group write size %lluk",
780 				new_max_bytes >> 10,
781 				XFS_FSB_TO_B(mp, max_group_write) >> 10);
782 		return -EINVAL;
783 	}
784 
785 	if (xfs_has_reflink(mp))
786 		goto set_limit;
787 
788 	if (new_max_fsbs == 1) {
789 		if (mp->m_ddev_targp->bt_awu_max ||
790 		    (mp->m_rtdev_targp && mp->m_rtdev_targp->bt_awu_max)) {
791 		} else {
792 			xfs_warn(mp,
793  "cannot support atomic writes of size %lluk with no reflink or HW support",
794 				new_max_bytes >> 10);
795 			return -EINVAL;
796 		}
797 	} else {
798 		xfs_warn(mp,
799  "cannot support atomic writes of size %lluk with no reflink support",
800 				new_max_bytes >> 10);
801 		return -EINVAL;
802 	}
803 
804 set_limit:
805 	error = xfs_calc_atomic_write_reservation(mp, new_max_fsbs);
806 	if (error) {
807 		xfs_warn(mp,
808  "cannot support completing atomic writes of %lluk",
809 				new_max_bytes >> 10);
810 		return error;
811 	}
812 
813 	xfs_calc_atomic_write_unit_max(mp, XG_TYPE_AG);
814 	xfs_calc_atomic_write_unit_max(mp, XG_TYPE_RTG);
815 	mp->m_awu_max_bytes = new_max_bytes;
816 	return 0;
817 }
818 
819 /* Compute maximum possible height for realtime btree types for this fs. */
820 static inline void
xfs_rtbtree_compute_maxlevels(struct xfs_mount * mp)821 xfs_rtbtree_compute_maxlevels(
822 	struct xfs_mount	*mp)
823 {
824 	mp->m_rtbtree_maxlevels = max(mp->m_rtrmap_maxlevels,
825 				      mp->m_rtrefc_maxlevels);
826 }
827 
828 /*
829  * This function does the following on an initial mount of a file system:
830  *	- reads the superblock from disk and init the mount struct
831  *	- if we're a 32-bit kernel, do a size check on the superblock
832  *		so we don't mount terabyte filesystems
833  *	- init mount struct realtime fields
834  *	- allocate inode hash table for fs
835  *	- init directory manager
836  *	- perform recovery and init the log manager
837  */
838 int
xfs_mountfs(struct xfs_mount * mp)839 xfs_mountfs(
840 	struct xfs_mount	*mp)
841 {
842 	struct xfs_sb		*sbp = &(mp->m_sb);
843 	struct xfs_inode	*rip;
844 	struct xfs_ino_geometry	*igeo = M_IGEO(mp);
845 	uint			quotamount = 0;
846 	uint			quotaflags = 0;
847 	int			error = 0;
848 	int			i;
849 
850 	xfs_sb_mount_common(mp, sbp);
851 
852 	/*
853 	 * Check for a mismatched features2 values.  Older kernels read & wrote
854 	 * into the wrong sb offset for sb_features2 on some platforms due to
855 	 * xfs_sb_t not being 64bit size aligned when sb_features2 was added,
856 	 * which made older superblock reading/writing routines swap it as a
857 	 * 64-bit value.
858 	 *
859 	 * For backwards compatibility, we make both slots equal.
860 	 *
861 	 * If we detect a mismatched field, we OR the set bits into the existing
862 	 * features2 field in case it has already been modified; we don't want
863 	 * to lose any features.  We then update the bad location with the ORed
864 	 * value so that older kernels will see any features2 flags. The
865 	 * superblock writeback code ensures the new sb_features2 is copied to
866 	 * sb_bad_features2 before it is logged or written to disk.
867 	 */
868 	if (xfs_sb_has_mismatched_features2(sbp)) {
869 		xfs_warn(mp, "correcting sb_features alignment problem");
870 		sbp->sb_features2 |= sbp->sb_bad_features2;
871 		mp->m_update_sb = true;
872 	}
873 
874 
875 	/* always use v2 inodes by default now */
876 	if (!(mp->m_sb.sb_versionnum & XFS_SB_VERSION_NLINKBIT)) {
877 		mp->m_sb.sb_versionnum |= XFS_SB_VERSION_NLINKBIT;
878 		mp->m_features |= XFS_FEAT_NLINK;
879 		mp->m_update_sb = true;
880 	}
881 
882 	/*
883 	 * If we were given new sunit/swidth options, do some basic validation
884 	 * checks and convert the incore dalign and swidth values to the
885 	 * same units (FSB) that everything else uses.  This /must/ happen
886 	 * before computing the inode geometry.
887 	 */
888 	error = xfs_validate_new_dalign(mp);
889 	if (error)
890 		goto out;
891 
892 	xfs_alloc_compute_maxlevels(mp);
893 	xfs_bmap_compute_maxlevels(mp, XFS_DATA_FORK);
894 	xfs_bmap_compute_maxlevels(mp, XFS_ATTR_FORK);
895 	xfs_mount_setup_inode_geom(mp);
896 	xfs_rmapbt_compute_maxlevels(mp);
897 	xfs_rtrmapbt_compute_maxlevels(mp);
898 	xfs_refcountbt_compute_maxlevels(mp);
899 	xfs_rtrefcountbt_compute_maxlevels(mp);
900 
901 	xfs_agbtree_compute_maxlevels(mp);
902 	xfs_rtbtree_compute_maxlevels(mp);
903 
904 	/*
905 	 * Check if sb_agblocks is aligned at stripe boundary.  If sb_agblocks
906 	 * is NOT aligned turn off m_dalign since allocator alignment is within
907 	 * an ag, therefore ag has to be aligned at stripe boundary.  Note that
908 	 * we must compute the free space and rmap btree geometry before doing
909 	 * this.
910 	 */
911 	error = xfs_update_alignment(mp);
912 	if (error)
913 		goto out;
914 
915 	/* enable fail_at_unmount as default */
916 	mp->m_fail_unmount = true;
917 
918 	error = xfs_mount_sysfs_init(mp);
919 	if (error)
920 		goto out_remove_scrub_stats;
921 
922 	xchk_stats_register(mp->m_scrub_stats, mp->m_debugfs);
923 
924 	error = xfs_errortag_init(mp);
925 	if (error)
926 		goto out_remove_sysfs;
927 
928 	error = xfs_uuid_mount(mp);
929 	if (error)
930 		goto out_remove_errortag;
931 
932 	/*
933 	 * Update the preferred write size based on the information from the
934 	 * on-disk superblock.
935 	 */
936 	mp->m_allocsize_log =
937 		max_t(uint32_t, sbp->sb_blocklog, mp->m_allocsize_log);
938 	mp->m_allocsize_blocks = 1U << (mp->m_allocsize_log - sbp->sb_blocklog);
939 
940 	/* set the low space thresholds for dynamic preallocation */
941 	xfs_set_low_space_thresholds(mp);
942 
943 	/*
944 	 * If enabled, sparse inode chunk alignment is expected to match the
945 	 * cluster size. Full inode chunk alignment must match the chunk size,
946 	 * but that is checked on sb read verification...
947 	 */
948 	if (xfs_has_sparseinodes(mp) &&
949 	    mp->m_sb.sb_spino_align !=
950 			XFS_B_TO_FSBT(mp, igeo->inode_cluster_size_raw)) {
951 		xfs_warn(mp,
952 	"Sparse inode block alignment (%u) must match cluster size (%llu).",
953 			 mp->m_sb.sb_spino_align,
954 			 XFS_B_TO_FSBT(mp, igeo->inode_cluster_size_raw));
955 		error = -EINVAL;
956 		goto out_remove_uuid;
957 	}
958 
959 	/*
960 	 * Check that the data (and log if separate) is an ok size.
961 	 */
962 	error = xfs_check_sizes(mp);
963 	if (error)
964 		goto out_remove_uuid;
965 
966 	/*
967 	 * Initialize realtime fields in the mount structure
968 	 */
969 	error = xfs_rtmount_init(mp);
970 	if (error) {
971 		xfs_warn(mp, "RT mount failed");
972 		goto out_remove_uuid;
973 	}
974 
975 	/*
976 	 *  Copies the low order bits of the timestamp and the randomly
977 	 *  set "sequence" number out of a UUID.
978 	 */
979 	mp->m_fixedfsid[0] =
980 		(get_unaligned_be16(&sbp->sb_uuid.b[8]) << 16) |
981 		 get_unaligned_be16(&sbp->sb_uuid.b[4]);
982 	mp->m_fixedfsid[1] = get_unaligned_be32(&sbp->sb_uuid.b[0]);
983 
984 	error = xfs_da_mount(mp);
985 	if (error) {
986 		xfs_warn(mp, "Failed dir/attr init: %d", error);
987 		goto out_remove_uuid;
988 	}
989 
990 	/*
991 	 * Initialize the precomputed transaction reservations values.
992 	 */
993 	xfs_trans_init(mp);
994 
995 	/*
996 	 * Allocate and initialize the per-ag data.
997 	 */
998 	error = xfs_initialize_perag(mp, 0, sbp->sb_agcount,
999 			mp->m_sb.sb_dblocks, &mp->m_maxagi);
1000 	if (error) {
1001 		xfs_warn(mp, "Failed per-ag init: %d", error);
1002 		goto out_free_dir;
1003 	}
1004 
1005 	error = xfs_initialize_rtgroups(mp, 0, sbp->sb_rgcount,
1006 			mp->m_sb.sb_rextents);
1007 	if (error) {
1008 		xfs_warn(mp, "Failed rtgroup init: %d", error);
1009 		goto out_free_perag;
1010 	}
1011 
1012 	if (XFS_IS_CORRUPT(mp, !sbp->sb_logblocks)) {
1013 		xfs_warn(mp, "no log defined");
1014 		error = -EFSCORRUPTED;
1015 		goto out_free_rtgroup;
1016 	}
1017 
1018 	error = xfs_inodegc_register_shrinker(mp);
1019 	if (error)
1020 		goto out_fail_wait;
1021 
1022 	/*
1023 	 * If we're resuming quota status, pick up the preliminary qflags from
1024 	 * the ondisk superblock so that we know if we should recover dquots.
1025 	 */
1026 	if (xfs_is_resuming_quotaon(mp))
1027 		xfs_qm_resume_quotaon(mp);
1028 
1029 	/*
1030 	 * Log's mount-time initialization. The first part of recovery can place
1031 	 * some items on the AIL, to be handled when recovery is finished or
1032 	 * cancelled.
1033 	 */
1034 	error = xfs_log_mount(mp, mp->m_logdev_targp,
1035 			      XFS_FSB_TO_DADDR(mp, sbp->sb_logstart),
1036 			      XFS_FSB_TO_BB(mp, sbp->sb_logblocks));
1037 	if (error) {
1038 		xfs_warn(mp, "log mount failed");
1039 		goto out_inodegc_shrinker;
1040 	}
1041 
1042 	/*
1043 	 * If we're resuming quota status and recovered the log, re-sample the
1044 	 * qflags from the ondisk superblock now that we've recovered it, just
1045 	 * in case someone shut down enforcement just before a crash.
1046 	 */
1047 	if (xfs_clear_resuming_quotaon(mp) && xlog_recovery_needed(mp->m_log))
1048 		xfs_qm_resume_quotaon(mp);
1049 
1050 	/*
1051 	 * If logged xattrs are still enabled after log recovery finishes, then
1052 	 * they'll be available until unmount.  Otherwise, turn them off.
1053 	 */
1054 	if (xfs_sb_version_haslogxattrs(&mp->m_sb))
1055 		xfs_set_using_logged_xattrs(mp);
1056 	else
1057 		xfs_clear_using_logged_xattrs(mp);
1058 
1059 	/* Enable background inode inactivation workers. */
1060 	xfs_inodegc_start(mp);
1061 	xfs_blockgc_start(mp);
1062 
1063 	if (xfs_has_metadir(mp)) {
1064 		error = xfs_mount_setup_metadir(mp);
1065 		if (error)
1066 			goto out_free_metadir;
1067 	}
1068 
1069 	/*
1070 	 * Get and sanity-check the root inode.
1071 	 * Save the pointer to it in the mount structure.
1072 	 */
1073 	error = xfs_iget(mp, NULL, sbp->sb_rootino, XFS_IGET_UNTRUSTED,
1074 			 XFS_ILOCK_EXCL, &rip);
1075 	if (error) {
1076 		xfs_warn(mp,
1077 			"Failed to read root inode 0x%llx, error %d",
1078 			sbp->sb_rootino, -error);
1079 		goto out_free_metadir;
1080 	}
1081 
1082 	ASSERT(rip != NULL);
1083 
1084 	if (XFS_IS_CORRUPT(mp, !S_ISDIR(VFS_I(rip)->i_mode))) {
1085 		xfs_warn(mp, "corrupted root inode %llu: not a directory",
1086 			(unsigned long long)rip->i_ino);
1087 		xfs_iunlock(rip, XFS_ILOCK_EXCL);
1088 		error = -EFSCORRUPTED;
1089 		goto out_rele_rip;
1090 	}
1091 	mp->m_rootip = rip;	/* save it */
1092 
1093 	xfs_iunlock(rip, XFS_ILOCK_EXCL);
1094 
1095 	/*
1096 	 * Initialize realtime inode pointers in the mount structure
1097 	 */
1098 	error = xfs_rtmount_inodes(mp);
1099 	if (error) {
1100 		/*
1101 		 * Free up the root inode.
1102 		 */
1103 		xfs_warn(mp, "failed to read RT inodes");
1104 		goto out_rele_rip;
1105 	}
1106 
1107 	/* Make sure the summary counts are ok. */
1108 	error = xfs_check_summary_counts(mp);
1109 	if (error)
1110 		goto out_rtunmount;
1111 
1112 	/*
1113 	 * If this is a read-only mount defer the superblock updates until
1114 	 * the next remount into writeable mode.  Otherwise we would never
1115 	 * perform the update e.g. for the root filesystem.
1116 	 */
1117 	if (mp->m_update_sb && !xfs_is_readonly(mp)) {
1118 		error = xfs_sync_sb(mp, false);
1119 		if (error) {
1120 			xfs_warn(mp, "failed to write sb changes");
1121 			goto out_rtunmount;
1122 		}
1123 	}
1124 
1125 	/*
1126 	 * Initialise the XFS quota management subsystem for this mount
1127 	 */
1128 	if (XFS_IS_QUOTA_ON(mp)) {
1129 		error = xfs_qm_newmount(mp, &quotamount, &quotaflags);
1130 		if (error)
1131 			goto out_rtunmount;
1132 	} else {
1133 		/*
1134 		 * If a file system had quotas running earlier, but decided to
1135 		 * mount without -o uquota/pquota/gquota options, revoke the
1136 		 * quotachecked license.
1137 		 */
1138 		if (mp->m_sb.sb_qflags & XFS_ALL_QUOTA_ACCT) {
1139 			xfs_notice(mp, "resetting quota flags");
1140 			error = xfs_mount_reset_sbqflags(mp);
1141 			if (error)
1142 				goto out_rtunmount;
1143 		}
1144 	}
1145 
1146 	/*
1147 	 * Finish recovering the file system.  This part needed to be delayed
1148 	 * until after the root and real-time bitmap inodes were consistently
1149 	 * read in.  Temporarily create per-AG space reservations for metadata
1150 	 * btree shape changes because space freeing transactions (for inode
1151 	 * inactivation) require the per-AG reservation in lieu of reserving
1152 	 * blocks.
1153 	 */
1154 	error = xfs_fs_reserve_ag_blocks(mp);
1155 	if (error && error == -ENOSPC)
1156 		xfs_warn(mp,
1157 	"ENOSPC reserving per-AG metadata pool, log recovery may fail.");
1158 	error = xfs_log_mount_finish(mp);
1159 	xfs_fs_unreserve_ag_blocks(mp);
1160 	if (error) {
1161 		xfs_warn(mp, "log mount finish failed");
1162 		goto out_rtunmount;
1163 	}
1164 
1165 	/*
1166 	 * Now the log is fully replayed, we can transition to full read-only
1167 	 * mode for read-only mounts. This will sync all the metadata and clean
1168 	 * the log so that the recovery we just performed does not have to be
1169 	 * replayed again on the next mount.
1170 	 *
1171 	 * We use the same quiesce mechanism as the rw->ro remount, as they are
1172 	 * semantically identical operations.
1173 	 */
1174 	if (xfs_is_readonly(mp) && !xfs_has_norecovery(mp))
1175 		xfs_log_clean(mp);
1176 
1177 	if (xfs_has_zoned(mp)) {
1178 		error = xfs_mount_zones(mp);
1179 		if (error)
1180 			goto out_rtunmount;
1181 	}
1182 
1183 	/*
1184 	 * Complete the quota initialisation, post-log-replay component.
1185 	 */
1186 	if (quotamount) {
1187 		ASSERT(mp->m_qflags == 0);
1188 		mp->m_qflags = quotaflags;
1189 
1190 		xfs_qm_mount_quotas(mp);
1191 	}
1192 
1193 	/*
1194 	 * Now we are mounted, reserve a small amount of unused space for
1195 	 * privileged transactions. This is needed so that transaction
1196 	 * space required for critical operations can dip into this pool
1197 	 * when at ENOSPC. This is needed for operations like create with
1198 	 * attr, unwritten extent conversion at ENOSPC, garbage collection
1199 	 * etc. Data allocations are not allowed to use this reserved space.
1200 	 *
1201 	 * This may drive us straight to ENOSPC on mount, but that implies
1202 	 * we were already there on the last unmount. Warn if this occurs.
1203 	 */
1204 	if (!xfs_is_readonly(mp)) {
1205 		for (i = 0; i < XC_FREE_NR; i++) {
1206 			error = xfs_reserve_blocks(mp, i,
1207 					xfs_default_resblks(mp, i));
1208 			if (error)
1209 				xfs_warn(mp,
1210 "Unable to allocate reserve blocks. Continuing without reserve pool for %s.",
1211 					xfs_free_pool_name[i]);
1212 		}
1213 
1214 		/* Reserve AG blocks for future btree expansion. */
1215 		error = xfs_fs_reserve_ag_blocks(mp);
1216 		if (error && error != -ENOSPC)
1217 			goto out_agresv;
1218 
1219 		xfs_zone_gc_start(mp);
1220 	}
1221 
1222 	/*
1223 	 * Pre-calculate atomic write unit max.  This involves computations
1224 	 * derived from transaction reservations, so we must do this after the
1225 	 * log is fully initialized.
1226 	 */
1227 	error = xfs_set_max_atomic_write_opt(mp, mp->m_awu_max_bytes);
1228 	if (error)
1229 		goto out_agresv;
1230 
1231 	return 0;
1232 
1233  out_agresv:
1234 	xfs_fs_unreserve_ag_blocks(mp);
1235 	xfs_qm_unmount_quotas(mp);
1236 	if (xfs_has_zoned(mp))
1237 		xfs_unmount_zones(mp);
1238  out_rtunmount:
1239 	xfs_rtunmount_inodes(mp);
1240  out_rele_rip:
1241 	xfs_irele(rip);
1242 	/* Clean out dquots that might be in memory after quotacheck. */
1243 	xfs_qm_unmount(mp);
1244  out_free_metadir:
1245 	if (mp->m_metadirip)
1246 		xfs_irele(mp->m_metadirip);
1247 
1248 	/*
1249 	 * Inactivate all inodes that might still be in memory after a log
1250 	 * intent recovery failure so that reclaim can free them.  Metadata
1251 	 * inodes and the root directory shouldn't need inactivation, but the
1252 	 * mount failed for some reason, so pull down all the state and flee.
1253 	 */
1254 	xfs_inodegc_flush(mp);
1255 
1256 	/*
1257 	 * Flush all inode reclamation work and flush the log.
1258 	 * We have to do this /after/ rtunmount and qm_unmount because those
1259 	 * two will have scheduled delayed reclaim for the rt/quota inodes.
1260 	 *
1261 	 * This is slightly different from the unmountfs call sequence
1262 	 * because we could be tearing down a partially set up mount.  In
1263 	 * particular, if log_mount_finish fails we bail out without calling
1264 	 * qm_unmount_quotas and therefore rely on qm_unmount to release the
1265 	 * quota inodes.
1266 	 */
1267 	xfs_unmount_flush_inodes(mp);
1268 	xfs_log_mount_cancel(mp);
1269  out_inodegc_shrinker:
1270 	shrinker_free(mp->m_inodegc_shrinker);
1271  out_fail_wait:
1272 	if (mp->m_logdev_targp && mp->m_logdev_targp != mp->m_ddev_targp)
1273 		xfs_buftarg_drain(mp->m_logdev_targp);
1274 	xfs_buftarg_drain(mp->m_ddev_targp);
1275  out_free_rtgroup:
1276 	xfs_free_rtgroups(mp, 0, mp->m_sb.sb_rgcount);
1277  out_free_perag:
1278 	xfs_free_perag_range(mp, 0, mp->m_sb.sb_agcount);
1279  out_free_dir:
1280 	xfs_da_unmount(mp);
1281  out_remove_uuid:
1282 	xfs_uuid_unmount(mp);
1283  out_remove_errortag:
1284 	xfs_errortag_del(mp);
1285  out_remove_sysfs:
1286 	xfs_mount_sysfs_del(mp);
1287  out_remove_scrub_stats:
1288 	xchk_stats_unregister(mp->m_scrub_stats);
1289  out:
1290 	return error;
1291 }
1292 
1293 /*
1294  * This flushes out the inodes,dquots and the superblock, unmounts the
1295  * log and makes sure that incore structures are freed.
1296  */
1297 void
xfs_unmountfs(struct xfs_mount * mp)1298 xfs_unmountfs(
1299 	struct xfs_mount	*mp)
1300 {
1301 	int			error;
1302 
1303 	/*
1304 	 * Perform all on-disk metadata updates required to inactivate inodes
1305 	 * that the VFS evicted earlier in the unmount process.  Freeing inodes
1306 	 * and discarding CoW fork preallocations can cause shape changes to
1307 	 * the free inode and refcount btrees, respectively, so we must finish
1308 	 * this before we discard the metadata space reservations.  Metadata
1309 	 * inodes and the root directory do not require inactivation.
1310 	 */
1311 	xfs_inodegc_flush(mp);
1312 
1313 	xfs_blockgc_stop(mp);
1314 	if (!test_bit(XFS_OPSTATE_READONLY, &mp->m_opstate))
1315 		xfs_zone_gc_stop(mp);
1316 	xfs_fs_unreserve_ag_blocks(mp);
1317 	xfs_qm_unmount_quotas(mp);
1318 	if (xfs_has_zoned(mp))
1319 		xfs_unmount_zones(mp);
1320 	xfs_rtunmount_inodes(mp);
1321 	xfs_irele(mp->m_rootip);
1322 	if (mp->m_metadirip)
1323 		xfs_irele(mp->m_metadirip);
1324 
1325 	xfs_unmount_flush_inodes(mp);
1326 
1327 	xfs_qm_unmount(mp);
1328 
1329 	/*
1330 	 * Unreserve any blocks we have so that when we unmount we don't account
1331 	 * the reserved free space as used. This is really only necessary for
1332 	 * lazy superblock counting because it trusts the incore superblock
1333 	 * counters to be absolutely correct on clean unmount.
1334 	 *
1335 	 * We don't bother correcting this elsewhere for lazy superblock
1336 	 * counting because on mount of an unclean filesystem we reconstruct the
1337 	 * correct counter value and this is irrelevant.
1338 	 *
1339 	 * For non-lazy counter filesystems, this doesn't matter at all because
1340 	 * we only every apply deltas to the superblock and hence the incore
1341 	 * value does not matter....
1342 	 */
1343 	error = xfs_reserve_blocks(mp, XC_FREE_BLOCKS, 0);
1344 	if (error)
1345 		xfs_warn(mp, "Unable to free reserved block pool. "
1346 				"Freespace may not be correct on next mount.");
1347 	xfs_unmount_check(mp);
1348 
1349 	/*
1350 	 * Indicate that it's ok to clear log incompat bits before cleaning
1351 	 * the log and writing the unmount record.
1352 	 */
1353 	xfs_set_done_with_log_incompat(mp);
1354 	xfs_log_unmount(mp);
1355 	xfs_da_unmount(mp);
1356 	xfs_uuid_unmount(mp);
1357 
1358 #if defined(DEBUG)
1359 	xfs_errortag_clearall(mp);
1360 #endif
1361 	shrinker_free(mp->m_inodegc_shrinker);
1362 	xfs_free_rtgroups(mp, 0, mp->m_sb.sb_rgcount);
1363 	xfs_free_perag_range(mp, 0, mp->m_sb.sb_agcount);
1364 	xfs_errortag_del(mp);
1365 	xchk_stats_unregister(mp->m_scrub_stats);
1366 	xfs_mount_sysfs_del(mp);
1367 }
1368 
1369 /*
1370  * Determine whether modifications can proceed. The caller specifies the minimum
1371  * freeze level for which modifications should not be allowed. This allows
1372  * certain operations to proceed while the freeze sequence is in progress, if
1373  * necessary.
1374  */
1375 bool
xfs_fs_writable(struct xfs_mount * mp,int level)1376 xfs_fs_writable(
1377 	struct xfs_mount	*mp,
1378 	int			level)
1379 {
1380 	ASSERT(level > SB_UNFROZEN);
1381 	if ((mp->m_super->s_writers.frozen >= level) ||
1382 	    xfs_is_shutdown(mp) || xfs_is_readonly(mp))
1383 		return false;
1384 
1385 	return true;
1386 }
1387 
1388 /*
1389  * Estimate the amount of free space that is not available to userspace and is
1390  * not explicitly reserved from the incore fdblocks.  This includes:
1391  *
1392  * - The minimum number of blocks needed to support splitting a bmap btree
1393  * - The blocks currently in use by the freespace btrees because they record
1394  *   the actual blocks that will fill per-AG metadata space reservations
1395  */
1396 uint64_t
xfs_freecounter_unavailable(struct xfs_mount * mp,enum xfs_free_counter ctr)1397 xfs_freecounter_unavailable(
1398 	struct xfs_mount	*mp,
1399 	enum xfs_free_counter	ctr)
1400 {
1401 	if (ctr != XC_FREE_BLOCKS)
1402 		return 0;
1403 	return mp->m_alloc_set_aside + atomic64_read(&mp->m_allocbt_blks);
1404 }
1405 
1406 void
xfs_add_freecounter(struct xfs_mount * mp,enum xfs_free_counter ctr,uint64_t delta)1407 xfs_add_freecounter(
1408 	struct xfs_mount	*mp,
1409 	enum xfs_free_counter	ctr,
1410 	uint64_t		delta)
1411 {
1412 	struct xfs_freecounter	*counter = &mp->m_free[ctr];
1413 	uint64_t		res_used;
1414 
1415 	/*
1416 	 * If the reserve pool is depleted, put blocks back into it first.
1417 	 * Most of the time the pool is full.
1418 	 */
1419 	if (likely(counter->res_avail == counter->res_total)) {
1420 		percpu_counter_add(&counter->count, delta);
1421 		return;
1422 	}
1423 
1424 	spin_lock(&mp->m_sb_lock);
1425 	res_used = counter->res_total - counter->res_avail;
1426 	if (res_used > delta) {
1427 		counter->res_avail += delta;
1428 	} else {
1429 		delta -= res_used;
1430 		counter->res_avail = counter->res_total;
1431 		percpu_counter_add(&counter->count, delta);
1432 	}
1433 	spin_unlock(&mp->m_sb_lock);
1434 }
1435 
1436 
1437 /* Adjust in-core free blocks or RT extents. */
1438 int
xfs_dec_freecounter(struct xfs_mount * mp,enum xfs_free_counter ctr,uint64_t delta,bool rsvd)1439 xfs_dec_freecounter(
1440 	struct xfs_mount	*mp,
1441 	enum xfs_free_counter	ctr,
1442 	uint64_t		delta,
1443 	bool			rsvd)
1444 {
1445 	struct xfs_freecounter	*counter = &mp->m_free[ctr];
1446 	s32			batch;
1447 
1448 	ASSERT(ctr < XC_FREE_NR);
1449 
1450 	/*
1451 	 * Taking blocks away, need to be more accurate the closer we
1452 	 * are to zero.
1453 	 *
1454 	 * If the counter has a value of less than 2 * max batch size,
1455 	 * then make everything serialise as we are real close to
1456 	 * ENOSPC.
1457 	 */
1458 	if (__percpu_counter_compare(&counter->count, 2 * XFS_FDBLOCKS_BATCH,
1459 				     XFS_FDBLOCKS_BATCH) < 0)
1460 		batch = 1;
1461 	else
1462 		batch = XFS_FDBLOCKS_BATCH;
1463 
1464 	/*
1465 	 * Set aside allocbt blocks because these blocks are tracked as free
1466 	 * space but not available for allocation. Technically this means that a
1467 	 * single reservation cannot consume all remaining free space, but the
1468 	 * ratio of allocbt blocks to usable free blocks should be rather small.
1469 	 * The tradeoff without this is that filesystems that maintain high
1470 	 * perag block reservations can over reserve physical block availability
1471 	 * and fail physical allocation, which leads to much more serious
1472 	 * problems (i.e. transaction abort, pagecache discards, etc.) than
1473 	 * slightly premature -ENOSPC.
1474 	 */
1475 	percpu_counter_add_batch(&counter->count, -((int64_t)delta), batch);
1476 	if (__percpu_counter_compare(&counter->count,
1477 			xfs_freecounter_unavailable(mp, ctr),
1478 			XFS_FDBLOCKS_BATCH) < 0) {
1479 		/*
1480 		 * Lock up the sb for dipping into reserves before releasing the
1481 		 * space that took us to ENOSPC.
1482 		 */
1483 		spin_lock(&mp->m_sb_lock);
1484 		percpu_counter_add(&counter->count, delta);
1485 		if (!rsvd)
1486 			goto fdblocks_enospc;
1487 		if (delta > counter->res_avail) {
1488 			if (ctr == XC_FREE_BLOCKS)
1489 				xfs_warn_once(mp,
1490 "Reserve blocks depleted! Consider increasing reserve pool size.");
1491 			goto fdblocks_enospc;
1492 		}
1493 		counter->res_avail -= delta;
1494 		trace_xfs_freecounter_reserved(mp, ctr, delta, _RET_IP_);
1495 		spin_unlock(&mp->m_sb_lock);
1496 	}
1497 
1498 	/* we had space! */
1499 	return 0;
1500 
1501 fdblocks_enospc:
1502 	trace_xfs_freecounter_enospc(mp, ctr, delta, _RET_IP_);
1503 	spin_unlock(&mp->m_sb_lock);
1504 	return -ENOSPC;
1505 }
1506 
1507 /*
1508  * Used to free the superblock along various error paths.
1509  */
1510 void
xfs_freesb(struct xfs_mount * mp)1511 xfs_freesb(
1512 	struct xfs_mount	*mp)
1513 {
1514 	struct xfs_buf		*bp = mp->m_sb_bp;
1515 
1516 	xfs_buf_lock(bp);
1517 	mp->m_sb_bp = NULL;
1518 	xfs_buf_relse(bp);
1519 }
1520 
1521 /*
1522  * If the underlying (data/log/rt) device is readonly, there are some
1523  * operations that cannot proceed.
1524  */
1525 int
xfs_dev_is_read_only(struct xfs_mount * mp,char * message)1526 xfs_dev_is_read_only(
1527 	struct xfs_mount	*mp,
1528 	char			*message)
1529 {
1530 	if (xfs_readonly_buftarg(mp->m_ddev_targp) ||
1531 	    xfs_readonly_buftarg(mp->m_logdev_targp) ||
1532 	    (mp->m_rtdev_targp && xfs_readonly_buftarg(mp->m_rtdev_targp))) {
1533 		xfs_notice(mp, "%s required on read-only device.", message);
1534 		xfs_notice(mp, "write access unavailable, cannot proceed.");
1535 		return -EROFS;
1536 	}
1537 	return 0;
1538 }
1539 
1540 /* Force the summary counters to be recalculated at next mount. */
1541 void
xfs_force_summary_recalc(struct xfs_mount * mp)1542 xfs_force_summary_recalc(
1543 	struct xfs_mount	*mp)
1544 {
1545 	if (!xfs_has_lazysbcount(mp))
1546 		return;
1547 
1548 	xfs_fs_mark_sick(mp, XFS_SICK_FS_COUNTERS);
1549 }
1550 
1551 /*
1552  * Enable a log incompat feature flag in the primary superblock.  The caller
1553  * cannot have any other transactions in progress.
1554  */
1555 int
xfs_add_incompat_log_feature(struct xfs_mount * mp,uint32_t feature)1556 xfs_add_incompat_log_feature(
1557 	struct xfs_mount	*mp,
1558 	uint32_t		feature)
1559 {
1560 	struct xfs_dsb		*dsb;
1561 	int			error;
1562 
1563 	ASSERT(hweight32(feature) == 1);
1564 	ASSERT(!(feature & XFS_SB_FEAT_INCOMPAT_LOG_UNKNOWN));
1565 
1566 	/*
1567 	 * Force the log to disk and kick the background AIL thread to reduce
1568 	 * the chances that the bwrite will stall waiting for the AIL to unpin
1569 	 * the primary superblock buffer.  This isn't a data integrity
1570 	 * operation, so we don't need a synchronous push.
1571 	 */
1572 	error = xfs_log_force(mp, XFS_LOG_SYNC);
1573 	if (error)
1574 		return error;
1575 	xfs_ail_push_all(mp->m_ail);
1576 
1577 	/*
1578 	 * Lock the primary superblock buffer to serialize all callers that
1579 	 * are trying to set feature bits.
1580 	 */
1581 	xfs_buf_lock(mp->m_sb_bp);
1582 	xfs_buf_hold(mp->m_sb_bp);
1583 
1584 	if (xfs_is_shutdown(mp)) {
1585 		error = -EIO;
1586 		goto rele;
1587 	}
1588 
1589 	if (xfs_sb_has_incompat_log_feature(&mp->m_sb, feature))
1590 		goto rele;
1591 
1592 	/*
1593 	 * Write the primary superblock to disk immediately, because we need
1594 	 * the log_incompat bit to be set in the primary super now to protect
1595 	 * the log items that we're going to commit later.
1596 	 */
1597 	dsb = mp->m_sb_bp->b_addr;
1598 	xfs_sb_to_disk(dsb, &mp->m_sb);
1599 	dsb->sb_features_log_incompat |= cpu_to_be32(feature);
1600 	error = xfs_bwrite(mp->m_sb_bp);
1601 	if (error)
1602 		goto shutdown;
1603 
1604 	/*
1605 	 * Add the feature bits to the incore superblock before we unlock the
1606 	 * buffer.
1607 	 */
1608 	xfs_sb_add_incompat_log_features(&mp->m_sb, feature);
1609 	xfs_buf_relse(mp->m_sb_bp);
1610 
1611 	/* Log the superblock to disk. */
1612 	return xfs_sync_sb(mp, false);
1613 shutdown:
1614 	xfs_force_shutdown(mp, SHUTDOWN_META_IO_ERROR);
1615 rele:
1616 	xfs_buf_relse(mp->m_sb_bp);
1617 	return error;
1618 }
1619 
1620 /*
1621  * Clear all the log incompat flags from the superblock.
1622  *
1623  * The caller cannot be in a transaction, must ensure that the log does not
1624  * contain any log items protected by any log incompat bit, and must ensure
1625  * that there are no other threads that depend on the state of the log incompat
1626  * feature flags in the primary super.
1627  *
1628  * Returns true if the superblock is dirty.
1629  */
1630 bool
xfs_clear_incompat_log_features(struct xfs_mount * mp)1631 xfs_clear_incompat_log_features(
1632 	struct xfs_mount	*mp)
1633 {
1634 	bool			ret = false;
1635 
1636 	if (!xfs_has_crc(mp) ||
1637 	    !xfs_sb_has_incompat_log_feature(&mp->m_sb,
1638 				XFS_SB_FEAT_INCOMPAT_LOG_ALL) ||
1639 	    xfs_is_shutdown(mp) ||
1640 	    !xfs_is_done_with_log_incompat(mp))
1641 		return false;
1642 
1643 	/*
1644 	 * Update the incore superblock.  We synchronize on the primary super
1645 	 * buffer lock to be consistent with the add function, though at least
1646 	 * in theory this shouldn't be necessary.
1647 	 */
1648 	xfs_buf_lock(mp->m_sb_bp);
1649 	xfs_buf_hold(mp->m_sb_bp);
1650 
1651 	if (xfs_sb_has_incompat_log_feature(&mp->m_sb,
1652 				XFS_SB_FEAT_INCOMPAT_LOG_ALL)) {
1653 		xfs_sb_remove_incompat_log_features(&mp->m_sb);
1654 		ret = true;
1655 	}
1656 
1657 	xfs_buf_relse(mp->m_sb_bp);
1658 	return ret;
1659 }
1660 
1661 /*
1662  * Update the in-core delayed block counter.
1663  *
1664  * We prefer to update the counter without having to take a spinlock for every
1665  * counter update (i.e. batching).  Each change to delayed allocation
1666  * reservations can change can easily exceed the default percpu counter
1667  * batching, so we use a larger batch factor here.
1668  *
1669  * Note that we don't currently have any callers requiring fast summation
1670  * (e.g. percpu_counter_read) so we can use a big batch value here.
1671  */
1672 #define XFS_DELALLOC_BATCH	(4096)
1673 void
xfs_mod_delalloc(struct xfs_inode * ip,int64_t data_delta,int64_t ind_delta)1674 xfs_mod_delalloc(
1675 	struct xfs_inode	*ip,
1676 	int64_t			data_delta,
1677 	int64_t			ind_delta)
1678 {
1679 	struct xfs_mount	*mp = ip->i_mount;
1680 
1681 	if (XFS_IS_REALTIME_INODE(ip)) {
1682 		percpu_counter_add_batch(&mp->m_delalloc_rtextents,
1683 				xfs_blen_to_rtbxlen(mp, data_delta),
1684 				XFS_DELALLOC_BATCH);
1685 		if (!ind_delta)
1686 			return;
1687 		data_delta = 0;
1688 	}
1689 	percpu_counter_add_batch(&mp->m_delalloc_blks, data_delta + ind_delta,
1690 			XFS_DELALLOC_BATCH);
1691 }
1692