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