xfs: merge xfs_inum.h into xfs_format.h
[linux-2.6-microblaze.git] / fs / xfs / xfs_mount.c
1 /*
2  * Copyright (c) 2000-2005 Silicon Graphics, Inc.
3  * All Rights Reserved.
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License as
7  * published by the Free Software Foundation.
8  *
9  * This program is distributed in the hope that it would be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write the Free Software Foundation,
16  * Inc.,  51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
17  */
18 #include "xfs.h"
19 #include "xfs_fs.h"
20 #include "xfs_shared.h"
21 #include "xfs_format.h"
22 #include "xfs_log_format.h"
23 #include "xfs_trans_resv.h"
24 #include "xfs_bit.h"
25 #include "xfs_sb.h"
26 #include "xfs_mount.h"
27 #include "xfs_da_format.h"
28 #include "xfs_inode.h"
29 #include "xfs_dir2.h"
30 #include "xfs_ialloc.h"
31 #include "xfs_alloc.h"
32 #include "xfs_rtalloc.h"
33 #include "xfs_bmap.h"
34 #include "xfs_trans.h"
35 #include "xfs_trans_priv.h"
36 #include "xfs_log.h"
37 #include "xfs_error.h"
38 #include "xfs_quota.h"
39 #include "xfs_fsops.h"
40 #include "xfs_trace.h"
41 #include "xfs_icache.h"
42 #include "xfs_sysfs.h"
43
44
45 #ifdef HAVE_PERCPU_SB
46 STATIC void     xfs_icsb_balance_counter(xfs_mount_t *, xfs_sb_field_t,
47                                                 int);
48 STATIC void     xfs_icsb_balance_counter_locked(xfs_mount_t *, xfs_sb_field_t,
49                                                 int);
50 STATIC void     xfs_icsb_disable_counter(xfs_mount_t *, xfs_sb_field_t);
51 #else
52
53 #define xfs_icsb_balance_counter(mp, a, b)              do { } while (0)
54 #define xfs_icsb_balance_counter_locked(mp, a, b)       do { } while (0)
55 #endif
56
57 static DEFINE_MUTEX(xfs_uuid_table_mutex);
58 static int xfs_uuid_table_size;
59 static uuid_t *xfs_uuid_table;
60
61 /*
62  * See if the UUID is unique among mounted XFS filesystems.
63  * Mount fails if UUID is nil or a FS with the same UUID is already mounted.
64  */
65 STATIC int
66 xfs_uuid_mount(
67         struct xfs_mount        *mp)
68 {
69         uuid_t                  *uuid = &mp->m_sb.sb_uuid;
70         int                     hole, i;
71
72         if (mp->m_flags & XFS_MOUNT_NOUUID)
73                 return 0;
74
75         if (uuid_is_nil(uuid)) {
76                 xfs_warn(mp, "Filesystem has nil UUID - can't mount");
77                 return -EINVAL;
78         }
79
80         mutex_lock(&xfs_uuid_table_mutex);
81         for (i = 0, hole = -1; i < xfs_uuid_table_size; i++) {
82                 if (uuid_is_nil(&xfs_uuid_table[i])) {
83                         hole = i;
84                         continue;
85                 }
86                 if (uuid_equal(uuid, &xfs_uuid_table[i]))
87                         goto out_duplicate;
88         }
89
90         if (hole < 0) {
91                 xfs_uuid_table = kmem_realloc(xfs_uuid_table,
92                         (xfs_uuid_table_size + 1) * sizeof(*xfs_uuid_table),
93                         xfs_uuid_table_size  * sizeof(*xfs_uuid_table),
94                         KM_SLEEP);
95                 hole = xfs_uuid_table_size++;
96         }
97         xfs_uuid_table[hole] = *uuid;
98         mutex_unlock(&xfs_uuid_table_mutex);
99
100         return 0;
101
102  out_duplicate:
103         mutex_unlock(&xfs_uuid_table_mutex);
104         xfs_warn(mp, "Filesystem has duplicate UUID %pU - can't mount", uuid);
105         return -EINVAL;
106 }
107
108 STATIC void
109 xfs_uuid_unmount(
110         struct xfs_mount        *mp)
111 {
112         uuid_t                  *uuid = &mp->m_sb.sb_uuid;
113         int                     i;
114
115         if (mp->m_flags & XFS_MOUNT_NOUUID)
116                 return;
117
118         mutex_lock(&xfs_uuid_table_mutex);
119         for (i = 0; i < xfs_uuid_table_size; i++) {
120                 if (uuid_is_nil(&xfs_uuid_table[i]))
121                         continue;
122                 if (!uuid_equal(uuid, &xfs_uuid_table[i]))
123                         continue;
124                 memset(&xfs_uuid_table[i], 0, sizeof(uuid_t));
125                 break;
126         }
127         ASSERT(i < xfs_uuid_table_size);
128         mutex_unlock(&xfs_uuid_table_mutex);
129 }
130
131
132 STATIC void
133 __xfs_free_perag(
134         struct rcu_head *head)
135 {
136         struct xfs_perag *pag = container_of(head, struct xfs_perag, rcu_head);
137
138         ASSERT(atomic_read(&pag->pag_ref) == 0);
139         kmem_free(pag);
140 }
141
142 /*
143  * Free up the per-ag resources associated with the mount structure.
144  */
145 STATIC void
146 xfs_free_perag(
147         xfs_mount_t     *mp)
148 {
149         xfs_agnumber_t  agno;
150         struct xfs_perag *pag;
151
152         for (agno = 0; agno < mp->m_sb.sb_agcount; agno++) {
153                 spin_lock(&mp->m_perag_lock);
154                 pag = radix_tree_delete(&mp->m_perag_tree, agno);
155                 spin_unlock(&mp->m_perag_lock);
156                 ASSERT(pag);
157                 ASSERT(atomic_read(&pag->pag_ref) == 0);
158                 call_rcu(&pag->rcu_head, __xfs_free_perag);
159         }
160 }
161
162 /*
163  * Check size of device based on the (data/realtime) block count.
164  * Note: this check is used by the growfs code as well as mount.
165  */
166 int
167 xfs_sb_validate_fsb_count(
168         xfs_sb_t        *sbp,
169         __uint64_t      nblocks)
170 {
171         ASSERT(PAGE_SHIFT >= sbp->sb_blocklog);
172         ASSERT(sbp->sb_blocklog >= BBSHIFT);
173
174         /* Limited by ULONG_MAX of page cache index */
175         if (nblocks >> (PAGE_CACHE_SHIFT - sbp->sb_blocklog) > ULONG_MAX)
176                 return -EFBIG;
177         return 0;
178 }
179
180 int
181 xfs_initialize_perag(
182         xfs_mount_t     *mp,
183         xfs_agnumber_t  agcount,
184         xfs_agnumber_t  *maxagi)
185 {
186         xfs_agnumber_t  index;
187         xfs_agnumber_t  first_initialised = 0;
188         xfs_perag_t     *pag;
189         xfs_agino_t     agino;
190         xfs_ino_t       ino;
191         xfs_sb_t        *sbp = &mp->m_sb;
192         int             error = -ENOMEM;
193
194         /*
195          * Walk the current per-ag tree so we don't try to initialise AGs
196          * that already exist (growfs case). Allocate and insert all the
197          * AGs we don't find ready for initialisation.
198          */
199         for (index = 0; index < agcount; index++) {
200                 pag = xfs_perag_get(mp, index);
201                 if (pag) {
202                         xfs_perag_put(pag);
203                         continue;
204                 }
205                 if (!first_initialised)
206                         first_initialised = index;
207
208                 pag = kmem_zalloc(sizeof(*pag), KM_MAYFAIL);
209                 if (!pag)
210                         goto out_unwind;
211                 pag->pag_agno = index;
212                 pag->pag_mount = mp;
213                 spin_lock_init(&pag->pag_ici_lock);
214                 mutex_init(&pag->pag_ici_reclaim_lock);
215                 INIT_RADIX_TREE(&pag->pag_ici_root, GFP_ATOMIC);
216                 spin_lock_init(&pag->pag_buf_lock);
217                 pag->pag_buf_tree = RB_ROOT;
218
219                 if (radix_tree_preload(GFP_NOFS))
220                         goto out_unwind;
221
222                 spin_lock(&mp->m_perag_lock);
223                 if (radix_tree_insert(&mp->m_perag_tree, index, pag)) {
224                         BUG();
225                         spin_unlock(&mp->m_perag_lock);
226                         radix_tree_preload_end();
227                         error = -EEXIST;
228                         goto out_unwind;
229                 }
230                 spin_unlock(&mp->m_perag_lock);
231                 radix_tree_preload_end();
232         }
233
234         /*
235          * If we mount with the inode64 option, or no inode overflows
236          * the legacy 32-bit address space clear the inode32 option.
237          */
238         agino = XFS_OFFBNO_TO_AGINO(mp, sbp->sb_agblocks - 1, 0);
239         ino = XFS_AGINO_TO_INO(mp, agcount - 1, agino);
240
241         if ((mp->m_flags & XFS_MOUNT_SMALL_INUMS) && ino > XFS_MAXINUMBER_32)
242                 mp->m_flags |= XFS_MOUNT_32BITINODES;
243         else
244                 mp->m_flags &= ~XFS_MOUNT_32BITINODES;
245
246         if (mp->m_flags & XFS_MOUNT_32BITINODES)
247                 index = xfs_set_inode32(mp, agcount);
248         else
249                 index = xfs_set_inode64(mp, agcount);
250
251         if (maxagi)
252                 *maxagi = index;
253         return 0;
254
255 out_unwind:
256         kmem_free(pag);
257         for (; index > first_initialised; index--) {
258                 pag = radix_tree_delete(&mp->m_perag_tree, index);
259                 kmem_free(pag);
260         }
261         return error;
262 }
263
264 /*
265  * xfs_readsb
266  *
267  * Does the initial read of the superblock.
268  */
269 int
270 xfs_readsb(
271         struct xfs_mount *mp,
272         int             flags)
273 {
274         unsigned int    sector_size;
275         struct xfs_buf  *bp;
276         struct xfs_sb   *sbp = &mp->m_sb;
277         int             error;
278         int             loud = !(flags & XFS_MFSI_QUIET);
279         const struct xfs_buf_ops *buf_ops;
280
281         ASSERT(mp->m_sb_bp == NULL);
282         ASSERT(mp->m_ddev_targp != NULL);
283
284         /*
285          * For the initial read, we must guess at the sector
286          * size based on the block device.  It's enough to
287          * get the sb_sectsize out of the superblock and
288          * then reread with the proper length.
289          * We don't verify it yet, because it may not be complete.
290          */
291         sector_size = xfs_getsize_buftarg(mp->m_ddev_targp);
292         buf_ops = NULL;
293
294         /*
295          * Allocate a (locked) buffer to hold the superblock.
296          * This will be kept around at all times to optimize
297          * access to the superblock.
298          */
299 reread:
300         error = xfs_buf_read_uncached(mp->m_ddev_targp, XFS_SB_DADDR,
301                                    BTOBB(sector_size), 0, &bp, buf_ops);
302         if (error) {
303                 if (loud)
304                         xfs_warn(mp, "SB validate failed with error %d.", error);
305                 /* bad CRC means corrupted metadata */
306                 if (error == -EFSBADCRC)
307                         error = -EFSCORRUPTED;
308                 return error;
309         }
310
311         /*
312          * Initialize the mount structure from the superblock.
313          */
314         xfs_sb_from_disk(sbp, XFS_BUF_TO_SBP(bp));
315
316         /*
317          * If we haven't validated the superblock, do so now before we try
318          * to check the sector size and reread the superblock appropriately.
319          */
320         if (sbp->sb_magicnum != XFS_SB_MAGIC) {
321                 if (loud)
322                         xfs_warn(mp, "Invalid superblock magic number");
323                 error = -EINVAL;
324                 goto release_buf;
325         }
326
327         /*
328          * We must be able to do sector-sized and sector-aligned IO.
329          */
330         if (sector_size > sbp->sb_sectsize) {
331                 if (loud)
332                         xfs_warn(mp, "device supports %u byte sectors (not %u)",
333                                 sector_size, sbp->sb_sectsize);
334                 error = -ENOSYS;
335                 goto release_buf;
336         }
337
338         if (buf_ops == NULL) {
339                 /*
340                  * Re-read the superblock so the buffer is correctly sized,
341                  * and properly verified.
342                  */
343                 xfs_buf_relse(bp);
344                 sector_size = sbp->sb_sectsize;
345                 buf_ops = loud ? &xfs_sb_buf_ops : &xfs_sb_quiet_buf_ops;
346                 goto reread;
347         }
348
349         /* Initialize per-cpu counters */
350         xfs_icsb_reinit_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_flags |= XFS_SB_UNIT;
411                         }
412                         if (sbp->sb_width != mp->m_swidth) {
413                                 sbp->sb_width = mp->m_swidth;
414                                 mp->m_update_flags |= XFS_SB_WIDTH;
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 >=
519             XFS_B_TO_FSBT(mp, mp->m_inode_cluster_size))
520                 mp->m_inoalign_mask = mp->m_sb.sb_inoalignmt - 1;
521         else
522                 mp->m_inoalign_mask = 0;
523         /*
524          * If we are using stripe alignment, check whether
525          * the stripe unit is a multiple of the inode alignment
526          */
527         if (mp->m_dalign && mp->m_inoalign_mask &&
528             !(mp->m_dalign & mp->m_inoalign_mask))
529                 mp->m_sinoalign = mp->m_dalign;
530         else
531                 mp->m_sinoalign = 0;
532 }
533
534 /*
535  * Check that the data (and log if separate) is an ok size.
536  */
537 STATIC int
538 xfs_check_sizes(
539         struct xfs_mount *mp)
540 {
541         struct xfs_buf  *bp;
542         xfs_daddr_t     d;
543         int             error;
544
545         d = (xfs_daddr_t)XFS_FSB_TO_BB(mp, mp->m_sb.sb_dblocks);
546         if (XFS_BB_TO_FSB(mp, d) != mp->m_sb.sb_dblocks) {
547                 xfs_warn(mp, "filesystem size mismatch detected");
548                 return -EFBIG;
549         }
550         error = xfs_buf_read_uncached(mp->m_ddev_targp,
551                                         d - XFS_FSS_TO_BB(mp, 1),
552                                         XFS_FSS_TO_BB(mp, 1), 0, &bp, NULL);
553         if (error) {
554                 xfs_warn(mp, "last sector read failed");
555                 return error;
556         }
557         xfs_buf_relse(bp);
558
559         if (mp->m_logdev_targp == mp->m_ddev_targp)
560                 return 0;
561
562         d = (xfs_daddr_t)XFS_FSB_TO_BB(mp, mp->m_sb.sb_logblocks);
563         if (XFS_BB_TO_FSB(mp, d) != mp->m_sb.sb_logblocks) {
564                 xfs_warn(mp, "log size mismatch detected");
565                 return -EFBIG;
566         }
567         error = xfs_buf_read_uncached(mp->m_logdev_targp,
568                                         d - XFS_FSB_TO_BB(mp, 1),
569                                         XFS_FSB_TO_BB(mp, 1), 0, &bp, NULL);
570         if (error) {
571                 xfs_warn(mp, "log device read failed");
572                 return error;
573         }
574         xfs_buf_relse(bp);
575         return 0;
576 }
577
578 /*
579  * Clear the quotaflags in memory and in the superblock.
580  */
581 int
582 xfs_mount_reset_sbqflags(
583         struct xfs_mount        *mp)
584 {
585         int                     error;
586         struct xfs_trans        *tp;
587
588         mp->m_qflags = 0;
589
590         /*
591          * It is OK to look at sb_qflags here in mount path,
592          * without m_sb_lock.
593          */
594         if (mp->m_sb.sb_qflags == 0)
595                 return 0;
596         spin_lock(&mp->m_sb_lock);
597         mp->m_sb.sb_qflags = 0;
598         spin_unlock(&mp->m_sb_lock);
599
600         /*
601          * If the fs is readonly, let the incore superblock run
602          * with quotas off but don't flush the update out to disk
603          */
604         if (mp->m_flags & XFS_MOUNT_RDONLY)
605                 return 0;
606
607         tp = xfs_trans_alloc(mp, XFS_TRANS_QM_SBCHANGE);
608         error = xfs_trans_reserve(tp, &M_RES(mp)->tr_qm_sbchange, 0, 0);
609         if (error) {
610                 xfs_trans_cancel(tp, 0);
611                 xfs_alert(mp, "%s: Superblock update failed!", __func__);
612                 return error;
613         }
614
615         xfs_mod_sb(tp, XFS_SB_QFLAGS);
616         return xfs_trans_commit(tp, 0);
617 }
618
619 __uint64_t
620 xfs_default_resblks(xfs_mount_t *mp)
621 {
622         __uint64_t resblks;
623
624         /*
625          * We default to 5% or 8192 fsbs of space reserved, whichever is
626          * smaller.  This is intended to cover concurrent allocation
627          * transactions when we initially hit enospc. These each require a 4
628          * block reservation. Hence by default we cover roughly 2000 concurrent
629          * allocation reservations.
630          */
631         resblks = mp->m_sb.sb_dblocks;
632         do_div(resblks, 20);
633         resblks = min_t(__uint64_t, resblks, 8192);
634         return resblks;
635 }
636
637 /*
638  * This function does the following on an initial mount of a file system:
639  *      - reads the superblock from disk and init the mount struct
640  *      - if we're a 32-bit kernel, do a size check on the superblock
641  *              so we don't mount terabyte filesystems
642  *      - init mount struct realtime fields
643  *      - allocate inode hash table for fs
644  *      - init directory manager
645  *      - perform recovery and init the log manager
646  */
647 int
648 xfs_mountfs(
649         xfs_mount_t     *mp)
650 {
651         xfs_sb_t        *sbp = &(mp->m_sb);
652         xfs_inode_t     *rip;
653         __uint64_t      resblks;
654         uint            quotamount = 0;
655         uint            quotaflags = 0;
656         int             error = 0;
657
658         xfs_sb_mount_common(mp, sbp);
659
660         /*
661          * Check for a mismatched features2 values.  Older kernels
662          * read & wrote into the wrong sb offset for sb_features2
663          * on some platforms due to xfs_sb_t not being 64bit size aligned
664          * when sb_features2 was added, which made older superblock
665          * reading/writing routines swap it as a 64-bit value.
666          *
667          * For backwards compatibility, we make both slots equal.
668          *
669          * If we detect a mismatched field, we OR the set bits into the
670          * existing features2 field in case it has already been modified; we
671          * don't want to lose any features.  We then update the bad location
672          * with the ORed value so that older kernels will see any features2
673          * flags, and mark the two fields as needing updates once the
674          * transaction subsystem is online.
675          */
676         if (xfs_sb_has_mismatched_features2(sbp)) {
677                 xfs_warn(mp, "correcting sb_features alignment problem");
678                 sbp->sb_features2 |= sbp->sb_bad_features2;
679                 sbp->sb_bad_features2 = sbp->sb_features2;
680                 mp->m_update_flags |= XFS_SB_FEATURES2 | XFS_SB_BAD_FEATURES2;
681
682                 /*
683                  * Re-check for ATTR2 in case it was found in bad_features2
684                  * slot.
685                  */
686                 if (xfs_sb_version_hasattr2(&mp->m_sb) &&
687                    !(mp->m_flags & XFS_MOUNT_NOATTR2))
688                         mp->m_flags |= XFS_MOUNT_ATTR2;
689         }
690
691         if (xfs_sb_version_hasattr2(&mp->m_sb) &&
692            (mp->m_flags & XFS_MOUNT_NOATTR2)) {
693                 xfs_sb_version_removeattr2(&mp->m_sb);
694                 mp->m_update_flags |= XFS_SB_FEATURES2;
695
696                 /* update sb_versionnum for the clearing of the morebits */
697                 if (!sbp->sb_features2)
698                         mp->m_update_flags |= XFS_SB_VERSIONNUM;
699         }
700
701         /* always use v2 inodes by default now */
702         if (!(mp->m_sb.sb_versionnum & XFS_SB_VERSION_NLINKBIT)) {
703                 mp->m_sb.sb_versionnum |= XFS_SB_VERSION_NLINKBIT;
704                 mp->m_update_flags |= XFS_SB_VERSIONNUM;
705         }
706
707         /*
708          * Check if sb_agblocks is aligned at stripe boundary
709          * If sb_agblocks is NOT aligned turn off m_dalign since
710          * allocator alignment is within an ag, therefore ag has
711          * to be aligned at stripe boundary.
712          */
713         error = xfs_update_alignment(mp);
714         if (error)
715                 goto out;
716
717         xfs_alloc_compute_maxlevels(mp);
718         xfs_bmap_compute_maxlevels(mp, XFS_DATA_FORK);
719         xfs_bmap_compute_maxlevels(mp, XFS_ATTR_FORK);
720         xfs_ialloc_compute_maxlevels(mp);
721
722         xfs_set_maxicount(mp);
723
724         error = xfs_sysfs_init(&mp->m_kobj, &xfs_mp_ktype, NULL, mp->m_fsname);
725         if (error)
726                 goto out;
727
728         error = xfs_uuid_mount(mp);
729         if (error)
730                 goto out_remove_sysfs;
731
732         /*
733          * Set the minimum read and write sizes
734          */
735         xfs_set_rw_sizes(mp);
736
737         /* set the low space thresholds for dynamic preallocation */
738         xfs_set_low_space_thresholds(mp);
739
740         /*
741          * Set the inode cluster size.
742          * This may still be overridden by the file system
743          * block size if it is larger than the chosen cluster size.
744          *
745          * For v5 filesystems, scale the cluster size with the inode size to
746          * keep a constant ratio of inode per cluster buffer, but only if mkfs
747          * has set the inode alignment value appropriately for larger cluster
748          * sizes.
749          */
750         mp->m_inode_cluster_size = XFS_INODE_BIG_CLUSTER_SIZE;
751         if (xfs_sb_version_hascrc(&mp->m_sb)) {
752                 int     new_size = mp->m_inode_cluster_size;
753
754                 new_size *= mp->m_sb.sb_inodesize / XFS_DINODE_MIN_SIZE;
755                 if (mp->m_sb.sb_inoalignmt >= XFS_B_TO_FSBT(mp, new_size))
756                         mp->m_inode_cluster_size = new_size;
757         }
758
759         /*
760          * Set inode alignment fields
761          */
762         xfs_set_inoalignment(mp);
763
764         /*
765          * Check that the data (and log if separate) is an ok size.
766          */
767         error = xfs_check_sizes(mp);
768         if (error)
769                 goto out_remove_uuid;
770
771         /*
772          * Initialize realtime fields in the mount structure
773          */
774         error = xfs_rtmount_init(mp);
775         if (error) {
776                 xfs_warn(mp, "RT mount failed");
777                 goto out_remove_uuid;
778         }
779
780         /*
781          *  Copies the low order bits of the timestamp and the randomly
782          *  set "sequence" number out of a UUID.
783          */
784         uuid_getnodeuniq(&sbp->sb_uuid, mp->m_fixedfsid);
785
786         mp->m_dmevmask = 0;     /* not persistent; set after each mount */
787
788         error = xfs_da_mount(mp);
789         if (error) {
790                 xfs_warn(mp, "Failed dir/attr init: %d", error);
791                 goto out_remove_uuid;
792         }
793
794         /*
795          * Initialize the precomputed transaction reservations values.
796          */
797         xfs_trans_init(mp);
798
799         /*
800          * Allocate and initialize the per-ag data.
801          */
802         spin_lock_init(&mp->m_perag_lock);
803         INIT_RADIX_TREE(&mp->m_perag_tree, GFP_ATOMIC);
804         error = xfs_initialize_perag(mp, sbp->sb_agcount, &mp->m_maxagi);
805         if (error) {
806                 xfs_warn(mp, "Failed per-ag init: %d", error);
807                 goto out_free_dir;
808         }
809
810         if (!sbp->sb_logblocks) {
811                 xfs_warn(mp, "no log defined");
812                 XFS_ERROR_REPORT("xfs_mountfs", XFS_ERRLEVEL_LOW, mp);
813                 error = -EFSCORRUPTED;
814                 goto out_free_perag;
815         }
816
817         /*
818          * log's mount-time initialization. Perform 1st part recovery if needed
819          */
820         error = xfs_log_mount(mp, mp->m_logdev_targp,
821                               XFS_FSB_TO_DADDR(mp, sbp->sb_logstart),
822                               XFS_FSB_TO_BB(mp, sbp->sb_logblocks));
823         if (error) {
824                 xfs_warn(mp, "log mount failed");
825                 goto out_fail_wait;
826         }
827
828         /*
829          * Now the log is mounted, we know if it was an unclean shutdown or
830          * not. If it was, with the first phase of recovery has completed, we
831          * have consistent AG blocks on disk. We have not recovered EFIs yet,
832          * but they are recovered transactionally in the second recovery phase
833          * later.
834          *
835          * Hence we can safely re-initialise incore superblock counters from
836          * the per-ag data. These may not be correct if the filesystem was not
837          * cleanly unmounted, so we need to wait for recovery to finish before
838          * doing this.
839          *
840          * If the filesystem was cleanly unmounted, then we can trust the
841          * values in the superblock to be correct and we don't need to do
842          * anything here.
843          *
844          * If we are currently making the filesystem, the initialisation will
845          * fail as the perag data is in an undefined state.
846          */
847         if (xfs_sb_version_haslazysbcount(&mp->m_sb) &&
848             !XFS_LAST_UNMOUNT_WAS_CLEAN(mp) &&
849              !mp->m_sb.sb_inprogress) {
850                 error = xfs_initialize_perag_data(mp, sbp->sb_agcount);
851                 if (error)
852                         goto out_log_dealloc;
853         }
854
855         /*
856          * Get and sanity-check the root inode.
857          * Save the pointer to it in the mount structure.
858          */
859         error = xfs_iget(mp, NULL, sbp->sb_rootino, 0, XFS_ILOCK_EXCL, &rip);
860         if (error) {
861                 xfs_warn(mp, "failed to read root inode");
862                 goto out_log_dealloc;
863         }
864
865         ASSERT(rip != NULL);
866
867         if (unlikely(!S_ISDIR(rip->i_d.di_mode))) {
868                 xfs_warn(mp, "corrupted root inode %llu: not a directory",
869                         (unsigned long long)rip->i_ino);
870                 xfs_iunlock(rip, XFS_ILOCK_EXCL);
871                 XFS_ERROR_REPORT("xfs_mountfs_int(2)", XFS_ERRLEVEL_LOW,
872                                  mp);
873                 error = -EFSCORRUPTED;
874                 goto out_rele_rip;
875         }
876         mp->m_rootip = rip;     /* save it */
877
878         xfs_iunlock(rip, XFS_ILOCK_EXCL);
879
880         /*
881          * Initialize realtime inode pointers in the mount structure
882          */
883         error = xfs_rtmount_inodes(mp);
884         if (error) {
885                 /*
886                  * Free up the root inode.
887                  */
888                 xfs_warn(mp, "failed to read RT inodes");
889                 goto out_rele_rip;
890         }
891
892         /*
893          * If this is a read-only mount defer the superblock updates until
894          * the next remount into writeable mode.  Otherwise we would never
895          * perform the update e.g. for the root filesystem.
896          */
897         if (mp->m_update_flags && !(mp->m_flags & XFS_MOUNT_RDONLY)) {
898                 error = xfs_mount_log_sb(mp, mp->m_update_flags);
899                 if (error) {
900                         xfs_warn(mp, "failed to write sb changes");
901                         goto out_rtunmount;
902                 }
903         }
904
905         /*
906          * Initialise the XFS quota management subsystem for this mount
907          */
908         if (XFS_IS_QUOTA_RUNNING(mp)) {
909                 error = xfs_qm_newmount(mp, &quotamount, &quotaflags);
910                 if (error)
911                         goto out_rtunmount;
912         } else {
913                 ASSERT(!XFS_IS_QUOTA_ON(mp));
914
915                 /*
916                  * If a file system had quotas running earlier, but decided to
917                  * mount without -o uquota/pquota/gquota options, revoke the
918                  * quotachecked license.
919                  */
920                 if (mp->m_sb.sb_qflags & XFS_ALL_QUOTA_ACCT) {
921                         xfs_notice(mp, "resetting quota flags");
922                         error = xfs_mount_reset_sbqflags(mp);
923                         if (error)
924                                 goto out_rtunmount;
925                 }
926         }
927
928         /*
929          * Finish recovering the file system.  This part needed to be
930          * delayed until after the root and real-time bitmap inodes
931          * were consistently read in.
932          */
933         error = xfs_log_mount_finish(mp);
934         if (error) {
935                 xfs_warn(mp, "log mount finish failed");
936                 goto out_rtunmount;
937         }
938
939         /*
940          * Complete the quota initialisation, post-log-replay component.
941          */
942         if (quotamount) {
943                 ASSERT(mp->m_qflags == 0);
944                 mp->m_qflags = quotaflags;
945
946                 xfs_qm_mount_quotas(mp);
947         }
948
949         /*
950          * Now we are mounted, reserve a small amount of unused space for
951          * privileged transactions. This is needed so that transaction
952          * space required for critical operations can dip into this pool
953          * when at ENOSPC. This is needed for operations like create with
954          * attr, unwritten extent conversion at ENOSPC, etc. Data allocations
955          * are not allowed to use this reserved space.
956          *
957          * This may drive us straight to ENOSPC on mount, but that implies
958          * we were already there on the last unmount. Warn if this occurs.
959          */
960         if (!(mp->m_flags & XFS_MOUNT_RDONLY)) {
961                 resblks = xfs_default_resblks(mp);
962                 error = xfs_reserve_blocks(mp, &resblks, NULL);
963                 if (error)
964                         xfs_warn(mp,
965         "Unable to allocate reserve blocks. Continuing without reserve pool.");
966         }
967
968         return 0;
969
970  out_rtunmount:
971         xfs_rtunmount_inodes(mp);
972  out_rele_rip:
973         IRELE(rip);
974  out_log_dealloc:
975         xfs_log_unmount(mp);
976  out_fail_wait:
977         if (mp->m_logdev_targp && mp->m_logdev_targp != mp->m_ddev_targp)
978                 xfs_wait_buftarg(mp->m_logdev_targp);
979         xfs_wait_buftarg(mp->m_ddev_targp);
980  out_free_perag:
981         xfs_free_perag(mp);
982  out_free_dir:
983         xfs_da_unmount(mp);
984  out_remove_uuid:
985         xfs_uuid_unmount(mp);
986  out_remove_sysfs:
987         xfs_sysfs_del(&mp->m_kobj);
988  out:
989         return error;
990 }
991
992 /*
993  * This flushes out the inodes,dquots and the superblock, unmounts the
994  * log and makes sure that incore structures are freed.
995  */
996 void
997 xfs_unmountfs(
998         struct xfs_mount        *mp)
999 {
1000         __uint64_t              resblks;
1001         int                     error;
1002
1003         cancel_delayed_work_sync(&mp->m_eofblocks_work);
1004
1005         xfs_qm_unmount_quotas(mp);
1006         xfs_rtunmount_inodes(mp);
1007         IRELE(mp->m_rootip);
1008
1009         /*
1010          * We can potentially deadlock here if we have an inode cluster
1011          * that has been freed has its buffer still pinned in memory because
1012          * the transaction is still sitting in a iclog. The stale inodes
1013          * on that buffer will have their flush locks held until the
1014          * transaction hits the disk and the callbacks run. the inode
1015          * flush takes the flush lock unconditionally and with nothing to
1016          * push out the iclog we will never get that unlocked. hence we
1017          * need to force the log first.
1018          */
1019         xfs_log_force(mp, XFS_LOG_SYNC);
1020
1021         /*
1022          * Flush all pending changes from the AIL.
1023          */
1024         xfs_ail_push_all_sync(mp->m_ail);
1025
1026         /*
1027          * And reclaim all inodes.  At this point there should be no dirty
1028          * inodes and none should be pinned or locked, but use synchronous
1029          * reclaim just to be sure. We can stop background inode reclaim
1030          * here as well if it is still running.
1031          */
1032         cancel_delayed_work_sync(&mp->m_reclaim_work);
1033         xfs_reclaim_inodes(mp, SYNC_WAIT);
1034
1035         xfs_qm_unmount(mp);
1036
1037         /*
1038          * Unreserve any blocks we have so that when we unmount we don't account
1039          * the reserved free space as used. This is really only necessary for
1040          * lazy superblock counting because it trusts the incore superblock
1041          * counters to be absolutely correct on clean unmount.
1042          *
1043          * We don't bother correcting this elsewhere for lazy superblock
1044          * counting because on mount of an unclean filesystem we reconstruct the
1045          * correct counter value and this is irrelevant.
1046          *
1047          * For non-lazy counter filesystems, this doesn't matter at all because
1048          * we only every apply deltas to the superblock and hence the incore
1049          * value does not matter....
1050          */
1051         resblks = 0;
1052         error = xfs_reserve_blocks(mp, &resblks, NULL);
1053         if (error)
1054                 xfs_warn(mp, "Unable to free reserved block pool. "
1055                                 "Freespace may not be correct on next mount.");
1056
1057         error = xfs_log_sbcount(mp);
1058         if (error)
1059                 xfs_warn(mp, "Unable to update superblock counters. "
1060                                 "Freespace may not be correct on next mount.");
1061
1062         xfs_log_unmount(mp);
1063         xfs_da_unmount(mp);
1064         xfs_uuid_unmount(mp);
1065
1066 #if defined(DEBUG)
1067         xfs_errortag_clearall(mp, 0);
1068 #endif
1069         xfs_free_perag(mp);
1070
1071         xfs_sysfs_del(&mp->m_kobj);
1072 }
1073
1074 int
1075 xfs_fs_writable(xfs_mount_t *mp)
1076 {
1077         return !(mp->m_super->s_writers.frozen || XFS_FORCED_SHUTDOWN(mp) ||
1078                 (mp->m_flags & XFS_MOUNT_RDONLY));
1079 }
1080
1081 /*
1082  * xfs_log_sbcount
1083  *
1084  * Sync the superblock counters to disk.
1085  *
1086  * Note this code can be called during the process of freezing, so
1087  * we may need to use the transaction allocator which does not
1088  * block when the transaction subsystem is in its frozen state.
1089  */
1090 int
1091 xfs_log_sbcount(xfs_mount_t *mp)
1092 {
1093         xfs_trans_t     *tp;
1094         int             error;
1095
1096         if (!xfs_fs_writable(mp))
1097                 return 0;
1098
1099         xfs_icsb_sync_counters(mp, 0);
1100
1101         /*
1102          * we don't need to do this if we are updating the superblock
1103          * counters on every modification.
1104          */
1105         if (!xfs_sb_version_haslazysbcount(&mp->m_sb))
1106                 return 0;
1107
1108         tp = _xfs_trans_alloc(mp, XFS_TRANS_SB_COUNT, KM_SLEEP);
1109         error = xfs_trans_reserve(tp, &M_RES(mp)->tr_sb, 0, 0);
1110         if (error) {
1111                 xfs_trans_cancel(tp, 0);
1112                 return error;
1113         }
1114
1115         xfs_mod_sb(tp, XFS_SB_IFREE | XFS_SB_ICOUNT | XFS_SB_FDBLOCKS);
1116         xfs_trans_set_sync(tp);
1117         error = xfs_trans_commit(tp, 0);
1118         return error;
1119 }
1120
1121 /*
1122  * xfs_mod_incore_sb_unlocked() is a utility routine commonly used to apply
1123  * a delta to a specified field in the in-core superblock.  Simply
1124  * switch on the field indicated and apply the delta to that field.
1125  * Fields are not allowed to dip below zero, so if the delta would
1126  * do this do not apply it and return EINVAL.
1127  *
1128  * The m_sb_lock must be held when this routine is called.
1129  */
1130 STATIC int
1131 xfs_mod_incore_sb_unlocked(
1132         xfs_mount_t     *mp,
1133         xfs_sb_field_t  field,
1134         int64_t         delta,
1135         int             rsvd)
1136 {
1137         int             scounter;       /* short counter for 32 bit fields */
1138         long long       lcounter;       /* long counter for 64 bit fields */
1139         long long       res_used, rem;
1140
1141         /*
1142          * With the in-core superblock spin lock held, switch
1143          * on the indicated field.  Apply the delta to the
1144          * proper field.  If the fields value would dip below
1145          * 0, then do not apply the delta and return EINVAL.
1146          */
1147         switch (field) {
1148         case XFS_SBS_ICOUNT:
1149                 lcounter = (long long)mp->m_sb.sb_icount;
1150                 lcounter += delta;
1151                 if (lcounter < 0) {
1152                         ASSERT(0);
1153                         return -EINVAL;
1154                 }
1155                 mp->m_sb.sb_icount = lcounter;
1156                 return 0;
1157         case XFS_SBS_IFREE:
1158                 lcounter = (long long)mp->m_sb.sb_ifree;
1159                 lcounter += delta;
1160                 if (lcounter < 0) {
1161                         ASSERT(0);
1162                         return -EINVAL;
1163                 }
1164                 mp->m_sb.sb_ifree = lcounter;
1165                 return 0;
1166         case XFS_SBS_FDBLOCKS:
1167                 lcounter = (long long)
1168                         mp->m_sb.sb_fdblocks - XFS_ALLOC_SET_ASIDE(mp);
1169                 res_used = (long long)(mp->m_resblks - mp->m_resblks_avail);
1170
1171                 if (delta > 0) {                /* Putting blocks back */
1172                         if (res_used > delta) {
1173                                 mp->m_resblks_avail += delta;
1174                         } else {
1175                                 rem = delta - res_used;
1176                                 mp->m_resblks_avail = mp->m_resblks;
1177                                 lcounter += rem;
1178                         }
1179                 } else {                                /* Taking blocks away */
1180                         lcounter += delta;
1181                         if (lcounter >= 0) {
1182                                 mp->m_sb.sb_fdblocks = lcounter +
1183                                                         XFS_ALLOC_SET_ASIDE(mp);
1184                                 return 0;
1185                         }
1186
1187                         /*
1188                          * We are out of blocks, use any available reserved
1189                          * blocks if were allowed to.
1190                          */
1191                         if (!rsvd)
1192                                 return -ENOSPC;
1193
1194                         lcounter = (long long)mp->m_resblks_avail + delta;
1195                         if (lcounter >= 0) {
1196                                 mp->m_resblks_avail = lcounter;
1197                                 return 0;
1198                         }
1199                         printk_once(KERN_WARNING
1200                                 "Filesystem \"%s\": reserve blocks depleted! "
1201                                 "Consider increasing reserve pool size.",
1202                                 mp->m_fsname);
1203                         return -ENOSPC;
1204                 }
1205
1206                 mp->m_sb.sb_fdblocks = lcounter + XFS_ALLOC_SET_ASIDE(mp);
1207                 return 0;
1208         case XFS_SBS_FREXTENTS:
1209                 lcounter = (long long)mp->m_sb.sb_frextents;
1210                 lcounter += delta;
1211                 if (lcounter < 0) {
1212                         return -ENOSPC;
1213                 }
1214                 mp->m_sb.sb_frextents = lcounter;
1215                 return 0;
1216         case XFS_SBS_DBLOCKS:
1217                 lcounter = (long long)mp->m_sb.sb_dblocks;
1218                 lcounter += delta;
1219                 if (lcounter < 0) {
1220                         ASSERT(0);
1221                         return -EINVAL;
1222                 }
1223                 mp->m_sb.sb_dblocks = lcounter;
1224                 return 0;
1225         case XFS_SBS_AGCOUNT:
1226                 scounter = mp->m_sb.sb_agcount;
1227                 scounter += delta;
1228                 if (scounter < 0) {
1229                         ASSERT(0);
1230                         return -EINVAL;
1231                 }
1232                 mp->m_sb.sb_agcount = scounter;
1233                 return 0;
1234         case XFS_SBS_IMAX_PCT:
1235                 scounter = mp->m_sb.sb_imax_pct;
1236                 scounter += delta;
1237                 if (scounter < 0) {
1238                         ASSERT(0);
1239                         return -EINVAL;
1240                 }
1241                 mp->m_sb.sb_imax_pct = scounter;
1242                 return 0;
1243         case XFS_SBS_REXTSIZE:
1244                 scounter = mp->m_sb.sb_rextsize;
1245                 scounter += delta;
1246                 if (scounter < 0) {
1247                         ASSERT(0);
1248                         return -EINVAL;
1249                 }
1250                 mp->m_sb.sb_rextsize = scounter;
1251                 return 0;
1252         case XFS_SBS_RBMBLOCKS:
1253                 scounter = mp->m_sb.sb_rbmblocks;
1254                 scounter += delta;
1255                 if (scounter < 0) {
1256                         ASSERT(0);
1257                         return -EINVAL;
1258                 }
1259                 mp->m_sb.sb_rbmblocks = scounter;
1260                 return 0;
1261         case XFS_SBS_RBLOCKS:
1262                 lcounter = (long long)mp->m_sb.sb_rblocks;
1263                 lcounter += delta;
1264                 if (lcounter < 0) {
1265                         ASSERT(0);
1266                         return -EINVAL;
1267                 }
1268                 mp->m_sb.sb_rblocks = lcounter;
1269                 return 0;
1270         case XFS_SBS_REXTENTS:
1271                 lcounter = (long long)mp->m_sb.sb_rextents;
1272                 lcounter += delta;
1273                 if (lcounter < 0) {
1274                         ASSERT(0);
1275                         return -EINVAL;
1276                 }
1277                 mp->m_sb.sb_rextents = lcounter;
1278                 return 0;
1279         case XFS_SBS_REXTSLOG:
1280                 scounter = mp->m_sb.sb_rextslog;
1281                 scounter += delta;
1282                 if (scounter < 0) {
1283                         ASSERT(0);
1284                         return -EINVAL;
1285                 }
1286                 mp->m_sb.sb_rextslog = scounter;
1287                 return 0;
1288         default:
1289                 ASSERT(0);
1290                 return -EINVAL;
1291         }
1292 }
1293
1294 /*
1295  * xfs_mod_incore_sb() is used to change a field in the in-core
1296  * superblock structure by the specified delta.  This modification
1297  * is protected by the m_sb_lock.  Just use the xfs_mod_incore_sb_unlocked()
1298  * routine to do the work.
1299  */
1300 int
1301 xfs_mod_incore_sb(
1302         struct xfs_mount        *mp,
1303         xfs_sb_field_t          field,
1304         int64_t                 delta,
1305         int                     rsvd)
1306 {
1307         int                     status;
1308
1309 #ifdef HAVE_PERCPU_SB
1310         ASSERT(field < XFS_SBS_ICOUNT || field > XFS_SBS_FDBLOCKS);
1311 #endif
1312         spin_lock(&mp->m_sb_lock);
1313         status = xfs_mod_incore_sb_unlocked(mp, field, delta, rsvd);
1314         spin_unlock(&mp->m_sb_lock);
1315
1316         return status;
1317 }
1318
1319 /*
1320  * Change more than one field in the in-core superblock structure at a time.
1321  *
1322  * The fields and changes to those fields are specified in the array of
1323  * xfs_mod_sb structures passed in.  Either all of the specified deltas
1324  * will be applied or none of them will.  If any modified field dips below 0,
1325  * then all modifications will be backed out and EINVAL will be returned.
1326  *
1327  * Note that this function may not be used for the superblock values that
1328  * are tracked with the in-memory per-cpu counters - a direct call to
1329  * xfs_icsb_modify_counters is required for these.
1330  */
1331 int
1332 xfs_mod_incore_sb_batch(
1333         struct xfs_mount        *mp,
1334         xfs_mod_sb_t            *msb,
1335         uint                    nmsb,
1336         int                     rsvd)
1337 {
1338         xfs_mod_sb_t            *msbp;
1339         int                     error = 0;
1340
1341         /*
1342          * Loop through the array of mod structures and apply each individually.
1343          * If any fail, then back out all those which have already been applied.
1344          * Do all of this within the scope of the m_sb_lock so that all of the
1345          * changes will be atomic.
1346          */
1347         spin_lock(&mp->m_sb_lock);
1348         for (msbp = msb; msbp < (msb + nmsb); msbp++) {
1349                 ASSERT(msbp->msb_field < XFS_SBS_ICOUNT ||
1350                        msbp->msb_field > XFS_SBS_FDBLOCKS);
1351
1352                 error = xfs_mod_incore_sb_unlocked(mp, msbp->msb_field,
1353                                                    msbp->msb_delta, rsvd);
1354                 if (error)
1355                         goto unwind;
1356         }
1357         spin_unlock(&mp->m_sb_lock);
1358         return 0;
1359
1360 unwind:
1361         while (--msbp >= msb) {
1362                 error = xfs_mod_incore_sb_unlocked(mp, msbp->msb_field,
1363                                                    -msbp->msb_delta, rsvd);
1364                 ASSERT(error == 0);
1365         }
1366         spin_unlock(&mp->m_sb_lock);
1367         return error;
1368 }
1369
1370 /*
1371  * xfs_getsb() is called to obtain the buffer for the superblock.
1372  * The buffer is returned locked and read in from disk.
1373  * The buffer should be released with a call to xfs_brelse().
1374  *
1375  * If the flags parameter is BUF_TRYLOCK, then we'll only return
1376  * the superblock buffer if it can be locked without sleeping.
1377  * If it can't then we'll return NULL.
1378  */
1379 struct xfs_buf *
1380 xfs_getsb(
1381         struct xfs_mount        *mp,
1382         int                     flags)
1383 {
1384         struct xfs_buf          *bp = mp->m_sb_bp;
1385
1386         if (!xfs_buf_trylock(bp)) {
1387                 if (flags & XBF_TRYLOCK)
1388                         return NULL;
1389                 xfs_buf_lock(bp);
1390         }
1391
1392         xfs_buf_hold(bp);
1393         ASSERT(XFS_BUF_ISDONE(bp));
1394         return bp;
1395 }
1396
1397 /*
1398  * Used to free the superblock along various error paths.
1399  */
1400 void
1401 xfs_freesb(
1402         struct xfs_mount        *mp)
1403 {
1404         struct xfs_buf          *bp = mp->m_sb_bp;
1405
1406         xfs_buf_lock(bp);
1407         mp->m_sb_bp = NULL;
1408         xfs_buf_relse(bp);
1409 }
1410
1411 /*
1412  * Used to log changes to the superblock unit and width fields which could
1413  * be altered by the mount options, as well as any potential sb_features2
1414  * fixup. Only the first superblock is updated.
1415  */
1416 int
1417 xfs_mount_log_sb(
1418         xfs_mount_t     *mp,
1419         __int64_t       fields)
1420 {
1421         xfs_trans_t     *tp;
1422         int             error;
1423
1424         ASSERT(fields & (XFS_SB_UNIT | XFS_SB_WIDTH | XFS_SB_UUID |
1425                          XFS_SB_FEATURES2 | XFS_SB_BAD_FEATURES2 |
1426                          XFS_SB_VERSIONNUM));
1427
1428         tp = xfs_trans_alloc(mp, XFS_TRANS_SB_UNIT);
1429         error = xfs_trans_reserve(tp, &M_RES(mp)->tr_sb, 0, 0);
1430         if (error) {
1431                 xfs_trans_cancel(tp, 0);
1432                 return error;
1433         }
1434         xfs_mod_sb(tp, fields);
1435         error = xfs_trans_commit(tp, 0);
1436         return error;
1437 }
1438
1439 /*
1440  * If the underlying (data/log/rt) device is readonly, there are some
1441  * operations that cannot proceed.
1442  */
1443 int
1444 xfs_dev_is_read_only(
1445         struct xfs_mount        *mp,
1446         char                    *message)
1447 {
1448         if (xfs_readonly_buftarg(mp->m_ddev_targp) ||
1449             xfs_readonly_buftarg(mp->m_logdev_targp) ||
1450             (mp->m_rtdev_targp && xfs_readonly_buftarg(mp->m_rtdev_targp))) {
1451                 xfs_notice(mp, "%s required on read-only device.", message);
1452                 xfs_notice(mp, "write access unavailable, cannot proceed.");
1453                 return -EROFS;
1454         }
1455         return 0;
1456 }
1457
1458 #ifdef HAVE_PERCPU_SB
1459 /*
1460  * Per-cpu incore superblock counters
1461  *
1462  * Simple concept, difficult implementation
1463  *
1464  * Basically, replace the incore superblock counters with a distributed per cpu
1465  * counter for contended fields (e.g.  free block count).
1466  *
1467  * Difficulties arise in that the incore sb is used for ENOSPC checking, and
1468  * hence needs to be accurately read when we are running low on space. Hence
1469  * there is a method to enable and disable the per-cpu counters based on how
1470  * much "stuff" is available in them.
1471  *
1472  * Basically, a counter is enabled if there is enough free resource to justify
1473  * running a per-cpu fast-path. If the per-cpu counter runs out (i.e. a local
1474  * ENOSPC), then we disable the counters to synchronise all callers and
1475  * re-distribute the available resources.
1476  *
1477  * If, once we redistributed the available resources, we still get a failure,
1478  * we disable the per-cpu counter and go through the slow path.
1479  *
1480  * The slow path is the current xfs_mod_incore_sb() function.  This means that
1481  * when we disable a per-cpu counter, we need to drain its resources back to
1482  * the global superblock. We do this after disabling the counter to prevent
1483  * more threads from queueing up on the counter.
1484  *
1485  * Essentially, this means that we still need a lock in the fast path to enable
1486  * synchronisation between the global counters and the per-cpu counters. This
1487  * is not a problem because the lock will be local to a CPU almost all the time
1488  * and have little contention except when we get to ENOSPC conditions.
1489  *
1490  * Basically, this lock becomes a barrier that enables us to lock out the fast
1491  * path while we do things like enabling and disabling counters and
1492  * synchronising the counters.
1493  *
1494  * Locking rules:
1495  *
1496  *      1. m_sb_lock before picking up per-cpu locks
1497  *      2. per-cpu locks always picked up via for_each_online_cpu() order
1498  *      3. accurate counter sync requires m_sb_lock + per cpu locks
1499  *      4. modifying per-cpu counters requires holding per-cpu lock
1500  *      5. modifying global counters requires holding m_sb_lock
1501  *      6. enabling or disabling a counter requires holding the m_sb_lock 
1502  *         and _none_ of the per-cpu locks.
1503  *
1504  * Disabled counters are only ever re-enabled by a balance operation
1505  * that results in more free resources per CPU than a given threshold.
1506  * To ensure counters don't remain disabled, they are rebalanced when
1507  * the global resource goes above a higher threshold (i.e. some hysteresis
1508  * is present to prevent thrashing).
1509  */
1510
1511 #ifdef CONFIG_HOTPLUG_CPU
1512 /*
1513  * hot-plug CPU notifier support.
1514  *
1515  * We need a notifier per filesystem as we need to be able to identify
1516  * the filesystem to balance the counters out. This is achieved by
1517  * having a notifier block embedded in the xfs_mount_t and doing pointer
1518  * magic to get the mount pointer from the notifier block address.
1519  */
1520 STATIC int
1521 xfs_icsb_cpu_notify(
1522         struct notifier_block *nfb,
1523         unsigned long action,
1524         void *hcpu)
1525 {
1526         xfs_icsb_cnts_t *cntp;
1527         xfs_mount_t     *mp;
1528
1529         mp = (xfs_mount_t *)container_of(nfb, xfs_mount_t, m_icsb_notifier);
1530         cntp = (xfs_icsb_cnts_t *)
1531                         per_cpu_ptr(mp->m_sb_cnts, (unsigned long)hcpu);
1532         switch (action) {
1533         case CPU_UP_PREPARE:
1534         case CPU_UP_PREPARE_FROZEN:
1535                 /* Easy Case - initialize the area and locks, and
1536                  * then rebalance when online does everything else for us. */
1537                 memset(cntp, 0, sizeof(xfs_icsb_cnts_t));
1538                 break;
1539         case CPU_ONLINE:
1540         case CPU_ONLINE_FROZEN:
1541                 xfs_icsb_lock(mp);
1542                 xfs_icsb_balance_counter(mp, XFS_SBS_ICOUNT, 0);
1543                 xfs_icsb_balance_counter(mp, XFS_SBS_IFREE, 0);
1544                 xfs_icsb_balance_counter(mp, XFS_SBS_FDBLOCKS, 0);
1545                 xfs_icsb_unlock(mp);
1546                 break;
1547         case CPU_DEAD:
1548         case CPU_DEAD_FROZEN:
1549                 /* Disable all the counters, then fold the dead cpu's
1550                  * count into the total on the global superblock and
1551                  * re-enable the counters. */
1552                 xfs_icsb_lock(mp);
1553                 spin_lock(&mp->m_sb_lock);
1554                 xfs_icsb_disable_counter(mp, XFS_SBS_ICOUNT);
1555                 xfs_icsb_disable_counter(mp, XFS_SBS_IFREE);
1556                 xfs_icsb_disable_counter(mp, XFS_SBS_FDBLOCKS);
1557
1558                 mp->m_sb.sb_icount += cntp->icsb_icount;
1559                 mp->m_sb.sb_ifree += cntp->icsb_ifree;
1560                 mp->m_sb.sb_fdblocks += cntp->icsb_fdblocks;
1561
1562                 memset(cntp, 0, sizeof(xfs_icsb_cnts_t));
1563
1564                 xfs_icsb_balance_counter_locked(mp, XFS_SBS_ICOUNT, 0);
1565                 xfs_icsb_balance_counter_locked(mp, XFS_SBS_IFREE, 0);
1566                 xfs_icsb_balance_counter_locked(mp, XFS_SBS_FDBLOCKS, 0);
1567                 spin_unlock(&mp->m_sb_lock);
1568                 xfs_icsb_unlock(mp);
1569                 break;
1570         }
1571
1572         return NOTIFY_OK;
1573 }
1574 #endif /* CONFIG_HOTPLUG_CPU */
1575
1576 int
1577 xfs_icsb_init_counters(
1578         xfs_mount_t     *mp)
1579 {
1580         xfs_icsb_cnts_t *cntp;
1581         int             i;
1582
1583         mp->m_sb_cnts = alloc_percpu(xfs_icsb_cnts_t);
1584         if (mp->m_sb_cnts == NULL)
1585                 return -ENOMEM;
1586
1587         for_each_online_cpu(i) {
1588                 cntp = (xfs_icsb_cnts_t *)per_cpu_ptr(mp->m_sb_cnts, i);
1589                 memset(cntp, 0, sizeof(xfs_icsb_cnts_t));
1590         }
1591
1592         mutex_init(&mp->m_icsb_mutex);
1593
1594         /*
1595          * start with all counters disabled so that the
1596          * initial balance kicks us off correctly
1597          */
1598         mp->m_icsb_counters = -1;
1599
1600 #ifdef CONFIG_HOTPLUG_CPU
1601         mp->m_icsb_notifier.notifier_call = xfs_icsb_cpu_notify;
1602         mp->m_icsb_notifier.priority = 0;
1603         register_hotcpu_notifier(&mp->m_icsb_notifier);
1604 #endif /* CONFIG_HOTPLUG_CPU */
1605
1606         return 0;
1607 }
1608
1609 void
1610 xfs_icsb_reinit_counters(
1611         xfs_mount_t     *mp)
1612 {
1613         xfs_icsb_lock(mp);
1614         /*
1615          * start with all counters disabled so that the
1616          * initial balance kicks us off correctly
1617          */
1618         mp->m_icsb_counters = -1;
1619         xfs_icsb_balance_counter(mp, XFS_SBS_ICOUNT, 0);
1620         xfs_icsb_balance_counter(mp, XFS_SBS_IFREE, 0);
1621         xfs_icsb_balance_counter(mp, XFS_SBS_FDBLOCKS, 0);
1622         xfs_icsb_unlock(mp);
1623 }
1624
1625 void
1626 xfs_icsb_destroy_counters(
1627         xfs_mount_t     *mp)
1628 {
1629         if (mp->m_sb_cnts) {
1630                 unregister_hotcpu_notifier(&mp->m_icsb_notifier);
1631                 free_percpu(mp->m_sb_cnts);
1632         }
1633         mutex_destroy(&mp->m_icsb_mutex);
1634 }
1635
1636 STATIC void
1637 xfs_icsb_lock_cntr(
1638         xfs_icsb_cnts_t *icsbp)
1639 {
1640         while (test_and_set_bit(XFS_ICSB_FLAG_LOCK, &icsbp->icsb_flags)) {
1641                 ndelay(1000);
1642         }
1643 }
1644
1645 STATIC void
1646 xfs_icsb_unlock_cntr(
1647         xfs_icsb_cnts_t *icsbp)
1648 {
1649         clear_bit(XFS_ICSB_FLAG_LOCK, &icsbp->icsb_flags);
1650 }
1651
1652
1653 STATIC void
1654 xfs_icsb_lock_all_counters(
1655         xfs_mount_t     *mp)
1656 {
1657         xfs_icsb_cnts_t *cntp;
1658         int             i;
1659
1660         for_each_online_cpu(i) {
1661                 cntp = (xfs_icsb_cnts_t *)per_cpu_ptr(mp->m_sb_cnts, i);
1662                 xfs_icsb_lock_cntr(cntp);
1663         }
1664 }
1665
1666 STATIC void
1667 xfs_icsb_unlock_all_counters(
1668         xfs_mount_t     *mp)
1669 {
1670         xfs_icsb_cnts_t *cntp;
1671         int             i;
1672
1673         for_each_online_cpu(i) {
1674                 cntp = (xfs_icsb_cnts_t *)per_cpu_ptr(mp->m_sb_cnts, i);
1675                 xfs_icsb_unlock_cntr(cntp);
1676         }
1677 }
1678
1679 STATIC void
1680 xfs_icsb_count(
1681         xfs_mount_t     *mp,
1682         xfs_icsb_cnts_t *cnt,
1683         int             flags)
1684 {
1685         xfs_icsb_cnts_t *cntp;
1686         int             i;
1687
1688         memset(cnt, 0, sizeof(xfs_icsb_cnts_t));
1689
1690         if (!(flags & XFS_ICSB_LAZY_COUNT))
1691                 xfs_icsb_lock_all_counters(mp);
1692
1693         for_each_online_cpu(i) {
1694                 cntp = (xfs_icsb_cnts_t *)per_cpu_ptr(mp->m_sb_cnts, i);
1695                 cnt->icsb_icount += cntp->icsb_icount;
1696                 cnt->icsb_ifree += cntp->icsb_ifree;
1697                 cnt->icsb_fdblocks += cntp->icsb_fdblocks;
1698         }
1699
1700         if (!(flags & XFS_ICSB_LAZY_COUNT))
1701                 xfs_icsb_unlock_all_counters(mp);
1702 }
1703
1704 STATIC int
1705 xfs_icsb_counter_disabled(
1706         xfs_mount_t     *mp,
1707         xfs_sb_field_t  field)
1708 {
1709         ASSERT((field >= XFS_SBS_ICOUNT) && (field <= XFS_SBS_FDBLOCKS));
1710         return test_bit(field, &mp->m_icsb_counters);
1711 }
1712
1713 STATIC void
1714 xfs_icsb_disable_counter(
1715         xfs_mount_t     *mp,
1716         xfs_sb_field_t  field)
1717 {
1718         xfs_icsb_cnts_t cnt;
1719
1720         ASSERT((field >= XFS_SBS_ICOUNT) && (field <= XFS_SBS_FDBLOCKS));
1721
1722         /*
1723          * If we are already disabled, then there is nothing to do
1724          * here. We check before locking all the counters to avoid
1725          * the expensive lock operation when being called in the
1726          * slow path and the counter is already disabled. This is
1727          * safe because the only time we set or clear this state is under
1728          * the m_icsb_mutex.
1729          */
1730         if (xfs_icsb_counter_disabled(mp, field))
1731                 return;
1732
1733         xfs_icsb_lock_all_counters(mp);
1734         if (!test_and_set_bit(field, &mp->m_icsb_counters)) {
1735                 /* drain back to superblock */
1736
1737                 xfs_icsb_count(mp, &cnt, XFS_ICSB_LAZY_COUNT);
1738                 switch(field) {
1739                 case XFS_SBS_ICOUNT:
1740                         mp->m_sb.sb_icount = cnt.icsb_icount;
1741                         break;
1742                 case XFS_SBS_IFREE:
1743                         mp->m_sb.sb_ifree = cnt.icsb_ifree;
1744                         break;
1745                 case XFS_SBS_FDBLOCKS:
1746                         mp->m_sb.sb_fdblocks = cnt.icsb_fdblocks;
1747                         break;
1748                 default:
1749                         BUG();
1750                 }
1751         }
1752
1753         xfs_icsb_unlock_all_counters(mp);
1754 }
1755
1756 STATIC void
1757 xfs_icsb_enable_counter(
1758         xfs_mount_t     *mp,
1759         xfs_sb_field_t  field,
1760         uint64_t        count,
1761         uint64_t        resid)
1762 {
1763         xfs_icsb_cnts_t *cntp;
1764         int             i;
1765
1766         ASSERT((field >= XFS_SBS_ICOUNT) && (field <= XFS_SBS_FDBLOCKS));
1767
1768         xfs_icsb_lock_all_counters(mp);
1769         for_each_online_cpu(i) {
1770                 cntp = per_cpu_ptr(mp->m_sb_cnts, i);
1771                 switch (field) {
1772                 case XFS_SBS_ICOUNT:
1773                         cntp->icsb_icount = count + resid;
1774                         break;
1775                 case XFS_SBS_IFREE:
1776                         cntp->icsb_ifree = count + resid;
1777                         break;
1778                 case XFS_SBS_FDBLOCKS:
1779                         cntp->icsb_fdblocks = count + resid;
1780                         break;
1781                 default:
1782                         BUG();
1783                         break;
1784                 }
1785                 resid = 0;
1786         }
1787         clear_bit(field, &mp->m_icsb_counters);
1788         xfs_icsb_unlock_all_counters(mp);
1789 }
1790
1791 void
1792 xfs_icsb_sync_counters_locked(
1793         xfs_mount_t     *mp,
1794         int             flags)
1795 {
1796         xfs_icsb_cnts_t cnt;
1797
1798         xfs_icsb_count(mp, &cnt, flags);
1799
1800         if (!xfs_icsb_counter_disabled(mp, XFS_SBS_ICOUNT))
1801                 mp->m_sb.sb_icount = cnt.icsb_icount;
1802         if (!xfs_icsb_counter_disabled(mp, XFS_SBS_IFREE))
1803                 mp->m_sb.sb_ifree = cnt.icsb_ifree;
1804         if (!xfs_icsb_counter_disabled(mp, XFS_SBS_FDBLOCKS))
1805                 mp->m_sb.sb_fdblocks = cnt.icsb_fdblocks;
1806 }
1807
1808 /*
1809  * Accurate update of per-cpu counters to incore superblock
1810  */
1811 void
1812 xfs_icsb_sync_counters(
1813         xfs_mount_t     *mp,
1814         int             flags)
1815 {
1816         spin_lock(&mp->m_sb_lock);
1817         xfs_icsb_sync_counters_locked(mp, flags);
1818         spin_unlock(&mp->m_sb_lock);
1819 }
1820
1821 /*
1822  * Balance and enable/disable counters as necessary.
1823  *
1824  * Thresholds for re-enabling counters are somewhat magic.  inode counts are
1825  * chosen to be the same number as single on disk allocation chunk per CPU, and
1826  * free blocks is something far enough zero that we aren't going thrash when we
1827  * get near ENOSPC. We also need to supply a minimum we require per cpu to
1828  * prevent looping endlessly when xfs_alloc_space asks for more than will
1829  * be distributed to a single CPU but each CPU has enough blocks to be
1830  * reenabled.
1831  *
1832  * Note that we can be called when counters are already disabled.
1833  * xfs_icsb_disable_counter() optimises the counter locking in this case to
1834  * prevent locking every per-cpu counter needlessly.
1835  */
1836
1837 #define XFS_ICSB_INO_CNTR_REENABLE      (uint64_t)64
1838 #define XFS_ICSB_FDBLK_CNTR_REENABLE(mp) \
1839                 (uint64_t)(512 + XFS_ALLOC_SET_ASIDE(mp))
1840 STATIC void
1841 xfs_icsb_balance_counter_locked(
1842         xfs_mount_t     *mp,
1843         xfs_sb_field_t  field,
1844         int             min_per_cpu)
1845 {
1846         uint64_t        count, resid;
1847         int             weight = num_online_cpus();
1848         uint64_t        min = (uint64_t)min_per_cpu;
1849
1850         /* disable counter and sync counter */
1851         xfs_icsb_disable_counter(mp, field);
1852
1853         /* update counters  - first CPU gets residual*/
1854         switch (field) {
1855         case XFS_SBS_ICOUNT:
1856                 count = mp->m_sb.sb_icount;
1857                 resid = do_div(count, weight);
1858                 if (count < max(min, XFS_ICSB_INO_CNTR_REENABLE))
1859                         return;
1860                 break;
1861         case XFS_SBS_IFREE:
1862                 count = mp->m_sb.sb_ifree;
1863                 resid = do_div(count, weight);
1864                 if (count < max(min, XFS_ICSB_INO_CNTR_REENABLE))
1865                         return;
1866                 break;
1867         case XFS_SBS_FDBLOCKS:
1868                 count = mp->m_sb.sb_fdblocks;
1869                 resid = do_div(count, weight);
1870                 if (count < max(min, XFS_ICSB_FDBLK_CNTR_REENABLE(mp)))
1871                         return;
1872                 break;
1873         default:
1874                 BUG();
1875                 count = resid = 0;      /* quiet, gcc */
1876                 break;
1877         }
1878
1879         xfs_icsb_enable_counter(mp, field, count, resid);
1880 }
1881
1882 STATIC void
1883 xfs_icsb_balance_counter(
1884         xfs_mount_t     *mp,
1885         xfs_sb_field_t  fields,
1886         int             min_per_cpu)
1887 {
1888         spin_lock(&mp->m_sb_lock);
1889         xfs_icsb_balance_counter_locked(mp, fields, min_per_cpu);
1890         spin_unlock(&mp->m_sb_lock);
1891 }
1892
1893 int
1894 xfs_icsb_modify_counters(
1895         xfs_mount_t     *mp,
1896         xfs_sb_field_t  field,
1897         int64_t         delta,
1898         int             rsvd)
1899 {
1900         xfs_icsb_cnts_t *icsbp;
1901         long long       lcounter;       /* long counter for 64 bit fields */
1902         int             ret = 0;
1903
1904         might_sleep();
1905 again:
1906         preempt_disable();
1907         icsbp = this_cpu_ptr(mp->m_sb_cnts);
1908
1909         /*
1910          * if the counter is disabled, go to slow path
1911          */
1912         if (unlikely(xfs_icsb_counter_disabled(mp, field)))
1913                 goto slow_path;
1914         xfs_icsb_lock_cntr(icsbp);
1915         if (unlikely(xfs_icsb_counter_disabled(mp, field))) {
1916                 xfs_icsb_unlock_cntr(icsbp);
1917                 goto slow_path;
1918         }
1919
1920         switch (field) {
1921         case XFS_SBS_ICOUNT:
1922                 lcounter = icsbp->icsb_icount;
1923                 lcounter += delta;
1924                 if (unlikely(lcounter < 0))
1925                         goto balance_counter;
1926                 icsbp->icsb_icount = lcounter;
1927                 break;
1928
1929         case XFS_SBS_IFREE:
1930                 lcounter = icsbp->icsb_ifree;
1931                 lcounter += delta;
1932                 if (unlikely(lcounter < 0))
1933                         goto balance_counter;
1934                 icsbp->icsb_ifree = lcounter;
1935                 break;
1936
1937         case XFS_SBS_FDBLOCKS:
1938                 BUG_ON((mp->m_resblks - mp->m_resblks_avail) != 0);
1939
1940                 lcounter = icsbp->icsb_fdblocks - XFS_ALLOC_SET_ASIDE(mp);
1941                 lcounter += delta;
1942                 if (unlikely(lcounter < 0))
1943                         goto balance_counter;
1944                 icsbp->icsb_fdblocks = lcounter + XFS_ALLOC_SET_ASIDE(mp);
1945                 break;
1946         default:
1947                 BUG();
1948                 break;
1949         }
1950         xfs_icsb_unlock_cntr(icsbp);
1951         preempt_enable();
1952         return 0;
1953
1954 slow_path:
1955         preempt_enable();
1956
1957         /*
1958          * serialise with a mutex so we don't burn lots of cpu on
1959          * the superblock lock. We still need to hold the superblock
1960          * lock, however, when we modify the global structures.
1961          */
1962         xfs_icsb_lock(mp);
1963
1964         /*
1965          * Now running atomically.
1966          *
1967          * If the counter is enabled, someone has beaten us to rebalancing.
1968          * Drop the lock and try again in the fast path....
1969          */
1970         if (!(xfs_icsb_counter_disabled(mp, field))) {
1971                 xfs_icsb_unlock(mp);
1972                 goto again;
1973         }
1974
1975         /*
1976          * The counter is currently disabled. Because we are
1977          * running atomically here, we know a rebalance cannot
1978          * be in progress. Hence we can go straight to operating
1979          * on the global superblock. We do not call xfs_mod_incore_sb()
1980          * here even though we need to get the m_sb_lock. Doing so
1981          * will cause us to re-enter this function and deadlock.
1982          * Hence we get the m_sb_lock ourselves and then call
1983          * xfs_mod_incore_sb_unlocked() as the unlocked path operates
1984          * directly on the global counters.
1985          */
1986         spin_lock(&mp->m_sb_lock);
1987         ret = xfs_mod_incore_sb_unlocked(mp, field, delta, rsvd);
1988         spin_unlock(&mp->m_sb_lock);
1989
1990         /*
1991          * Now that we've modified the global superblock, we
1992          * may be able to re-enable the distributed counters
1993          * (e.g. lots of space just got freed). After that
1994          * we are done.
1995          */
1996         if (ret != -ENOSPC)
1997                 xfs_icsb_balance_counter(mp, field, 0);
1998         xfs_icsb_unlock(mp);
1999         return ret;
2000
2001 balance_counter:
2002         xfs_icsb_unlock_cntr(icsbp);
2003         preempt_enable();
2004
2005         /*
2006          * We may have multiple threads here if multiple per-cpu
2007          * counters run dry at the same time. This will mean we can
2008          * do more balances than strictly necessary but it is not
2009          * the common slowpath case.
2010          */
2011         xfs_icsb_lock(mp);
2012
2013         /*
2014          * running atomically.
2015          *
2016          * This will leave the counter in the correct state for future
2017          * accesses. After the rebalance, we simply try again and our retry
2018          * will either succeed through the fast path or slow path without
2019          * another balance operation being required.
2020          */
2021         xfs_icsb_balance_counter(mp, field, delta);
2022         xfs_icsb_unlock(mp);
2023         goto again;
2024 }
2025
2026 #endif