xref: /linux/fs/xfs/xfs_mount.c (revision 4e0ae876f77bc01a7e77724dea57b4b82bd53244)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (c) 2000-2005 Silicon Graphics, Inc.
4  * All Rights Reserved.
5  */
6 #include "xfs.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_defer.h"
16 #include "xfs_da_format.h"
17 #include "xfs_da_btree.h"
18 #include "xfs_inode.h"
19 #include "xfs_dir2.h"
20 #include "xfs_ialloc.h"
21 #include "xfs_alloc.h"
22 #include "xfs_rtalloc.h"
23 #include "xfs_bmap.h"
24 #include "xfs_trans.h"
25 #include "xfs_trans_priv.h"
26 #include "xfs_log.h"
27 #include "xfs_error.h"
28 #include "xfs_quota.h"
29 #include "xfs_fsops.h"
30 #include "xfs_trace.h"
31 #include "xfs_icache.h"
32 #include "xfs_sysfs.h"
33 #include "xfs_rmap_btree.h"
34 #include "xfs_refcount_btree.h"
35 #include "xfs_reflink.h"
36 #include "xfs_extent_busy.h"
37 
38 
39 static DEFINE_MUTEX(xfs_uuid_table_mutex);
40 static int xfs_uuid_table_size;
41 static uuid_t *xfs_uuid_table;
42 
43 void
44 xfs_uuid_table_free(void)
45 {
46 	if (xfs_uuid_table_size == 0)
47 		return;
48 	kmem_free(xfs_uuid_table);
49 	xfs_uuid_table = NULL;
50 	xfs_uuid_table_size = 0;
51 }
52 
53 /*
54  * See if the UUID is unique among mounted XFS filesystems.
55  * Mount fails if UUID is nil or a FS with the same UUID is already mounted.
56  */
57 STATIC int
58 xfs_uuid_mount(
59 	struct xfs_mount	*mp)
60 {
61 	uuid_t			*uuid = &mp->m_sb.sb_uuid;
62 	int			hole, i;
63 
64 	/* Publish UUID in struct super_block */
65 	uuid_copy(&mp->m_super->s_uuid, uuid);
66 
67 	if (mp->m_flags & XFS_MOUNT_NOUUID)
68 		return 0;
69 
70 	if (uuid_is_null(uuid)) {
71 		xfs_warn(mp, "Filesystem has null UUID - can't mount");
72 		return -EINVAL;
73 	}
74 
75 	mutex_lock(&xfs_uuid_table_mutex);
76 	for (i = 0, hole = -1; i < xfs_uuid_table_size; i++) {
77 		if (uuid_is_null(&xfs_uuid_table[i])) {
78 			hole = i;
79 			continue;
80 		}
81 		if (uuid_equal(uuid, &xfs_uuid_table[i]))
82 			goto out_duplicate;
83 	}
84 
85 	if (hole < 0) {
86 		xfs_uuid_table = kmem_realloc(xfs_uuid_table,
87 			(xfs_uuid_table_size + 1) * sizeof(*xfs_uuid_table),
88 			KM_SLEEP);
89 		hole = xfs_uuid_table_size++;
90 	}
91 	xfs_uuid_table[hole] = *uuid;
92 	mutex_unlock(&xfs_uuid_table_mutex);
93 
94 	return 0;
95 
96  out_duplicate:
97 	mutex_unlock(&xfs_uuid_table_mutex);
98 	xfs_warn(mp, "Filesystem has duplicate UUID %pU - can't mount", uuid);
99 	return -EINVAL;
100 }
101 
102 STATIC void
103 xfs_uuid_unmount(
104 	struct xfs_mount	*mp)
105 {
106 	uuid_t			*uuid = &mp->m_sb.sb_uuid;
107 	int			i;
108 
109 	if (mp->m_flags & XFS_MOUNT_NOUUID)
110 		return;
111 
112 	mutex_lock(&xfs_uuid_table_mutex);
113 	for (i = 0; i < xfs_uuid_table_size; i++) {
114 		if (uuid_is_null(&xfs_uuid_table[i]))
115 			continue;
116 		if (!uuid_equal(uuid, &xfs_uuid_table[i]))
117 			continue;
118 		memset(&xfs_uuid_table[i], 0, sizeof(uuid_t));
119 		break;
120 	}
121 	ASSERT(i < xfs_uuid_table_size);
122 	mutex_unlock(&xfs_uuid_table_mutex);
123 }
124 
125 
126 STATIC void
127 __xfs_free_perag(
128 	struct rcu_head	*head)
129 {
130 	struct xfs_perag *pag = container_of(head, struct xfs_perag, rcu_head);
131 
132 	ASSERT(atomic_read(&pag->pag_ref) == 0);
133 	kmem_free(pag);
134 }
135 
136 /*
137  * Free up the per-ag resources associated with the mount structure.
138  */
139 STATIC void
140 xfs_free_perag(
141 	xfs_mount_t	*mp)
142 {
143 	xfs_agnumber_t	agno;
144 	struct xfs_perag *pag;
145 
146 	for (agno = 0; agno < mp->m_sb.sb_agcount; agno++) {
147 		spin_lock(&mp->m_perag_lock);
148 		pag = radix_tree_delete(&mp->m_perag_tree, agno);
149 		spin_unlock(&mp->m_perag_lock);
150 		ASSERT(pag);
151 		ASSERT(atomic_read(&pag->pag_ref) == 0);
152 		xfs_iunlink_destroy(pag);
153 		xfs_buf_hash_destroy(pag);
154 		mutex_destroy(&pag->pag_ici_reclaim_lock);
155 		call_rcu(&pag->rcu_head, __xfs_free_perag);
156 	}
157 }
158 
159 /*
160  * Check size of device based on the (data/realtime) block count.
161  * Note: this check is used by the growfs code as well as mount.
162  */
163 int
164 xfs_sb_validate_fsb_count(
165 	xfs_sb_t	*sbp,
166 	uint64_t	nblocks)
167 {
168 	ASSERT(PAGE_SHIFT >= sbp->sb_blocklog);
169 	ASSERT(sbp->sb_blocklog >= BBSHIFT);
170 
171 	/* Limited by ULONG_MAX of page cache index */
172 	if (nblocks >> (PAGE_SHIFT - sbp->sb_blocklog) > ULONG_MAX)
173 		return -EFBIG;
174 	return 0;
175 }
176 
177 int
178 xfs_initialize_perag(
179 	xfs_mount_t	*mp,
180 	xfs_agnumber_t	agcount,
181 	xfs_agnumber_t	*maxagi)
182 {
183 	xfs_agnumber_t	index;
184 	xfs_agnumber_t	first_initialised = NULLAGNUMBER;
185 	xfs_perag_t	*pag;
186 	int		error = -ENOMEM;
187 
188 	/*
189 	 * Walk the current per-ag tree so we don't try to initialise AGs
190 	 * that already exist (growfs case). Allocate and insert all the
191 	 * AGs we don't find ready for initialisation.
192 	 */
193 	for (index = 0; index < agcount; index++) {
194 		pag = xfs_perag_get(mp, index);
195 		if (pag) {
196 			xfs_perag_put(pag);
197 			continue;
198 		}
199 
200 		pag = kmem_zalloc(sizeof(*pag), KM_MAYFAIL);
201 		if (!pag)
202 			goto out_unwind_new_pags;
203 		pag->pag_agno = index;
204 		pag->pag_mount = mp;
205 		spin_lock_init(&pag->pag_ici_lock);
206 		mutex_init(&pag->pag_ici_reclaim_lock);
207 		INIT_RADIX_TREE(&pag->pag_ici_root, GFP_ATOMIC);
208 		if (xfs_buf_hash_init(pag))
209 			goto out_free_pag;
210 		init_waitqueue_head(&pag->pagb_wait);
211 		spin_lock_init(&pag->pagb_lock);
212 		pag->pagb_count = 0;
213 		pag->pagb_tree = RB_ROOT;
214 
215 		if (radix_tree_preload(GFP_NOFS))
216 			goto out_hash_destroy;
217 
218 		spin_lock(&mp->m_perag_lock);
219 		if (radix_tree_insert(&mp->m_perag_tree, index, pag)) {
220 			BUG();
221 			spin_unlock(&mp->m_perag_lock);
222 			radix_tree_preload_end();
223 			error = -EEXIST;
224 			goto out_hash_destroy;
225 		}
226 		spin_unlock(&mp->m_perag_lock);
227 		radix_tree_preload_end();
228 		/* first new pag is fully initialized */
229 		if (first_initialised == NULLAGNUMBER)
230 			first_initialised = index;
231 		error = xfs_iunlink_init(pag);
232 		if (error)
233 			goto out_hash_destroy;
234 	}
235 
236 	index = xfs_set_inode_alloc(mp, agcount);
237 
238 	if (maxagi)
239 		*maxagi = index;
240 
241 	mp->m_ag_prealloc_blocks = xfs_prealloc_blocks(mp);
242 	return 0;
243 
244 out_hash_destroy:
245 	xfs_buf_hash_destroy(pag);
246 out_free_pag:
247 	mutex_destroy(&pag->pag_ici_reclaim_lock);
248 	kmem_free(pag);
249 out_unwind_new_pags:
250 	/* unwind any prior newly initialized pags */
251 	for (index = first_initialised; index < agcount; index++) {
252 		pag = radix_tree_delete(&mp->m_perag_tree, index);
253 		if (!pag)
254 			break;
255 		xfs_buf_hash_destroy(pag);
256 		xfs_iunlink_destroy(pag);
257 		mutex_destroy(&pag->pag_ici_reclaim_lock);
258 		kmem_free(pag);
259 	}
260 	return error;
261 }
262 
263 /*
264  * xfs_readsb
265  *
266  * Does the initial read of the superblock.
267  */
268 int
269 xfs_readsb(
270 	struct xfs_mount *mp,
271 	int		flags)
272 {
273 	unsigned int	sector_size;
274 	struct xfs_buf	*bp;
275 	struct xfs_sb	*sbp = &mp->m_sb;
276 	int		error;
277 	int		loud = !(flags & XFS_MFSI_QUIET);
278 	const struct xfs_buf_ops *buf_ops;
279 
280 	ASSERT(mp->m_sb_bp == NULL);
281 	ASSERT(mp->m_ddev_targp != NULL);
282 
283 	/*
284 	 * For the initial read, we must guess at the sector
285 	 * size based on the block device.  It's enough to
286 	 * get the sb_sectsize out of the superblock and
287 	 * then reread with the proper length.
288 	 * We don't verify it yet, because it may not be complete.
289 	 */
290 	sector_size = xfs_getsize_buftarg(mp->m_ddev_targp);
291 	buf_ops = NULL;
292 
293 	/*
294 	 * Allocate a (locked) buffer to hold the superblock. This will be kept
295 	 * around at all times to optimize access to the superblock. Therefore,
296 	 * set XBF_NO_IOACCT to make sure it doesn't hold the buftarg count
297 	 * elevated.
298 	 */
299 reread:
300 	error = xfs_buf_read_uncached(mp->m_ddev_targp, XFS_SB_DADDR,
301 				      BTOBB(sector_size), XBF_NO_IOACCT, &bp,
302 				      buf_ops);
303 	if (error) {
304 		if (loud)
305 			xfs_warn(mp, "SB validate failed with error %d.", error);
306 		/* bad CRC means corrupted metadata */
307 		if (error == -EFSBADCRC)
308 			error = -EFSCORRUPTED;
309 		return error;
310 	}
311 
312 	/*
313 	 * Initialize the mount structure from the superblock.
314 	 */
315 	xfs_sb_from_disk(sbp, XFS_BUF_TO_SBP(bp));
316 
317 	/*
318 	 * If we haven't validated the superblock, do so now before we try
319 	 * to check the sector size and reread the superblock appropriately.
320 	 */
321 	if (sbp->sb_magicnum != XFS_SB_MAGIC) {
322 		if (loud)
323 			xfs_warn(mp, "Invalid superblock magic number");
324 		error = -EINVAL;
325 		goto release_buf;
326 	}
327 
328 	/*
329 	 * We must be able to do sector-sized and sector-aligned IO.
330 	 */
331 	if (sector_size > sbp->sb_sectsize) {
332 		if (loud)
333 			xfs_warn(mp, "device supports %u byte sectors (not %u)",
334 				sector_size, sbp->sb_sectsize);
335 		error = -ENOSYS;
336 		goto release_buf;
337 	}
338 
339 	if (buf_ops == NULL) {
340 		/*
341 		 * Re-read the superblock so the buffer is correctly sized,
342 		 * and properly verified.
343 		 */
344 		xfs_buf_relse(bp);
345 		sector_size = sbp->sb_sectsize;
346 		buf_ops = loud ? &xfs_sb_buf_ops : &xfs_sb_quiet_buf_ops;
347 		goto reread;
348 	}
349 
350 	xfs_reinit_percpu_counters(mp);
351 
352 	/* no need to be quiet anymore, so reset the buf ops */
353 	bp->b_ops = &xfs_sb_buf_ops;
354 
355 	mp->m_sb_bp = bp;
356 	xfs_buf_unlock(bp);
357 	return 0;
358 
359 release_buf:
360 	xfs_buf_relse(bp);
361 	return error;
362 }
363 
364 /*
365  * Update alignment values based on mount options and sb values
366  */
367 STATIC int
368 xfs_update_alignment(xfs_mount_t *mp)
369 {
370 	xfs_sb_t	*sbp = &(mp->m_sb);
371 
372 	if (mp->m_dalign) {
373 		/*
374 		 * If stripe unit and stripe width are not multiples
375 		 * of the fs blocksize turn off alignment.
376 		 */
377 		if ((BBTOB(mp->m_dalign) & mp->m_blockmask) ||
378 		    (BBTOB(mp->m_swidth) & mp->m_blockmask)) {
379 			xfs_warn(mp,
380 		"alignment check failed: sunit/swidth vs. blocksize(%d)",
381 				sbp->sb_blocksize);
382 			return -EINVAL;
383 		} else {
384 			/*
385 			 * Convert the stripe unit and width to FSBs.
386 			 */
387 			mp->m_dalign = XFS_BB_TO_FSBT(mp, mp->m_dalign);
388 			if (mp->m_dalign && (sbp->sb_agblocks % mp->m_dalign)) {
389 				xfs_warn(mp,
390 			"alignment check failed: sunit/swidth vs. agsize(%d)",
391 					 sbp->sb_agblocks);
392 				return -EINVAL;
393 			} else if (mp->m_dalign) {
394 				mp->m_swidth = XFS_BB_TO_FSBT(mp, mp->m_swidth);
395 			} else {
396 				xfs_warn(mp,
397 			"alignment check failed: sunit(%d) less than bsize(%d)",
398 					 mp->m_dalign, sbp->sb_blocksize);
399 				return -EINVAL;
400 			}
401 		}
402 
403 		/*
404 		 * Update superblock with new values
405 		 * and log changes
406 		 */
407 		if (xfs_sb_version_hasdalign(sbp)) {
408 			if (sbp->sb_unit != mp->m_dalign) {
409 				sbp->sb_unit = mp->m_dalign;
410 				mp->m_update_sb = true;
411 			}
412 			if (sbp->sb_width != mp->m_swidth) {
413 				sbp->sb_width = mp->m_swidth;
414 				mp->m_update_sb = true;
415 			}
416 		} else {
417 			xfs_warn(mp,
418 	"cannot change alignment: superblock does not support data alignment");
419 			return -EINVAL;
420 		}
421 	} else if ((mp->m_flags & XFS_MOUNT_NOALIGN) != XFS_MOUNT_NOALIGN &&
422 		    xfs_sb_version_hasdalign(&mp->m_sb)) {
423 			mp->m_dalign = sbp->sb_unit;
424 			mp->m_swidth = sbp->sb_width;
425 	}
426 
427 	return 0;
428 }
429 
430 /*
431  * Set the maximum inode count for this filesystem
432  */
433 STATIC void
434 xfs_set_maxicount(xfs_mount_t *mp)
435 {
436 	xfs_sb_t	*sbp = &(mp->m_sb);
437 	uint64_t	icount;
438 
439 	if (sbp->sb_imax_pct) {
440 		/*
441 		 * Make sure the maximum inode count is a multiple
442 		 * of the units we allocate inodes in.
443 		 */
444 		icount = sbp->sb_dblocks * sbp->sb_imax_pct;
445 		do_div(icount, 100);
446 		do_div(icount, mp->m_ialloc_blks);
447 		mp->m_maxicount = (icount * mp->m_ialloc_blks)  <<
448 				   sbp->sb_inopblog;
449 	} else {
450 		mp->m_maxicount = 0;
451 	}
452 }
453 
454 /*
455  * Set the default minimum read and write sizes unless
456  * already specified in a mount option.
457  * We use smaller I/O sizes when the file system
458  * is being used for NFS service (wsync mount option).
459  */
460 STATIC void
461 xfs_set_rw_sizes(xfs_mount_t *mp)
462 {
463 	xfs_sb_t	*sbp = &(mp->m_sb);
464 	int		readio_log, writeio_log;
465 
466 	if (!(mp->m_flags & XFS_MOUNT_DFLT_IOSIZE)) {
467 		if (mp->m_flags & XFS_MOUNT_WSYNC) {
468 			readio_log = XFS_WSYNC_READIO_LOG;
469 			writeio_log = XFS_WSYNC_WRITEIO_LOG;
470 		} else {
471 			readio_log = XFS_READIO_LOG_LARGE;
472 			writeio_log = XFS_WRITEIO_LOG_LARGE;
473 		}
474 	} else {
475 		readio_log = mp->m_readio_log;
476 		writeio_log = mp->m_writeio_log;
477 	}
478 
479 	if (sbp->sb_blocklog > readio_log) {
480 		mp->m_readio_log = sbp->sb_blocklog;
481 	} else {
482 		mp->m_readio_log = readio_log;
483 	}
484 	mp->m_readio_blocks = 1 << (mp->m_readio_log - sbp->sb_blocklog);
485 	if (sbp->sb_blocklog > writeio_log) {
486 		mp->m_writeio_log = sbp->sb_blocklog;
487 	} else {
488 		mp->m_writeio_log = writeio_log;
489 	}
490 	mp->m_writeio_blocks = 1 << (mp->m_writeio_log - sbp->sb_blocklog);
491 }
492 
493 /*
494  * precalculate the low space thresholds for dynamic speculative preallocation.
495  */
496 void
497 xfs_set_low_space_thresholds(
498 	struct xfs_mount	*mp)
499 {
500 	int i;
501 
502 	for (i = 0; i < XFS_LOWSP_MAX; i++) {
503 		uint64_t space = mp->m_sb.sb_dblocks;
504 
505 		do_div(space, 100);
506 		mp->m_low_space[i] = space * (i + 1);
507 	}
508 }
509 
510 
511 /*
512  * Set whether we're using inode alignment.
513  */
514 STATIC void
515 xfs_set_inoalignment(xfs_mount_t *mp)
516 {
517 	if (xfs_sb_version_hasalign(&mp->m_sb) &&
518 		mp->m_sb.sb_inoalignmt >= xfs_icluster_size_fsb(mp))
519 		mp->m_inoalign_mask = mp->m_sb.sb_inoalignmt - 1;
520 	else
521 		mp->m_inoalign_mask = 0;
522 	/*
523 	 * If we are using stripe alignment, check whether
524 	 * the stripe unit is a multiple of the inode alignment
525 	 */
526 	if (mp->m_dalign && mp->m_inoalign_mask &&
527 	    !(mp->m_dalign & mp->m_inoalign_mask))
528 		mp->m_sinoalign = mp->m_dalign;
529 	else
530 		mp->m_sinoalign = 0;
531 }
532 
533 /*
534  * Check that the data (and log if separate) is an ok size.
535  */
536 STATIC int
537 xfs_check_sizes(
538 	struct xfs_mount *mp)
539 {
540 	struct xfs_buf	*bp;
541 	xfs_daddr_t	d;
542 	int		error;
543 
544 	d = (xfs_daddr_t)XFS_FSB_TO_BB(mp, mp->m_sb.sb_dblocks);
545 	if (XFS_BB_TO_FSB(mp, d) != mp->m_sb.sb_dblocks) {
546 		xfs_warn(mp, "filesystem size mismatch detected");
547 		return -EFBIG;
548 	}
549 	error = xfs_buf_read_uncached(mp->m_ddev_targp,
550 					d - XFS_FSS_TO_BB(mp, 1),
551 					XFS_FSS_TO_BB(mp, 1), 0, &bp, NULL);
552 	if (error) {
553 		xfs_warn(mp, "last sector read failed");
554 		return error;
555 	}
556 	xfs_buf_relse(bp);
557 
558 	if (mp->m_logdev_targp == mp->m_ddev_targp)
559 		return 0;
560 
561 	d = (xfs_daddr_t)XFS_FSB_TO_BB(mp, mp->m_sb.sb_logblocks);
562 	if (XFS_BB_TO_FSB(mp, d) != mp->m_sb.sb_logblocks) {
563 		xfs_warn(mp, "log size mismatch detected");
564 		return -EFBIG;
565 	}
566 	error = xfs_buf_read_uncached(mp->m_logdev_targp,
567 					d - XFS_FSB_TO_BB(mp, 1),
568 					XFS_FSB_TO_BB(mp, 1), 0, &bp, NULL);
569 	if (error) {
570 		xfs_warn(mp, "log device read failed");
571 		return error;
572 	}
573 	xfs_buf_relse(bp);
574 	return 0;
575 }
576 
577 /*
578  * Clear the quotaflags in memory and in the superblock.
579  */
580 int
581 xfs_mount_reset_sbqflags(
582 	struct xfs_mount	*mp)
583 {
584 	mp->m_qflags = 0;
585 
586 	/* It is OK to look at sb_qflags in the mount path without m_sb_lock. */
587 	if (mp->m_sb.sb_qflags == 0)
588 		return 0;
589 	spin_lock(&mp->m_sb_lock);
590 	mp->m_sb.sb_qflags = 0;
591 	spin_unlock(&mp->m_sb_lock);
592 
593 	if (!xfs_fs_writable(mp, SB_FREEZE_WRITE))
594 		return 0;
595 
596 	return xfs_sync_sb(mp, false);
597 }
598 
599 uint64_t
600 xfs_default_resblks(xfs_mount_t *mp)
601 {
602 	uint64_t resblks;
603 
604 	/*
605 	 * We default to 5% or 8192 fsbs of space reserved, whichever is
606 	 * smaller.  This is intended to cover concurrent allocation
607 	 * transactions when we initially hit enospc. These each require a 4
608 	 * block reservation. Hence by default we cover roughly 2000 concurrent
609 	 * allocation reservations.
610 	 */
611 	resblks = mp->m_sb.sb_dblocks;
612 	do_div(resblks, 20);
613 	resblks = min_t(uint64_t, resblks, 8192);
614 	return resblks;
615 }
616 
617 /* Ensure the summary counts are correct. */
618 STATIC int
619 xfs_check_summary_counts(
620 	struct xfs_mount	*mp)
621 {
622 	/*
623 	 * The AG0 superblock verifier rejects in-progress filesystems,
624 	 * so we should never see the flag set this far into mounting.
625 	 */
626 	if (mp->m_sb.sb_inprogress) {
627 		xfs_err(mp, "sb_inprogress set after log recovery??");
628 		WARN_ON(1);
629 		return -EFSCORRUPTED;
630 	}
631 
632 	/*
633 	 * Now the log is mounted, we know if it was an unclean shutdown or
634 	 * not. If it was, with the first phase of recovery has completed, we
635 	 * have consistent AG blocks on disk. We have not recovered EFIs yet,
636 	 * but they are recovered transactionally in the second recovery phase
637 	 * later.
638 	 *
639 	 * If the log was clean when we mounted, we can check the summary
640 	 * counters.  If any of them are obviously incorrect, we can recompute
641 	 * them from the AGF headers in the next step.
642 	 */
643 	if (XFS_LAST_UNMOUNT_WAS_CLEAN(mp) &&
644 	    (mp->m_sb.sb_fdblocks > mp->m_sb.sb_dblocks ||
645 	     !xfs_verify_icount(mp, mp->m_sb.sb_icount) ||
646 	     mp->m_sb.sb_ifree > mp->m_sb.sb_icount))
647 		mp->m_flags |= XFS_MOUNT_BAD_SUMMARY;
648 
649 	/*
650 	 * We can safely re-initialise incore superblock counters from the
651 	 * per-ag data. These may not be correct if the filesystem was not
652 	 * cleanly unmounted, so we waited for recovery to finish before doing
653 	 * this.
654 	 *
655 	 * If the filesystem was cleanly unmounted or the previous check did
656 	 * not flag anything weird, then we can trust the values in the
657 	 * superblock to be correct and we don't need to do anything here.
658 	 * Otherwise, recalculate the summary counters.
659 	 */
660 	if ((!xfs_sb_version_haslazysbcount(&mp->m_sb) ||
661 	     XFS_LAST_UNMOUNT_WAS_CLEAN(mp)) &&
662 	    !(mp->m_flags & XFS_MOUNT_BAD_SUMMARY))
663 		return 0;
664 
665 	return xfs_initialize_perag_data(mp, mp->m_sb.sb_agcount);
666 }
667 
668 /*
669  * This function does the following on an initial mount of a file system:
670  *	- reads the superblock from disk and init the mount struct
671  *	- if we're a 32-bit kernel, do a size check on the superblock
672  *		so we don't mount terabyte filesystems
673  *	- init mount struct realtime fields
674  *	- allocate inode hash table for fs
675  *	- init directory manager
676  *	- perform recovery and init the log manager
677  */
678 int
679 xfs_mountfs(
680 	struct xfs_mount	*mp)
681 {
682 	struct xfs_sb		*sbp = &(mp->m_sb);
683 	struct xfs_inode	*rip;
684 	uint64_t		resblks;
685 	uint			quotamount = 0;
686 	uint			quotaflags = 0;
687 	int			error = 0;
688 
689 	xfs_sb_mount_common(mp, sbp);
690 
691 	/*
692 	 * Check for a mismatched features2 values.  Older kernels read & wrote
693 	 * into the wrong sb offset for sb_features2 on some platforms due to
694 	 * xfs_sb_t not being 64bit size aligned when sb_features2 was added,
695 	 * which made older superblock reading/writing routines swap it as a
696 	 * 64-bit value.
697 	 *
698 	 * For backwards compatibility, we make both slots equal.
699 	 *
700 	 * If we detect a mismatched field, we OR the set bits into the existing
701 	 * features2 field in case it has already been modified; we don't want
702 	 * to lose any features.  We then update the bad location with the ORed
703 	 * value so that older kernels will see any features2 flags. The
704 	 * superblock writeback code ensures the new sb_features2 is copied to
705 	 * sb_bad_features2 before it is logged or written to disk.
706 	 */
707 	if (xfs_sb_has_mismatched_features2(sbp)) {
708 		xfs_warn(mp, "correcting sb_features alignment problem");
709 		sbp->sb_features2 |= sbp->sb_bad_features2;
710 		mp->m_update_sb = true;
711 
712 		/*
713 		 * Re-check for ATTR2 in case it was found in bad_features2
714 		 * slot.
715 		 */
716 		if (xfs_sb_version_hasattr2(&mp->m_sb) &&
717 		   !(mp->m_flags & XFS_MOUNT_NOATTR2))
718 			mp->m_flags |= XFS_MOUNT_ATTR2;
719 	}
720 
721 	if (xfs_sb_version_hasattr2(&mp->m_sb) &&
722 	   (mp->m_flags & XFS_MOUNT_NOATTR2)) {
723 		xfs_sb_version_removeattr2(&mp->m_sb);
724 		mp->m_update_sb = true;
725 
726 		/* update sb_versionnum for the clearing of the morebits */
727 		if (!sbp->sb_features2)
728 			mp->m_update_sb = true;
729 	}
730 
731 	/* always use v2 inodes by default now */
732 	if (!(mp->m_sb.sb_versionnum & XFS_SB_VERSION_NLINKBIT)) {
733 		mp->m_sb.sb_versionnum |= XFS_SB_VERSION_NLINKBIT;
734 		mp->m_update_sb = true;
735 	}
736 
737 	/*
738 	 * Check if sb_agblocks is aligned at stripe boundary
739 	 * If sb_agblocks is NOT aligned turn off m_dalign since
740 	 * allocator alignment is within an ag, therefore ag has
741 	 * to be aligned at stripe boundary.
742 	 */
743 	error = xfs_update_alignment(mp);
744 	if (error)
745 		goto out;
746 
747 	xfs_alloc_compute_maxlevels(mp);
748 	xfs_bmap_compute_maxlevels(mp, XFS_DATA_FORK);
749 	xfs_bmap_compute_maxlevels(mp, XFS_ATTR_FORK);
750 	xfs_ialloc_compute_maxlevels(mp);
751 	xfs_rmapbt_compute_maxlevels(mp);
752 	xfs_refcountbt_compute_maxlevels(mp);
753 
754 	xfs_set_maxicount(mp);
755 
756 	/* enable fail_at_unmount as default */
757 	mp->m_fail_unmount = true;
758 
759 	error = xfs_sysfs_init(&mp->m_kobj, &xfs_mp_ktype, NULL, mp->m_fsname);
760 	if (error)
761 		goto out;
762 
763 	error = xfs_sysfs_init(&mp->m_stats.xs_kobj, &xfs_stats_ktype,
764 			       &mp->m_kobj, "stats");
765 	if (error)
766 		goto out_remove_sysfs;
767 
768 	error = xfs_error_sysfs_init(mp);
769 	if (error)
770 		goto out_del_stats;
771 
772 	error = xfs_errortag_init(mp);
773 	if (error)
774 		goto out_remove_error_sysfs;
775 
776 	error = xfs_uuid_mount(mp);
777 	if (error)
778 		goto out_remove_errortag;
779 
780 	/*
781 	 * Set the minimum read and write sizes
782 	 */
783 	xfs_set_rw_sizes(mp);
784 
785 	/* set the low space thresholds for dynamic preallocation */
786 	xfs_set_low_space_thresholds(mp);
787 
788 	/*
789 	 * Set the inode cluster size.
790 	 * This may still be overridden by the file system
791 	 * block size if it is larger than the chosen cluster size.
792 	 *
793 	 * For v5 filesystems, scale the cluster size with the inode size to
794 	 * keep a constant ratio of inode per cluster buffer, but only if mkfs
795 	 * has set the inode alignment value appropriately for larger cluster
796 	 * sizes.
797 	 */
798 	mp->m_inode_cluster_size = XFS_INODE_BIG_CLUSTER_SIZE;
799 	if (xfs_sb_version_hascrc(&mp->m_sb)) {
800 		int	new_size = mp->m_inode_cluster_size;
801 
802 		new_size *= mp->m_sb.sb_inodesize / XFS_DINODE_MIN_SIZE;
803 		if (mp->m_sb.sb_inoalignmt >= XFS_B_TO_FSBT(mp, new_size))
804 			mp->m_inode_cluster_size = new_size;
805 	}
806 	mp->m_blocks_per_cluster = xfs_icluster_size_fsb(mp);
807 	mp->m_inodes_per_cluster = XFS_FSB_TO_INO(mp, mp->m_blocks_per_cluster);
808 	mp->m_cluster_align = xfs_ialloc_cluster_alignment(mp);
809 	mp->m_cluster_align_inodes = XFS_FSB_TO_INO(mp, mp->m_cluster_align);
810 
811 	/*
812 	 * If enabled, sparse inode chunk alignment is expected to match the
813 	 * cluster size. Full inode chunk alignment must match the chunk size,
814 	 * but that is checked on sb read verification...
815 	 */
816 	if (xfs_sb_version_hassparseinodes(&mp->m_sb) &&
817 	    mp->m_sb.sb_spino_align !=
818 			XFS_B_TO_FSBT(mp, mp->m_inode_cluster_size)) {
819 		xfs_warn(mp,
820 	"Sparse inode block alignment (%u) must match cluster size (%llu).",
821 			 mp->m_sb.sb_spino_align,
822 			 XFS_B_TO_FSBT(mp, mp->m_inode_cluster_size));
823 		error = -EINVAL;
824 		goto out_remove_uuid;
825 	}
826 
827 	/*
828 	 * Set inode alignment fields
829 	 */
830 	xfs_set_inoalignment(mp);
831 
832 	/*
833 	 * Check that the data (and log if separate) is an ok size.
834 	 */
835 	error = xfs_check_sizes(mp);
836 	if (error)
837 		goto out_remove_uuid;
838 
839 	/*
840 	 * Initialize realtime fields in the mount structure
841 	 */
842 	error = xfs_rtmount_init(mp);
843 	if (error) {
844 		xfs_warn(mp, "RT mount failed");
845 		goto out_remove_uuid;
846 	}
847 
848 	/*
849 	 *  Copies the low order bits of the timestamp and the randomly
850 	 *  set "sequence" number out of a UUID.
851 	 */
852 	mp->m_fixedfsid[0] =
853 		(get_unaligned_be16(&sbp->sb_uuid.b[8]) << 16) |
854 		 get_unaligned_be16(&sbp->sb_uuid.b[4]);
855 	mp->m_fixedfsid[1] = get_unaligned_be32(&sbp->sb_uuid.b[0]);
856 
857 	error = xfs_da_mount(mp);
858 	if (error) {
859 		xfs_warn(mp, "Failed dir/attr init: %d", error);
860 		goto out_remove_uuid;
861 	}
862 
863 	/*
864 	 * Initialize the precomputed transaction reservations values.
865 	 */
866 	xfs_trans_init(mp);
867 
868 	/*
869 	 * Allocate and initialize the per-ag data.
870 	 */
871 	error = xfs_initialize_perag(mp, sbp->sb_agcount, &mp->m_maxagi);
872 	if (error) {
873 		xfs_warn(mp, "Failed per-ag init: %d", error);
874 		goto out_free_dir;
875 	}
876 
877 	if (!sbp->sb_logblocks) {
878 		xfs_warn(mp, "no log defined");
879 		XFS_ERROR_REPORT("xfs_mountfs", XFS_ERRLEVEL_LOW, mp);
880 		error = -EFSCORRUPTED;
881 		goto out_free_perag;
882 	}
883 
884 	/*
885 	 * Log's mount-time initialization. The first part of recovery can place
886 	 * some items on the AIL, to be handled when recovery is finished or
887 	 * cancelled.
888 	 */
889 	error = xfs_log_mount(mp, mp->m_logdev_targp,
890 			      XFS_FSB_TO_DADDR(mp, sbp->sb_logstart),
891 			      XFS_FSB_TO_BB(mp, sbp->sb_logblocks));
892 	if (error) {
893 		xfs_warn(mp, "log mount failed");
894 		goto out_fail_wait;
895 	}
896 
897 	/* Make sure the summary counts are ok. */
898 	error = xfs_check_summary_counts(mp);
899 	if (error)
900 		goto out_log_dealloc;
901 
902 	/*
903 	 * Get and sanity-check the root inode.
904 	 * Save the pointer to it in the mount structure.
905 	 */
906 	error = xfs_iget(mp, NULL, sbp->sb_rootino, XFS_IGET_UNTRUSTED,
907 			 XFS_ILOCK_EXCL, &rip);
908 	if (error) {
909 		xfs_warn(mp,
910 			"Failed to read root inode 0x%llx, error %d",
911 			sbp->sb_rootino, -error);
912 		goto out_log_dealloc;
913 	}
914 
915 	ASSERT(rip != NULL);
916 
917 	if (unlikely(!S_ISDIR(VFS_I(rip)->i_mode))) {
918 		xfs_warn(mp, "corrupted root inode %llu: not a directory",
919 			(unsigned long long)rip->i_ino);
920 		xfs_iunlock(rip, XFS_ILOCK_EXCL);
921 		XFS_ERROR_REPORT("xfs_mountfs_int(2)", XFS_ERRLEVEL_LOW,
922 				 mp);
923 		error = -EFSCORRUPTED;
924 		goto out_rele_rip;
925 	}
926 	mp->m_rootip = rip;	/* save it */
927 
928 	xfs_iunlock(rip, XFS_ILOCK_EXCL);
929 
930 	/*
931 	 * Initialize realtime inode pointers in the mount structure
932 	 */
933 	error = xfs_rtmount_inodes(mp);
934 	if (error) {
935 		/*
936 		 * Free up the root inode.
937 		 */
938 		xfs_warn(mp, "failed to read RT inodes");
939 		goto out_rele_rip;
940 	}
941 
942 	/*
943 	 * If this is a read-only mount defer the superblock updates until
944 	 * the next remount into writeable mode.  Otherwise we would never
945 	 * perform the update e.g. for the root filesystem.
946 	 */
947 	if (mp->m_update_sb && !(mp->m_flags & XFS_MOUNT_RDONLY)) {
948 		error = xfs_sync_sb(mp, false);
949 		if (error) {
950 			xfs_warn(mp, "failed to write sb changes");
951 			goto out_rtunmount;
952 		}
953 	}
954 
955 	/*
956 	 * Initialise the XFS quota management subsystem for this mount
957 	 */
958 	if (XFS_IS_QUOTA_RUNNING(mp)) {
959 		error = xfs_qm_newmount(mp, &quotamount, &quotaflags);
960 		if (error)
961 			goto out_rtunmount;
962 	} else {
963 		ASSERT(!XFS_IS_QUOTA_ON(mp));
964 
965 		/*
966 		 * If a file system had quotas running earlier, but decided to
967 		 * mount without -o uquota/pquota/gquota options, revoke the
968 		 * quotachecked license.
969 		 */
970 		if (mp->m_sb.sb_qflags & XFS_ALL_QUOTA_ACCT) {
971 			xfs_notice(mp, "resetting quota flags");
972 			error = xfs_mount_reset_sbqflags(mp);
973 			if (error)
974 				goto out_rtunmount;
975 		}
976 	}
977 
978 	/*
979 	 * Finish recovering the file system.  This part needed to be delayed
980 	 * until after the root and real-time bitmap inodes were consistently
981 	 * read in.
982 	 */
983 	error = xfs_log_mount_finish(mp);
984 	if (error) {
985 		xfs_warn(mp, "log mount finish failed");
986 		goto out_rtunmount;
987 	}
988 
989 	/*
990 	 * Now the log is fully replayed, we can transition to full read-only
991 	 * mode for read-only mounts. This will sync all the metadata and clean
992 	 * the log so that the recovery we just performed does not have to be
993 	 * replayed again on the next mount.
994 	 *
995 	 * We use the same quiesce mechanism as the rw->ro remount, as they are
996 	 * semantically identical operations.
997 	 */
998 	if ((mp->m_flags & (XFS_MOUNT_RDONLY|XFS_MOUNT_NORECOVERY)) ==
999 							XFS_MOUNT_RDONLY) {
1000 		xfs_quiesce_attr(mp);
1001 	}
1002 
1003 	/*
1004 	 * Complete the quota initialisation, post-log-replay component.
1005 	 */
1006 	if (quotamount) {
1007 		ASSERT(mp->m_qflags == 0);
1008 		mp->m_qflags = quotaflags;
1009 
1010 		xfs_qm_mount_quotas(mp);
1011 	}
1012 
1013 	/*
1014 	 * Now we are mounted, reserve a small amount of unused space for
1015 	 * privileged transactions. This is needed so that transaction
1016 	 * space required for critical operations can dip into this pool
1017 	 * when at ENOSPC. This is needed for operations like create with
1018 	 * attr, unwritten extent conversion at ENOSPC, etc. Data allocations
1019 	 * are not allowed to use this reserved space.
1020 	 *
1021 	 * This may drive us straight to ENOSPC on mount, but that implies
1022 	 * we were already there on the last unmount. Warn if this occurs.
1023 	 */
1024 	if (!(mp->m_flags & XFS_MOUNT_RDONLY)) {
1025 		resblks = xfs_default_resblks(mp);
1026 		error = xfs_reserve_blocks(mp, &resblks, NULL);
1027 		if (error)
1028 			xfs_warn(mp,
1029 	"Unable to allocate reserve blocks. Continuing without reserve pool.");
1030 
1031 		/* Recover any CoW blocks that never got remapped. */
1032 		error = xfs_reflink_recover_cow(mp);
1033 		if (error) {
1034 			xfs_err(mp,
1035 	"Error %d recovering leftover CoW allocations.", error);
1036 			xfs_force_shutdown(mp, SHUTDOWN_CORRUPT_INCORE);
1037 			goto out_quota;
1038 		}
1039 
1040 		/* Reserve AG blocks for future btree expansion. */
1041 		error = xfs_fs_reserve_ag_blocks(mp);
1042 		if (error && error != -ENOSPC)
1043 			goto out_agresv;
1044 	}
1045 
1046 	return 0;
1047 
1048  out_agresv:
1049 	xfs_fs_unreserve_ag_blocks(mp);
1050  out_quota:
1051 	xfs_qm_unmount_quotas(mp);
1052  out_rtunmount:
1053 	xfs_rtunmount_inodes(mp);
1054  out_rele_rip:
1055 	xfs_irele(rip);
1056 	/* Clean out dquots that might be in memory after quotacheck. */
1057 	xfs_qm_unmount(mp);
1058 	/*
1059 	 * Cancel all delayed reclaim work and reclaim the inodes directly.
1060 	 * We have to do this /after/ rtunmount and qm_unmount because those
1061 	 * two will have scheduled delayed reclaim for the rt/quota inodes.
1062 	 *
1063 	 * This is slightly different from the unmountfs call sequence
1064 	 * because we could be tearing down a partially set up mount.  In
1065 	 * particular, if log_mount_finish fails we bail out without calling
1066 	 * qm_unmount_quotas and therefore rely on qm_unmount to release the
1067 	 * quota inodes.
1068 	 */
1069 	cancel_delayed_work_sync(&mp->m_reclaim_work);
1070 	xfs_reclaim_inodes(mp, SYNC_WAIT);
1071  out_log_dealloc:
1072 	mp->m_flags |= XFS_MOUNT_UNMOUNTING;
1073 	xfs_log_mount_cancel(mp);
1074  out_fail_wait:
1075 	if (mp->m_logdev_targp && mp->m_logdev_targp != mp->m_ddev_targp)
1076 		xfs_wait_buftarg(mp->m_logdev_targp);
1077 	xfs_wait_buftarg(mp->m_ddev_targp);
1078  out_free_perag:
1079 	xfs_free_perag(mp);
1080  out_free_dir:
1081 	xfs_da_unmount(mp);
1082  out_remove_uuid:
1083 	xfs_uuid_unmount(mp);
1084  out_remove_errortag:
1085 	xfs_errortag_del(mp);
1086  out_remove_error_sysfs:
1087 	xfs_error_sysfs_del(mp);
1088  out_del_stats:
1089 	xfs_sysfs_del(&mp->m_stats.xs_kobj);
1090  out_remove_sysfs:
1091 	xfs_sysfs_del(&mp->m_kobj);
1092  out:
1093 	return error;
1094 }
1095 
1096 /*
1097  * This flushes out the inodes,dquots and the superblock, unmounts the
1098  * log and makes sure that incore structures are freed.
1099  */
1100 void
1101 xfs_unmountfs(
1102 	struct xfs_mount	*mp)
1103 {
1104 	uint64_t		resblks;
1105 	int			error;
1106 
1107 	xfs_icache_disable_reclaim(mp);
1108 	xfs_fs_unreserve_ag_blocks(mp);
1109 	xfs_qm_unmount_quotas(mp);
1110 	xfs_rtunmount_inodes(mp);
1111 	xfs_irele(mp->m_rootip);
1112 
1113 	/*
1114 	 * We can potentially deadlock here if we have an inode cluster
1115 	 * that has been freed has its buffer still pinned in memory because
1116 	 * the transaction is still sitting in a iclog. The stale inodes
1117 	 * on that buffer will have their flush locks held until the
1118 	 * transaction hits the disk and the callbacks run. the inode
1119 	 * flush takes the flush lock unconditionally and with nothing to
1120 	 * push out the iclog we will never get that unlocked. hence we
1121 	 * need to force the log first.
1122 	 */
1123 	xfs_log_force(mp, XFS_LOG_SYNC);
1124 
1125 	/*
1126 	 * Wait for all busy extents to be freed, including completion of
1127 	 * any discard operation.
1128 	 */
1129 	xfs_extent_busy_wait_all(mp);
1130 	flush_workqueue(xfs_discard_wq);
1131 
1132 	/*
1133 	 * We now need to tell the world we are unmounting. This will allow
1134 	 * us to detect that the filesystem is going away and we should error
1135 	 * out anything that we have been retrying in the background. This will
1136 	 * prevent neverending retries in AIL pushing from hanging the unmount.
1137 	 */
1138 	mp->m_flags |= XFS_MOUNT_UNMOUNTING;
1139 
1140 	/*
1141 	 * Flush all pending changes from the AIL.
1142 	 */
1143 	xfs_ail_push_all_sync(mp->m_ail);
1144 
1145 	/*
1146 	 * And reclaim all inodes.  At this point there should be no dirty
1147 	 * inodes and none should be pinned or locked, but use synchronous
1148 	 * reclaim just to be sure. We can stop background inode reclaim
1149 	 * here as well if it is still running.
1150 	 */
1151 	cancel_delayed_work_sync(&mp->m_reclaim_work);
1152 	xfs_reclaim_inodes(mp, SYNC_WAIT);
1153 
1154 	xfs_qm_unmount(mp);
1155 
1156 	/*
1157 	 * Unreserve any blocks we have so that when we unmount we don't account
1158 	 * the reserved free space as used. This is really only necessary for
1159 	 * lazy superblock counting because it trusts the incore superblock
1160 	 * counters to be absolutely correct on clean unmount.
1161 	 *
1162 	 * We don't bother correcting this elsewhere for lazy superblock
1163 	 * counting because on mount of an unclean filesystem we reconstruct the
1164 	 * correct counter value and this is irrelevant.
1165 	 *
1166 	 * For non-lazy counter filesystems, this doesn't matter at all because
1167 	 * we only every apply deltas to the superblock and hence the incore
1168 	 * value does not matter....
1169 	 */
1170 	resblks = 0;
1171 	error = xfs_reserve_blocks(mp, &resblks, NULL);
1172 	if (error)
1173 		xfs_warn(mp, "Unable to free reserved block pool. "
1174 				"Freespace may not be correct on next mount.");
1175 
1176 	error = xfs_log_sbcount(mp);
1177 	if (error)
1178 		xfs_warn(mp, "Unable to update superblock counters. "
1179 				"Freespace may not be correct on next mount.");
1180 
1181 
1182 	xfs_log_unmount(mp);
1183 	xfs_da_unmount(mp);
1184 	xfs_uuid_unmount(mp);
1185 
1186 #if defined(DEBUG)
1187 	xfs_errortag_clearall(mp);
1188 #endif
1189 	xfs_free_perag(mp);
1190 
1191 	xfs_errortag_del(mp);
1192 	xfs_error_sysfs_del(mp);
1193 	xfs_sysfs_del(&mp->m_stats.xs_kobj);
1194 	xfs_sysfs_del(&mp->m_kobj);
1195 }
1196 
1197 /*
1198  * Determine whether modifications can proceed. The caller specifies the minimum
1199  * freeze level for which modifications should not be allowed. This allows
1200  * certain operations to proceed while the freeze sequence is in progress, if
1201  * necessary.
1202  */
1203 bool
1204 xfs_fs_writable(
1205 	struct xfs_mount	*mp,
1206 	int			level)
1207 {
1208 	ASSERT(level > SB_UNFROZEN);
1209 	if ((mp->m_super->s_writers.frozen >= level) ||
1210 	    XFS_FORCED_SHUTDOWN(mp) || (mp->m_flags & XFS_MOUNT_RDONLY))
1211 		return false;
1212 
1213 	return true;
1214 }
1215 
1216 /*
1217  * xfs_log_sbcount
1218  *
1219  * Sync the superblock counters to disk.
1220  *
1221  * Note this code can be called during the process of freezing, so we use the
1222  * transaction allocator that does not block when the transaction subsystem is
1223  * in its frozen state.
1224  */
1225 int
1226 xfs_log_sbcount(xfs_mount_t *mp)
1227 {
1228 	/* allow this to proceed during the freeze sequence... */
1229 	if (!xfs_fs_writable(mp, SB_FREEZE_COMPLETE))
1230 		return 0;
1231 
1232 	/*
1233 	 * we don't need to do this if we are updating the superblock
1234 	 * counters on every modification.
1235 	 */
1236 	if (!xfs_sb_version_haslazysbcount(&mp->m_sb))
1237 		return 0;
1238 
1239 	return xfs_sync_sb(mp, true);
1240 }
1241 
1242 /*
1243  * Deltas for the inode count are +/-64, hence we use a large batch size
1244  * of 128 so we don't need to take the counter lock on every update.
1245  */
1246 #define XFS_ICOUNT_BATCH	128
1247 int
1248 xfs_mod_icount(
1249 	struct xfs_mount	*mp,
1250 	int64_t			delta)
1251 {
1252 	percpu_counter_add_batch(&mp->m_icount, delta, XFS_ICOUNT_BATCH);
1253 	if (__percpu_counter_compare(&mp->m_icount, 0, XFS_ICOUNT_BATCH) < 0) {
1254 		ASSERT(0);
1255 		percpu_counter_add(&mp->m_icount, -delta);
1256 		return -EINVAL;
1257 	}
1258 	return 0;
1259 }
1260 
1261 int
1262 xfs_mod_ifree(
1263 	struct xfs_mount	*mp,
1264 	int64_t			delta)
1265 {
1266 	percpu_counter_add(&mp->m_ifree, delta);
1267 	if (percpu_counter_compare(&mp->m_ifree, 0) < 0) {
1268 		ASSERT(0);
1269 		percpu_counter_add(&mp->m_ifree, -delta);
1270 		return -EINVAL;
1271 	}
1272 	return 0;
1273 }
1274 
1275 /*
1276  * Deltas for the block count can vary from 1 to very large, but lock contention
1277  * only occurs on frequent small block count updates such as in the delayed
1278  * allocation path for buffered writes (page a time updates). Hence we set
1279  * a large batch count (1024) to minimise global counter updates except when
1280  * we get near to ENOSPC and we have to be very accurate with our updates.
1281  */
1282 #define XFS_FDBLOCKS_BATCH	1024
1283 int
1284 xfs_mod_fdblocks(
1285 	struct xfs_mount	*mp,
1286 	int64_t			delta,
1287 	bool			rsvd)
1288 {
1289 	int64_t			lcounter;
1290 	long long		res_used;
1291 	s32			batch;
1292 
1293 	if (delta > 0) {
1294 		/*
1295 		 * If the reserve pool is depleted, put blocks back into it
1296 		 * first. Most of the time the pool is full.
1297 		 */
1298 		if (likely(mp->m_resblks == mp->m_resblks_avail)) {
1299 			percpu_counter_add(&mp->m_fdblocks, delta);
1300 			return 0;
1301 		}
1302 
1303 		spin_lock(&mp->m_sb_lock);
1304 		res_used = (long long)(mp->m_resblks - mp->m_resblks_avail);
1305 
1306 		if (res_used > delta) {
1307 			mp->m_resblks_avail += delta;
1308 		} else {
1309 			delta -= res_used;
1310 			mp->m_resblks_avail = mp->m_resblks;
1311 			percpu_counter_add(&mp->m_fdblocks, delta);
1312 		}
1313 		spin_unlock(&mp->m_sb_lock);
1314 		return 0;
1315 	}
1316 
1317 	/*
1318 	 * Taking blocks away, need to be more accurate the closer we
1319 	 * are to zero.
1320 	 *
1321 	 * If the counter has a value of less than 2 * max batch size,
1322 	 * then make everything serialise as we are real close to
1323 	 * ENOSPC.
1324 	 */
1325 	if (__percpu_counter_compare(&mp->m_fdblocks, 2 * XFS_FDBLOCKS_BATCH,
1326 				     XFS_FDBLOCKS_BATCH) < 0)
1327 		batch = 1;
1328 	else
1329 		batch = XFS_FDBLOCKS_BATCH;
1330 
1331 	percpu_counter_add_batch(&mp->m_fdblocks, delta, batch);
1332 	if (__percpu_counter_compare(&mp->m_fdblocks, mp->m_alloc_set_aside,
1333 				     XFS_FDBLOCKS_BATCH) >= 0) {
1334 		/* we had space! */
1335 		return 0;
1336 	}
1337 
1338 	/*
1339 	 * lock up the sb for dipping into reserves before releasing the space
1340 	 * that took us to ENOSPC.
1341 	 */
1342 	spin_lock(&mp->m_sb_lock);
1343 	percpu_counter_add(&mp->m_fdblocks, -delta);
1344 	if (!rsvd)
1345 		goto fdblocks_enospc;
1346 
1347 	lcounter = (long long)mp->m_resblks_avail + delta;
1348 	if (lcounter >= 0) {
1349 		mp->m_resblks_avail = lcounter;
1350 		spin_unlock(&mp->m_sb_lock);
1351 		return 0;
1352 	}
1353 	printk_once(KERN_WARNING
1354 		"Filesystem \"%s\": reserve blocks depleted! "
1355 		"Consider increasing reserve pool size.",
1356 		mp->m_fsname);
1357 fdblocks_enospc:
1358 	spin_unlock(&mp->m_sb_lock);
1359 	return -ENOSPC;
1360 }
1361 
1362 int
1363 xfs_mod_frextents(
1364 	struct xfs_mount	*mp,
1365 	int64_t			delta)
1366 {
1367 	int64_t			lcounter;
1368 	int			ret = 0;
1369 
1370 	spin_lock(&mp->m_sb_lock);
1371 	lcounter = mp->m_sb.sb_frextents + delta;
1372 	if (lcounter < 0)
1373 		ret = -ENOSPC;
1374 	else
1375 		mp->m_sb.sb_frextents = lcounter;
1376 	spin_unlock(&mp->m_sb_lock);
1377 	return ret;
1378 }
1379 
1380 /*
1381  * xfs_getsb() is called to obtain the buffer for the superblock.
1382  * The buffer is returned locked and read in from disk.
1383  * The buffer should be released with a call to xfs_brelse().
1384  *
1385  * If the flags parameter is BUF_TRYLOCK, then we'll only return
1386  * the superblock buffer if it can be locked without sleeping.
1387  * If it can't then we'll return NULL.
1388  */
1389 struct xfs_buf *
1390 xfs_getsb(
1391 	struct xfs_mount	*mp,
1392 	int			flags)
1393 {
1394 	struct xfs_buf		*bp = mp->m_sb_bp;
1395 
1396 	if (!xfs_buf_trylock(bp)) {
1397 		if (flags & XBF_TRYLOCK)
1398 			return NULL;
1399 		xfs_buf_lock(bp);
1400 	}
1401 
1402 	xfs_buf_hold(bp);
1403 	ASSERT(bp->b_flags & XBF_DONE);
1404 	return bp;
1405 }
1406 
1407 /*
1408  * Used to free the superblock along various error paths.
1409  */
1410 void
1411 xfs_freesb(
1412 	struct xfs_mount	*mp)
1413 {
1414 	struct xfs_buf		*bp = mp->m_sb_bp;
1415 
1416 	xfs_buf_lock(bp);
1417 	mp->m_sb_bp = NULL;
1418 	xfs_buf_relse(bp);
1419 }
1420 
1421 /*
1422  * If the underlying (data/log/rt) device is readonly, there are some
1423  * operations that cannot proceed.
1424  */
1425 int
1426 xfs_dev_is_read_only(
1427 	struct xfs_mount	*mp,
1428 	char			*message)
1429 {
1430 	if (xfs_readonly_buftarg(mp->m_ddev_targp) ||
1431 	    xfs_readonly_buftarg(mp->m_logdev_targp) ||
1432 	    (mp->m_rtdev_targp && xfs_readonly_buftarg(mp->m_rtdev_targp))) {
1433 		xfs_notice(mp, "%s required on read-only device.", message);
1434 		xfs_notice(mp, "write access unavailable, cannot proceed.");
1435 		return -EROFS;
1436 	}
1437 	return 0;
1438 }
1439 
1440 /* Force the summary counters to be recalculated at next mount. */
1441 void
1442 xfs_force_summary_recalc(
1443 	struct xfs_mount	*mp)
1444 {
1445 	if (!xfs_sb_version_haslazysbcount(&mp->m_sb))
1446 		return;
1447 
1448 	spin_lock(&mp->m_sb_lock);
1449 	mp->m_flags |= XFS_MOUNT_BAD_SUMMARY;
1450 	spin_unlock(&mp->m_sb_lock);
1451 }
1452