GNU Linux-libre 4.14.303-gnu1
[releases.git] / fs / ext4 / mballoc.c
1 /*
2  * Copyright (c) 2003-2006, Cluster File Systems, Inc, info@clusterfs.com
3  * Written by Alex Tomas <alex@clusterfs.com>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License version 2 as
7  * published by the Free Software Foundation.
8  *
9  * This program is distributed in the hope that it will 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 to the Free Software
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-
17  */
18
19
20 /*
21  * mballoc.c contains the multiblocks allocation routines
22  */
23
24 #include "ext4_jbd2.h"
25 #include "mballoc.h"
26 #include <linux/log2.h>
27 #include <linux/module.h>
28 #include <linux/slab.h>
29 #include <linux/nospec.h>
30 #include <linux/backing-dev.h>
31 #include <trace/events/ext4.h>
32
33 #ifdef CONFIG_EXT4_DEBUG
34 ushort ext4_mballoc_debug __read_mostly;
35
36 module_param_named(mballoc_debug, ext4_mballoc_debug, ushort, 0644);
37 MODULE_PARM_DESC(mballoc_debug, "Debugging level for ext4's mballoc");
38 #endif
39
40 /*
41  * MUSTDO:
42  *   - test ext4_ext_search_left() and ext4_ext_search_right()
43  *   - search for metadata in few groups
44  *
45  * TODO v4:
46  *   - normalization should take into account whether file is still open
47  *   - discard preallocations if no free space left (policy?)
48  *   - don't normalize tails
49  *   - quota
50  *   - reservation for superuser
51  *
52  * TODO v3:
53  *   - bitmap read-ahead (proposed by Oleg Drokin aka green)
54  *   - track min/max extents in each group for better group selection
55  *   - mb_mark_used() may allocate chunk right after splitting buddy
56  *   - tree of groups sorted by number of free blocks
57  *   - error handling
58  */
59
60 /*
61  * The allocation request involve request for multiple number of blocks
62  * near to the goal(block) value specified.
63  *
64  * During initialization phase of the allocator we decide to use the
65  * group preallocation or inode preallocation depending on the size of
66  * the file. The size of the file could be the resulting file size we
67  * would have after allocation, or the current file size, which ever
68  * is larger. If the size is less than sbi->s_mb_stream_request we
69  * select to use the group preallocation. The default value of
70  * s_mb_stream_request is 16 blocks. This can also be tuned via
71  * /sys/fs/ext4/<partition>/mb_stream_req. The value is represented in
72  * terms of number of blocks.
73  *
74  * The main motivation for having small file use group preallocation is to
75  * ensure that we have small files closer together on the disk.
76  *
77  * First stage the allocator looks at the inode prealloc list,
78  * ext4_inode_info->i_prealloc_list, which contains list of prealloc
79  * spaces for this particular inode. The inode prealloc space is
80  * represented as:
81  *
82  * pa_lstart -> the logical start block for this prealloc space
83  * pa_pstart -> the physical start block for this prealloc space
84  * pa_len    -> length for this prealloc space (in clusters)
85  * pa_free   ->  free space available in this prealloc space (in clusters)
86  *
87  * The inode preallocation space is used looking at the _logical_ start
88  * block. If only the logical file block falls within the range of prealloc
89  * space we will consume the particular prealloc space. This makes sure that
90  * we have contiguous physical blocks representing the file blocks
91  *
92  * The important thing to be noted in case of inode prealloc space is that
93  * we don't modify the values associated to inode prealloc space except
94  * pa_free.
95  *
96  * If we are not able to find blocks in the inode prealloc space and if we
97  * have the group allocation flag set then we look at the locality group
98  * prealloc space. These are per CPU prealloc list represented as
99  *
100  * ext4_sb_info.s_locality_groups[smp_processor_id()]
101  *
102  * The reason for having a per cpu locality group is to reduce the contention
103  * between CPUs. It is possible to get scheduled at this point.
104  *
105  * The locality group prealloc space is used looking at whether we have
106  * enough free space (pa_free) within the prealloc space.
107  *
108  * If we can't allocate blocks via inode prealloc or/and locality group
109  * prealloc then we look at the buddy cache. The buddy cache is represented
110  * by ext4_sb_info.s_buddy_cache (struct inode) whose file offset gets
111  * mapped to the buddy and bitmap information regarding different
112  * groups. The buddy information is attached to buddy cache inode so that
113  * we can access them through the page cache. The information regarding
114  * each group is loaded via ext4_mb_load_buddy.  The information involve
115  * block bitmap and buddy information. The information are stored in the
116  * inode as:
117  *
118  *  {                        page                        }
119  *  [ group 0 bitmap][ group 0 buddy] [group 1][ group 1]...
120  *
121  *
122  * one block each for bitmap and buddy information.  So for each group we
123  * take up 2 blocks. A page can contain blocks_per_page (PAGE_SIZE /
124  * blocksize) blocks.  So it can have information regarding groups_per_page
125  * which is blocks_per_page/2
126  *
127  * The buddy cache inode is not stored on disk. The inode is thrown
128  * away when the filesystem is unmounted.
129  *
130  * We look for count number of blocks in the buddy cache. If we were able
131  * to locate that many free blocks we return with additional information
132  * regarding rest of the contiguous physical block available
133  *
134  * Before allocating blocks via buddy cache we normalize the request
135  * blocks. This ensure we ask for more blocks that we needed. The extra
136  * blocks that we get after allocation is added to the respective prealloc
137  * list. In case of inode preallocation we follow a list of heuristics
138  * based on file size. This can be found in ext4_mb_normalize_request. If
139  * we are doing a group prealloc we try to normalize the request to
140  * sbi->s_mb_group_prealloc.  The default value of s_mb_group_prealloc is
141  * dependent on the cluster size; for non-bigalloc file systems, it is
142  * 512 blocks. This can be tuned via
143  * /sys/fs/ext4/<partition>/mb_group_prealloc. The value is represented in
144  * terms of number of blocks. If we have mounted the file system with -O
145  * stripe=<value> option the group prealloc request is normalized to the
146  * the smallest multiple of the stripe value (sbi->s_stripe) which is
147  * greater than the default mb_group_prealloc.
148  *
149  * The regular allocator (using the buddy cache) supports a few tunables.
150  *
151  * /sys/fs/ext4/<partition>/mb_min_to_scan
152  * /sys/fs/ext4/<partition>/mb_max_to_scan
153  * /sys/fs/ext4/<partition>/mb_order2_req
154  *
155  * The regular allocator uses buddy scan only if the request len is power of
156  * 2 blocks and the order of allocation is >= sbi->s_mb_order2_reqs. The
157  * value of s_mb_order2_reqs can be tuned via
158  * /sys/fs/ext4/<partition>/mb_order2_req.  If the request len is equal to
159  * stripe size (sbi->s_stripe), we try to search for contiguous block in
160  * stripe size. This should result in better allocation on RAID setups. If
161  * not, we search in the specific group using bitmap for best extents. The
162  * tunable min_to_scan and max_to_scan control the behaviour here.
163  * min_to_scan indicate how long the mballoc __must__ look for a best
164  * extent and max_to_scan indicates how long the mballoc __can__ look for a
165  * best extent in the found extents. Searching for the blocks starts with
166  * the group specified as the goal value in allocation context via
167  * ac_g_ex. Each group is first checked based on the criteria whether it
168  * can be used for allocation. ext4_mb_good_group explains how the groups are
169  * checked.
170  *
171  * Both the prealloc space are getting populated as above. So for the first
172  * request we will hit the buddy cache which will result in this prealloc
173  * space getting filled. The prealloc space is then later used for the
174  * subsequent request.
175  */
176
177 /*
178  * mballoc operates on the following data:
179  *  - on-disk bitmap
180  *  - in-core buddy (actually includes buddy and bitmap)
181  *  - preallocation descriptors (PAs)
182  *
183  * there are two types of preallocations:
184  *  - inode
185  *    assiged to specific inode and can be used for this inode only.
186  *    it describes part of inode's space preallocated to specific
187  *    physical blocks. any block from that preallocated can be used
188  *    independent. the descriptor just tracks number of blocks left
189  *    unused. so, before taking some block from descriptor, one must
190  *    make sure corresponded logical block isn't allocated yet. this
191  *    also means that freeing any block within descriptor's range
192  *    must discard all preallocated blocks.
193  *  - locality group
194  *    assigned to specific locality group which does not translate to
195  *    permanent set of inodes: inode can join and leave group. space
196  *    from this type of preallocation can be used for any inode. thus
197  *    it's consumed from the beginning to the end.
198  *
199  * relation between them can be expressed as:
200  *    in-core buddy = on-disk bitmap + preallocation descriptors
201  *
202  * this mean blocks mballoc considers used are:
203  *  - allocated blocks (persistent)
204  *  - preallocated blocks (non-persistent)
205  *
206  * consistency in mballoc world means that at any time a block is either
207  * free or used in ALL structures. notice: "any time" should not be read
208  * literally -- time is discrete and delimited by locks.
209  *
210  *  to keep it simple, we don't use block numbers, instead we count number of
211  *  blocks: how many blocks marked used/free in on-disk bitmap, buddy and PA.
212  *
213  * all operations can be expressed as:
214  *  - init buddy:                       buddy = on-disk + PAs
215  *  - new PA:                           buddy += N; PA = N
216  *  - use inode PA:                     on-disk += N; PA -= N
217  *  - discard inode PA                  buddy -= on-disk - PA; PA = 0
218  *  - use locality group PA             on-disk += N; PA -= N
219  *  - discard locality group PA         buddy -= PA; PA = 0
220  *  note: 'buddy -= on-disk - PA' is used to show that on-disk bitmap
221  *        is used in real operation because we can't know actual used
222  *        bits from PA, only from on-disk bitmap
223  *
224  * if we follow this strict logic, then all operations above should be atomic.
225  * given some of them can block, we'd have to use something like semaphores
226  * killing performance on high-end SMP hardware. let's try to relax it using
227  * the following knowledge:
228  *  1) if buddy is referenced, it's already initialized
229  *  2) while block is used in buddy and the buddy is referenced,
230  *     nobody can re-allocate that block
231  *  3) we work on bitmaps and '+' actually means 'set bits'. if on-disk has
232  *     bit set and PA claims same block, it's OK. IOW, one can set bit in
233  *     on-disk bitmap if buddy has same bit set or/and PA covers corresponded
234  *     block
235  *
236  * so, now we're building a concurrency table:
237  *  - init buddy vs.
238  *    - new PA
239  *      blocks for PA are allocated in the buddy, buddy must be referenced
240  *      until PA is linked to allocation group to avoid concurrent buddy init
241  *    - use inode PA
242  *      we need to make sure that either on-disk bitmap or PA has uptodate data
243  *      given (3) we care that PA-=N operation doesn't interfere with init
244  *    - discard inode PA
245  *      the simplest way would be to have buddy initialized by the discard
246  *    - use locality group PA
247  *      again PA-=N must be serialized with init
248  *    - discard locality group PA
249  *      the simplest way would be to have buddy initialized by the discard
250  *  - new PA vs.
251  *    - use inode PA
252  *      i_data_sem serializes them
253  *    - discard inode PA
254  *      discard process must wait until PA isn't used by another process
255  *    - use locality group PA
256  *      some mutex should serialize them
257  *    - discard locality group PA
258  *      discard process must wait until PA isn't used by another process
259  *  - use inode PA
260  *    - use inode PA
261  *      i_data_sem or another mutex should serializes them
262  *    - discard inode PA
263  *      discard process must wait until PA isn't used by another process
264  *    - use locality group PA
265  *      nothing wrong here -- they're different PAs covering different blocks
266  *    - discard locality group PA
267  *      discard process must wait until PA isn't used by another process
268  *
269  * now we're ready to make few consequences:
270  *  - PA is referenced and while it is no discard is possible
271  *  - PA is referenced until block isn't marked in on-disk bitmap
272  *  - PA changes only after on-disk bitmap
273  *  - discard must not compete with init. either init is done before
274  *    any discard or they're serialized somehow
275  *  - buddy init as sum of on-disk bitmap and PAs is done atomically
276  *
277  * a special case when we've used PA to emptiness. no need to modify buddy
278  * in this case, but we should care about concurrent init
279  *
280  */
281
282  /*
283  * Logic in few words:
284  *
285  *  - allocation:
286  *    load group
287  *    find blocks
288  *    mark bits in on-disk bitmap
289  *    release group
290  *
291  *  - use preallocation:
292  *    find proper PA (per-inode or group)
293  *    load group
294  *    mark bits in on-disk bitmap
295  *    release group
296  *    release PA
297  *
298  *  - free:
299  *    load group
300  *    mark bits in on-disk bitmap
301  *    release group
302  *
303  *  - discard preallocations in group:
304  *    mark PAs deleted
305  *    move them onto local list
306  *    load on-disk bitmap
307  *    load group
308  *    remove PA from object (inode or locality group)
309  *    mark free blocks in-core
310  *
311  *  - discard inode's preallocations:
312  */
313
314 /*
315  * Locking rules
316  *
317  * Locks:
318  *  - bitlock on a group        (group)
319  *  - object (inode/locality)   (object)
320  *  - per-pa lock               (pa)
321  *
322  * Paths:
323  *  - new pa
324  *    object
325  *    group
326  *
327  *  - find and use pa:
328  *    pa
329  *
330  *  - release consumed pa:
331  *    pa
332  *    group
333  *    object
334  *
335  *  - generate in-core bitmap:
336  *    group
337  *        pa
338  *
339  *  - discard all for given object (inode, locality group):
340  *    object
341  *        pa
342  *    group
343  *
344  *  - discard all for given group:
345  *    group
346  *        pa
347  *    group
348  *        object
349  *
350  */
351 static struct kmem_cache *ext4_pspace_cachep;
352 static struct kmem_cache *ext4_ac_cachep;
353 static struct kmem_cache *ext4_free_data_cachep;
354
355 /* We create slab caches for groupinfo data structures based on the
356  * superblock block size.  There will be one per mounted filesystem for
357  * each unique s_blocksize_bits */
358 #define NR_GRPINFO_CACHES 8
359 static struct kmem_cache *ext4_groupinfo_caches[NR_GRPINFO_CACHES];
360
361 static const char * const ext4_groupinfo_slab_names[NR_GRPINFO_CACHES] = {
362         "ext4_groupinfo_1k", "ext4_groupinfo_2k", "ext4_groupinfo_4k",
363         "ext4_groupinfo_8k", "ext4_groupinfo_16k", "ext4_groupinfo_32k",
364         "ext4_groupinfo_64k", "ext4_groupinfo_128k"
365 };
366
367 static void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
368                                         ext4_group_t group);
369 static void ext4_mb_generate_from_freelist(struct super_block *sb, void *bitmap,
370                                                 ext4_group_t group);
371
372 static inline void *mb_correct_addr_and_bit(int *bit, void *addr)
373 {
374 #if BITS_PER_LONG == 64
375         *bit += ((unsigned long) addr & 7UL) << 3;
376         addr = (void *) ((unsigned long) addr & ~7UL);
377 #elif BITS_PER_LONG == 32
378         *bit += ((unsigned long) addr & 3UL) << 3;
379         addr = (void *) ((unsigned long) addr & ~3UL);
380 #else
381 #error "how many bits you are?!"
382 #endif
383         return addr;
384 }
385
386 static inline int mb_test_bit(int bit, void *addr)
387 {
388         /*
389          * ext4_test_bit on architecture like powerpc
390          * needs unsigned long aligned address
391          */
392         addr = mb_correct_addr_and_bit(&bit, addr);
393         return ext4_test_bit(bit, addr);
394 }
395
396 static inline void mb_set_bit(int bit, void *addr)
397 {
398         addr = mb_correct_addr_and_bit(&bit, addr);
399         ext4_set_bit(bit, addr);
400 }
401
402 static inline void mb_clear_bit(int bit, void *addr)
403 {
404         addr = mb_correct_addr_and_bit(&bit, addr);
405         ext4_clear_bit(bit, addr);
406 }
407
408 static inline int mb_test_and_clear_bit(int bit, void *addr)
409 {
410         addr = mb_correct_addr_and_bit(&bit, addr);
411         return ext4_test_and_clear_bit(bit, addr);
412 }
413
414 static inline int mb_find_next_zero_bit(void *addr, int max, int start)
415 {
416         int fix = 0, ret, tmpmax;
417         addr = mb_correct_addr_and_bit(&fix, addr);
418         tmpmax = max + fix;
419         start += fix;
420
421         ret = ext4_find_next_zero_bit(addr, tmpmax, start) - fix;
422         if (ret > max)
423                 return max;
424         return ret;
425 }
426
427 static inline int mb_find_next_bit(void *addr, int max, int start)
428 {
429         int fix = 0, ret, tmpmax;
430         addr = mb_correct_addr_and_bit(&fix, addr);
431         tmpmax = max + fix;
432         start += fix;
433
434         ret = ext4_find_next_bit(addr, tmpmax, start) - fix;
435         if (ret > max)
436                 return max;
437         return ret;
438 }
439
440 static void *mb_find_buddy(struct ext4_buddy *e4b, int order, int *max)
441 {
442         char *bb;
443
444         BUG_ON(e4b->bd_bitmap == e4b->bd_buddy);
445         BUG_ON(max == NULL);
446
447         if (order > e4b->bd_blkbits + 1) {
448                 *max = 0;
449                 return NULL;
450         }
451
452         /* at order 0 we see each particular block */
453         if (order == 0) {
454                 *max = 1 << (e4b->bd_blkbits + 3);
455                 return e4b->bd_bitmap;
456         }
457
458         bb = e4b->bd_buddy + EXT4_SB(e4b->bd_sb)->s_mb_offsets[order];
459         *max = EXT4_SB(e4b->bd_sb)->s_mb_maxs[order];
460
461         return bb;
462 }
463
464 #ifdef DOUBLE_CHECK
465 static void mb_free_blocks_double(struct inode *inode, struct ext4_buddy *e4b,
466                            int first, int count)
467 {
468         int i;
469         struct super_block *sb = e4b->bd_sb;
470
471         if (unlikely(e4b->bd_info->bb_bitmap == NULL))
472                 return;
473         assert_spin_locked(ext4_group_lock_ptr(sb, e4b->bd_group));
474         for (i = 0; i < count; i++) {
475                 if (!mb_test_bit(first + i, e4b->bd_info->bb_bitmap)) {
476                         ext4_fsblk_t blocknr;
477
478                         blocknr = ext4_group_first_block_no(sb, e4b->bd_group);
479                         blocknr += EXT4_C2B(EXT4_SB(sb), first + i);
480                         ext4_grp_locked_error(sb, e4b->bd_group,
481                                               inode ? inode->i_ino : 0,
482                                               blocknr,
483                                               "freeing block already freed "
484                                               "(bit %u)",
485                                               first + i);
486                 }
487                 mb_clear_bit(first + i, e4b->bd_info->bb_bitmap);
488         }
489 }
490
491 static void mb_mark_used_double(struct ext4_buddy *e4b, int first, int count)
492 {
493         int i;
494
495         if (unlikely(e4b->bd_info->bb_bitmap == NULL))
496                 return;
497         assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
498         for (i = 0; i < count; i++) {
499                 BUG_ON(mb_test_bit(first + i, e4b->bd_info->bb_bitmap));
500                 mb_set_bit(first + i, e4b->bd_info->bb_bitmap);
501         }
502 }
503
504 static void mb_cmp_bitmaps(struct ext4_buddy *e4b, void *bitmap)
505 {
506         if (memcmp(e4b->bd_info->bb_bitmap, bitmap, e4b->bd_sb->s_blocksize)) {
507                 unsigned char *b1, *b2;
508                 int i;
509                 b1 = (unsigned char *) e4b->bd_info->bb_bitmap;
510                 b2 = (unsigned char *) bitmap;
511                 for (i = 0; i < e4b->bd_sb->s_blocksize; i++) {
512                         if (b1[i] != b2[i]) {
513                                 ext4_msg(e4b->bd_sb, KERN_ERR,
514                                          "corruption in group %u "
515                                          "at byte %u(%u): %x in copy != %x "
516                                          "on disk/prealloc",
517                                          e4b->bd_group, i, i * 8, b1[i], b2[i]);
518                                 BUG();
519                         }
520                 }
521         }
522 }
523
524 #else
525 static inline void mb_free_blocks_double(struct inode *inode,
526                                 struct ext4_buddy *e4b, int first, int count)
527 {
528         return;
529 }
530 static inline void mb_mark_used_double(struct ext4_buddy *e4b,
531                                                 int first, int count)
532 {
533         return;
534 }
535 static inline void mb_cmp_bitmaps(struct ext4_buddy *e4b, void *bitmap)
536 {
537         return;
538 }
539 #endif
540
541 #ifdef AGGRESSIVE_CHECK
542
543 #define MB_CHECK_ASSERT(assert)                                         \
544 do {                                                                    \
545         if (!(assert)) {                                                \
546                 printk(KERN_EMERG                                       \
547                         "Assertion failure in %s() at %s:%d: \"%s\"\n", \
548                         function, file, line, # assert);                \
549                 BUG();                                                  \
550         }                                                               \
551 } while (0)
552
553 static int __mb_check_buddy(struct ext4_buddy *e4b, char *file,
554                                 const char *function, int line)
555 {
556         struct super_block *sb = e4b->bd_sb;
557         int order = e4b->bd_blkbits + 1;
558         int max;
559         int max2;
560         int i;
561         int j;
562         int k;
563         int count;
564         struct ext4_group_info *grp;
565         int fragments = 0;
566         int fstart;
567         struct list_head *cur;
568         void *buddy;
569         void *buddy2;
570
571         {
572                 static int mb_check_counter;
573                 if (mb_check_counter++ % 100 != 0)
574                         return 0;
575         }
576
577         while (order > 1) {
578                 buddy = mb_find_buddy(e4b, order, &max);
579                 MB_CHECK_ASSERT(buddy);
580                 buddy2 = mb_find_buddy(e4b, order - 1, &max2);
581                 MB_CHECK_ASSERT(buddy2);
582                 MB_CHECK_ASSERT(buddy != buddy2);
583                 MB_CHECK_ASSERT(max * 2 == max2);
584
585                 count = 0;
586                 for (i = 0; i < max; i++) {
587
588                         if (mb_test_bit(i, buddy)) {
589                                 /* only single bit in buddy2 may be 1 */
590                                 if (!mb_test_bit(i << 1, buddy2)) {
591                                         MB_CHECK_ASSERT(
592                                                 mb_test_bit((i<<1)+1, buddy2));
593                                 } else if (!mb_test_bit((i << 1) + 1, buddy2)) {
594                                         MB_CHECK_ASSERT(
595                                                 mb_test_bit(i << 1, buddy2));
596                                 }
597                                 continue;
598                         }
599
600                         /* both bits in buddy2 must be 1 */
601                         MB_CHECK_ASSERT(mb_test_bit(i << 1, buddy2));
602                         MB_CHECK_ASSERT(mb_test_bit((i << 1) + 1, buddy2));
603
604                         for (j = 0; j < (1 << order); j++) {
605                                 k = (i * (1 << order)) + j;
606                                 MB_CHECK_ASSERT(
607                                         !mb_test_bit(k, e4b->bd_bitmap));
608                         }
609                         count++;
610                 }
611                 MB_CHECK_ASSERT(e4b->bd_info->bb_counters[order] == count);
612                 order--;
613         }
614
615         fstart = -1;
616         buddy = mb_find_buddy(e4b, 0, &max);
617         for (i = 0; i < max; i++) {
618                 if (!mb_test_bit(i, buddy)) {
619                         MB_CHECK_ASSERT(i >= e4b->bd_info->bb_first_free);
620                         if (fstart == -1) {
621                                 fragments++;
622                                 fstart = i;
623                         }
624                         continue;
625                 }
626                 fstart = -1;
627                 /* check used bits only */
628                 for (j = 0; j < e4b->bd_blkbits + 1; j++) {
629                         buddy2 = mb_find_buddy(e4b, j, &max2);
630                         k = i >> j;
631                         MB_CHECK_ASSERT(k < max2);
632                         MB_CHECK_ASSERT(mb_test_bit(k, buddy2));
633                 }
634         }
635         MB_CHECK_ASSERT(!EXT4_MB_GRP_NEED_INIT(e4b->bd_info));
636         MB_CHECK_ASSERT(e4b->bd_info->bb_fragments == fragments);
637
638         grp = ext4_get_group_info(sb, e4b->bd_group);
639         list_for_each(cur, &grp->bb_prealloc_list) {
640                 ext4_group_t groupnr;
641                 struct ext4_prealloc_space *pa;
642                 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
643                 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &groupnr, &k);
644                 MB_CHECK_ASSERT(groupnr == e4b->bd_group);
645                 for (i = 0; i < pa->pa_len; i++)
646                         MB_CHECK_ASSERT(mb_test_bit(k + i, buddy));
647         }
648         return 0;
649 }
650 #undef MB_CHECK_ASSERT
651 #define mb_check_buddy(e4b) __mb_check_buddy(e4b,       \
652                                         __FILE__, __func__, __LINE__)
653 #else
654 #define mb_check_buddy(e4b)
655 #endif
656
657 /*
658  * Divide blocks started from @first with length @len into
659  * smaller chunks with power of 2 blocks.
660  * Clear the bits in bitmap which the blocks of the chunk(s) covered,
661  * then increase bb_counters[] for corresponded chunk size.
662  */
663 static void ext4_mb_mark_free_simple(struct super_block *sb,
664                                 void *buddy, ext4_grpblk_t first, ext4_grpblk_t len,
665                                         struct ext4_group_info *grp)
666 {
667         struct ext4_sb_info *sbi = EXT4_SB(sb);
668         ext4_grpblk_t min;
669         ext4_grpblk_t max;
670         ext4_grpblk_t chunk;
671         unsigned int border;
672
673         BUG_ON(len > EXT4_CLUSTERS_PER_GROUP(sb));
674
675         border = 2 << sb->s_blocksize_bits;
676
677         while (len > 0) {
678                 /* find how many blocks can be covered since this position */
679                 max = ffs(first | border) - 1;
680
681                 /* find how many blocks of power 2 we need to mark */
682                 min = fls(len) - 1;
683
684                 if (max < min)
685                         min = max;
686                 chunk = 1 << min;
687
688                 /* mark multiblock chunks only */
689                 grp->bb_counters[min]++;
690                 if (min > 0)
691                         mb_clear_bit(first >> min,
692                                      buddy + sbi->s_mb_offsets[min]);
693
694                 len -= chunk;
695                 first += chunk;
696         }
697 }
698
699 /*
700  * Cache the order of the largest free extent we have available in this block
701  * group.
702  */
703 static void
704 mb_set_largest_free_order(struct super_block *sb, struct ext4_group_info *grp)
705 {
706         int i;
707         int bits;
708
709         grp->bb_largest_free_order = -1; /* uninit */
710
711         bits = sb->s_blocksize_bits + 1;
712         for (i = bits; i >= 0; i--) {
713                 if (grp->bb_counters[i] > 0) {
714                         grp->bb_largest_free_order = i;
715                         break;
716                 }
717         }
718 }
719
720 static noinline_for_stack
721 void ext4_mb_generate_buddy(struct super_block *sb,
722                                 void *buddy, void *bitmap, ext4_group_t group)
723 {
724         struct ext4_group_info *grp = ext4_get_group_info(sb, group);
725         struct ext4_sb_info *sbi = EXT4_SB(sb);
726         ext4_grpblk_t max = EXT4_CLUSTERS_PER_GROUP(sb);
727         ext4_grpblk_t i = 0;
728         ext4_grpblk_t first;
729         ext4_grpblk_t len;
730         unsigned free = 0;
731         unsigned fragments = 0;
732         unsigned long long period = get_cycles();
733
734         /* initialize buddy from bitmap which is aggregation
735          * of on-disk bitmap and preallocations */
736         i = mb_find_next_zero_bit(bitmap, max, 0);
737         grp->bb_first_free = i;
738         while (i < max) {
739                 fragments++;
740                 first = i;
741                 i = mb_find_next_bit(bitmap, max, i);
742                 len = i - first;
743                 free += len;
744                 if (len > 1)
745                         ext4_mb_mark_free_simple(sb, buddy, first, len, grp);
746                 else
747                         grp->bb_counters[0]++;
748                 if (i < max)
749                         i = mb_find_next_zero_bit(bitmap, max, i);
750         }
751         grp->bb_fragments = fragments;
752
753         if (free != grp->bb_free) {
754                 ext4_grp_locked_error(sb, group, 0, 0,
755                                       "block bitmap and bg descriptor "
756                                       "inconsistent: %u vs %u free clusters",
757                                       free, grp->bb_free);
758                 /*
759                  * If we intend to continue, we consider group descriptor
760                  * corrupt and update bb_free using bitmap value
761                  */
762                 grp->bb_free = free;
763                 if (!EXT4_MB_GRP_BBITMAP_CORRUPT(grp))
764                         percpu_counter_sub(&sbi->s_freeclusters_counter,
765                                            grp->bb_free);
766                 set_bit(EXT4_GROUP_INFO_BBITMAP_CORRUPT_BIT, &grp->bb_state);
767         }
768         mb_set_largest_free_order(sb, grp);
769
770         clear_bit(EXT4_GROUP_INFO_NEED_INIT_BIT, &(grp->bb_state));
771
772         period = get_cycles() - period;
773         spin_lock(&EXT4_SB(sb)->s_bal_lock);
774         EXT4_SB(sb)->s_mb_buddies_generated++;
775         EXT4_SB(sb)->s_mb_generation_time += period;
776         spin_unlock(&EXT4_SB(sb)->s_bal_lock);
777 }
778
779 static void mb_regenerate_buddy(struct ext4_buddy *e4b)
780 {
781         int count;
782         int order = 1;
783         void *buddy;
784
785         while ((buddy = mb_find_buddy(e4b, order++, &count))) {
786                 ext4_set_bits(buddy, 0, count);
787         }
788         e4b->bd_info->bb_fragments = 0;
789         memset(e4b->bd_info->bb_counters, 0,
790                 sizeof(*e4b->bd_info->bb_counters) *
791                 (e4b->bd_sb->s_blocksize_bits + 2));
792
793         ext4_mb_generate_buddy(e4b->bd_sb, e4b->bd_buddy,
794                 e4b->bd_bitmap, e4b->bd_group);
795 }
796
797 /* The buddy information is attached the buddy cache inode
798  * for convenience. The information regarding each group
799  * is loaded via ext4_mb_load_buddy. The information involve
800  * block bitmap and buddy information. The information are
801  * stored in the inode as
802  *
803  * {                        page                        }
804  * [ group 0 bitmap][ group 0 buddy] [group 1][ group 1]...
805  *
806  *
807  * one block each for bitmap and buddy information.
808  * So for each group we take up 2 blocks. A page can
809  * contain blocks_per_page (PAGE_SIZE / blocksize)  blocks.
810  * So it can have information regarding groups_per_page which
811  * is blocks_per_page/2
812  *
813  * Locking note:  This routine takes the block group lock of all groups
814  * for this page; do not hold this lock when calling this routine!
815  */
816
817 static int ext4_mb_init_cache(struct page *page, char *incore, gfp_t gfp)
818 {
819         ext4_group_t ngroups;
820         int blocksize;
821         int blocks_per_page;
822         int groups_per_page;
823         int err = 0;
824         int i;
825         ext4_group_t first_group, group;
826         int first_block;
827         struct super_block *sb;
828         struct buffer_head *bhs;
829         struct buffer_head **bh = NULL;
830         struct inode *inode;
831         char *data;
832         char *bitmap;
833         struct ext4_group_info *grinfo;
834
835         mb_debug(1, "init page %lu\n", page->index);
836
837         inode = page->mapping->host;
838         sb = inode->i_sb;
839         ngroups = ext4_get_groups_count(sb);
840         blocksize = i_blocksize(inode);
841         blocks_per_page = PAGE_SIZE / blocksize;
842
843         groups_per_page = blocks_per_page >> 1;
844         if (groups_per_page == 0)
845                 groups_per_page = 1;
846
847         /* allocate buffer_heads to read bitmaps */
848         if (groups_per_page > 1) {
849                 i = sizeof(struct buffer_head *) * groups_per_page;
850                 bh = kzalloc(i, gfp);
851                 if (bh == NULL) {
852                         err = -ENOMEM;
853                         goto out;
854                 }
855         } else
856                 bh = &bhs;
857
858         first_group = page->index * blocks_per_page / 2;
859
860         /* read all groups the page covers into the cache */
861         for (i = 0, group = first_group; i < groups_per_page; i++, group++) {
862                 if (group >= ngroups)
863                         break;
864
865                 grinfo = ext4_get_group_info(sb, group);
866                 /*
867                  * If page is uptodate then we came here after online resize
868                  * which added some new uninitialized group info structs, so
869                  * we must skip all initialized uptodate buddies on the page,
870                  * which may be currently in use by an allocating task.
871                  */
872                 if (PageUptodate(page) && !EXT4_MB_GRP_NEED_INIT(grinfo)) {
873                         bh[i] = NULL;
874                         continue;
875                 }
876                 bh[i] = ext4_read_block_bitmap_nowait(sb, group);
877                 if (IS_ERR(bh[i])) {
878                         err = PTR_ERR(bh[i]);
879                         bh[i] = NULL;
880                         goto out;
881                 }
882                 mb_debug(1, "read bitmap for group %u\n", group);
883         }
884
885         /* wait for I/O completion */
886         for (i = 0, group = first_group; i < groups_per_page; i++, group++) {
887                 int err2;
888
889                 if (!bh[i])
890                         continue;
891                 err2 = ext4_wait_block_bitmap(sb, group, bh[i]);
892                 if (!err)
893                         err = err2;
894         }
895
896         first_block = page->index * blocks_per_page;
897         for (i = 0; i < blocks_per_page; i++) {
898                 group = (first_block + i) >> 1;
899                 if (group >= ngroups)
900                         break;
901
902                 if (!bh[group - first_group])
903                         /* skip initialized uptodate buddy */
904                         continue;
905
906                 if (!buffer_verified(bh[group - first_group]))
907                         /* Skip faulty bitmaps */
908                         continue;
909                 err = 0;
910
911                 /*
912                  * data carry information regarding this
913                  * particular group in the format specified
914                  * above
915                  *
916                  */
917                 data = page_address(page) + (i * blocksize);
918                 bitmap = bh[group - first_group]->b_data;
919
920                 /*
921                  * We place the buddy block and bitmap block
922                  * close together
923                  */
924                 if ((first_block + i) & 1) {
925                         /* this is block of buddy */
926                         BUG_ON(incore == NULL);
927                         mb_debug(1, "put buddy for group %u in page %lu/%x\n",
928                                 group, page->index, i * blocksize);
929                         trace_ext4_mb_buddy_bitmap_load(sb, group);
930                         grinfo = ext4_get_group_info(sb, group);
931                         grinfo->bb_fragments = 0;
932                         memset(grinfo->bb_counters, 0,
933                                sizeof(*grinfo->bb_counters) *
934                                 (sb->s_blocksize_bits+2));
935                         /*
936                          * incore got set to the group block bitmap below
937                          */
938                         ext4_lock_group(sb, group);
939                         /* init the buddy */
940                         memset(data, 0xff, blocksize);
941                         ext4_mb_generate_buddy(sb, data, incore, group);
942                         ext4_unlock_group(sb, group);
943                         incore = NULL;
944                 } else {
945                         /* this is block of bitmap */
946                         BUG_ON(incore != NULL);
947                         mb_debug(1, "put bitmap for group %u in page %lu/%x\n",
948                                 group, page->index, i * blocksize);
949                         trace_ext4_mb_bitmap_load(sb, group);
950
951                         /* see comments in ext4_mb_put_pa() */
952                         ext4_lock_group(sb, group);
953                         memcpy(data, bitmap, blocksize);
954
955                         /* mark all preallocated blks used in in-core bitmap */
956                         ext4_mb_generate_from_pa(sb, data, group);
957                         ext4_mb_generate_from_freelist(sb, data, group);
958                         ext4_unlock_group(sb, group);
959
960                         /* set incore so that the buddy information can be
961                          * generated using this
962                          */
963                         incore = data;
964                 }
965         }
966         SetPageUptodate(page);
967
968 out:
969         if (bh) {
970                 for (i = 0; i < groups_per_page; i++)
971                         brelse(bh[i]);
972                 if (bh != &bhs)
973                         kfree(bh);
974         }
975         return err;
976 }
977
978 /*
979  * Lock the buddy and bitmap pages. This make sure other parallel init_group
980  * on the same buddy page doesn't happen whild holding the buddy page lock.
981  * Return locked buddy and bitmap pages on e4b struct. If buddy and bitmap
982  * are on the same page e4b->bd_buddy_page is NULL and return value is 0.
983  */
984 static int ext4_mb_get_buddy_page_lock(struct super_block *sb,
985                 ext4_group_t group, struct ext4_buddy *e4b, gfp_t gfp)
986 {
987         struct inode *inode = EXT4_SB(sb)->s_buddy_cache;
988         int block, pnum, poff;
989         int blocks_per_page;
990         struct page *page;
991
992         e4b->bd_buddy_page = NULL;
993         e4b->bd_bitmap_page = NULL;
994
995         blocks_per_page = PAGE_SIZE / sb->s_blocksize;
996         /*
997          * the buddy cache inode stores the block bitmap
998          * and buddy information in consecutive blocks.
999          * So for each group we need two blocks.
1000          */
1001         block = group * 2;
1002         pnum = block / blocks_per_page;
1003         poff = block % blocks_per_page;
1004         page = find_or_create_page(inode->i_mapping, pnum, gfp);
1005         if (!page)
1006                 return -ENOMEM;
1007         BUG_ON(page->mapping != inode->i_mapping);
1008         e4b->bd_bitmap_page = page;
1009         e4b->bd_bitmap = page_address(page) + (poff * sb->s_blocksize);
1010
1011         if (blocks_per_page >= 2) {
1012                 /* buddy and bitmap are on the same page */
1013                 return 0;
1014         }
1015
1016         block++;
1017         pnum = block / blocks_per_page;
1018         page = find_or_create_page(inode->i_mapping, pnum, gfp);
1019         if (!page)
1020                 return -ENOMEM;
1021         BUG_ON(page->mapping != inode->i_mapping);
1022         e4b->bd_buddy_page = page;
1023         return 0;
1024 }
1025
1026 static void ext4_mb_put_buddy_page_lock(struct ext4_buddy *e4b)
1027 {
1028         if (e4b->bd_bitmap_page) {
1029                 unlock_page(e4b->bd_bitmap_page);
1030                 put_page(e4b->bd_bitmap_page);
1031         }
1032         if (e4b->bd_buddy_page) {
1033                 unlock_page(e4b->bd_buddy_page);
1034                 put_page(e4b->bd_buddy_page);
1035         }
1036 }
1037
1038 /*
1039  * Locking note:  This routine calls ext4_mb_init_cache(), which takes the
1040  * block group lock of all groups for this page; do not hold the BG lock when
1041  * calling this routine!
1042  */
1043 static noinline_for_stack
1044 int ext4_mb_init_group(struct super_block *sb, ext4_group_t group, gfp_t gfp)
1045 {
1046
1047         struct ext4_group_info *this_grp;
1048         struct ext4_buddy e4b;
1049         struct page *page;
1050         int ret = 0;
1051
1052         might_sleep();
1053         mb_debug(1, "init group %u\n", group);
1054         this_grp = ext4_get_group_info(sb, group);
1055         /*
1056          * This ensures that we don't reinit the buddy cache
1057          * page which map to the group from which we are already
1058          * allocating. If we are looking at the buddy cache we would
1059          * have taken a reference using ext4_mb_load_buddy and that
1060          * would have pinned buddy page to page cache.
1061          * The call to ext4_mb_get_buddy_page_lock will mark the
1062          * page accessed.
1063          */
1064         ret = ext4_mb_get_buddy_page_lock(sb, group, &e4b, gfp);
1065         if (ret || !EXT4_MB_GRP_NEED_INIT(this_grp)) {
1066                 /*
1067                  * somebody initialized the group
1068                  * return without doing anything
1069                  */
1070                 goto err;
1071         }
1072
1073         page = e4b.bd_bitmap_page;
1074         ret = ext4_mb_init_cache(page, NULL, gfp);
1075         if (ret)
1076                 goto err;
1077         if (!PageUptodate(page)) {
1078                 ret = -EIO;
1079                 goto err;
1080         }
1081
1082         if (e4b.bd_buddy_page == NULL) {
1083                 /*
1084                  * If both the bitmap and buddy are in
1085                  * the same page we don't need to force
1086                  * init the buddy
1087                  */
1088                 ret = 0;
1089                 goto err;
1090         }
1091         /* init buddy cache */
1092         page = e4b.bd_buddy_page;
1093         ret = ext4_mb_init_cache(page, e4b.bd_bitmap, gfp);
1094         if (ret)
1095                 goto err;
1096         if (!PageUptodate(page)) {
1097                 ret = -EIO;
1098                 goto err;
1099         }
1100 err:
1101         ext4_mb_put_buddy_page_lock(&e4b);
1102         return ret;
1103 }
1104
1105 /*
1106  * Locking note:  This routine calls ext4_mb_init_cache(), which takes the
1107  * block group lock of all groups for this page; do not hold the BG lock when
1108  * calling this routine!
1109  */
1110 static noinline_for_stack int
1111 ext4_mb_load_buddy_gfp(struct super_block *sb, ext4_group_t group,
1112                        struct ext4_buddy *e4b, gfp_t gfp)
1113 {
1114         int blocks_per_page;
1115         int block;
1116         int pnum;
1117         int poff;
1118         struct page *page;
1119         int ret;
1120         struct ext4_group_info *grp;
1121         struct ext4_sb_info *sbi = EXT4_SB(sb);
1122         struct inode *inode = sbi->s_buddy_cache;
1123
1124         might_sleep();
1125         mb_debug(1, "load group %u\n", group);
1126
1127         blocks_per_page = PAGE_SIZE / sb->s_blocksize;
1128         grp = ext4_get_group_info(sb, group);
1129
1130         e4b->bd_blkbits = sb->s_blocksize_bits;
1131         e4b->bd_info = grp;
1132         e4b->bd_sb = sb;
1133         e4b->bd_group = group;
1134         e4b->bd_buddy_page = NULL;
1135         e4b->bd_bitmap_page = NULL;
1136
1137         if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
1138                 /*
1139                  * we need full data about the group
1140                  * to make a good selection
1141                  */
1142                 ret = ext4_mb_init_group(sb, group, gfp);
1143                 if (ret)
1144                         return ret;
1145         }
1146
1147         /*
1148          * the buddy cache inode stores the block bitmap
1149          * and buddy information in consecutive blocks.
1150          * So for each group we need two blocks.
1151          */
1152         block = group * 2;
1153         pnum = block / blocks_per_page;
1154         poff = block % blocks_per_page;
1155
1156         /* we could use find_or_create_page(), but it locks page
1157          * what we'd like to avoid in fast path ... */
1158         page = find_get_page_flags(inode->i_mapping, pnum, FGP_ACCESSED);
1159         if (page == NULL || !PageUptodate(page)) {
1160                 if (page)
1161                         /*
1162                          * drop the page reference and try
1163                          * to get the page with lock. If we
1164                          * are not uptodate that implies
1165                          * somebody just created the page but
1166                          * is yet to initialize the same. So
1167                          * wait for it to initialize.
1168                          */
1169                         put_page(page);
1170                 page = find_or_create_page(inode->i_mapping, pnum, gfp);
1171                 if (page) {
1172                         BUG_ON(page->mapping != inode->i_mapping);
1173                         if (!PageUptodate(page)) {
1174                                 ret = ext4_mb_init_cache(page, NULL, gfp);
1175                                 if (ret) {
1176                                         unlock_page(page);
1177                                         goto err;
1178                                 }
1179                                 mb_cmp_bitmaps(e4b, page_address(page) +
1180                                                (poff * sb->s_blocksize));
1181                         }
1182                         unlock_page(page);
1183                 }
1184         }
1185         if (page == NULL) {
1186                 ret = -ENOMEM;
1187                 goto err;
1188         }
1189         if (!PageUptodate(page)) {
1190                 ret = -EIO;
1191                 goto err;
1192         }
1193
1194         /* Pages marked accessed already */
1195         e4b->bd_bitmap_page = page;
1196         e4b->bd_bitmap = page_address(page) + (poff * sb->s_blocksize);
1197
1198         block++;
1199         pnum = block / blocks_per_page;
1200         poff = block % blocks_per_page;
1201
1202         page = find_get_page_flags(inode->i_mapping, pnum, FGP_ACCESSED);
1203         if (page == NULL || !PageUptodate(page)) {
1204                 if (page)
1205                         put_page(page);
1206                 page = find_or_create_page(inode->i_mapping, pnum, gfp);
1207                 if (page) {
1208                         BUG_ON(page->mapping != inode->i_mapping);
1209                         if (!PageUptodate(page)) {
1210                                 ret = ext4_mb_init_cache(page, e4b->bd_bitmap,
1211                                                          gfp);
1212                                 if (ret) {
1213                                         unlock_page(page);
1214                                         goto err;
1215                                 }
1216                         }
1217                         unlock_page(page);
1218                 }
1219         }
1220         if (page == NULL) {
1221                 ret = -ENOMEM;
1222                 goto err;
1223         }
1224         if (!PageUptodate(page)) {
1225                 ret = -EIO;
1226                 goto err;
1227         }
1228
1229         /* Pages marked accessed already */
1230         e4b->bd_buddy_page = page;
1231         e4b->bd_buddy = page_address(page) + (poff * sb->s_blocksize);
1232
1233         BUG_ON(e4b->bd_bitmap_page == NULL);
1234         BUG_ON(e4b->bd_buddy_page == NULL);
1235
1236         return 0;
1237
1238 err:
1239         if (page)
1240                 put_page(page);
1241         if (e4b->bd_bitmap_page)
1242                 put_page(e4b->bd_bitmap_page);
1243         if (e4b->bd_buddy_page)
1244                 put_page(e4b->bd_buddy_page);
1245         e4b->bd_buddy = NULL;
1246         e4b->bd_bitmap = NULL;
1247         return ret;
1248 }
1249
1250 static int ext4_mb_load_buddy(struct super_block *sb, ext4_group_t group,
1251                               struct ext4_buddy *e4b)
1252 {
1253         return ext4_mb_load_buddy_gfp(sb, group, e4b, GFP_NOFS);
1254 }
1255
1256 static void ext4_mb_unload_buddy(struct ext4_buddy *e4b)
1257 {
1258         if (e4b->bd_bitmap_page)
1259                 put_page(e4b->bd_bitmap_page);
1260         if (e4b->bd_buddy_page)
1261                 put_page(e4b->bd_buddy_page);
1262 }
1263
1264
1265 static int mb_find_order_for_block(struct ext4_buddy *e4b, int block)
1266 {
1267         int order = 1;
1268         int bb_incr = 1 << (e4b->bd_blkbits - 1);
1269         void *bb;
1270
1271         BUG_ON(e4b->bd_bitmap == e4b->bd_buddy);
1272         BUG_ON(block >= (1 << (e4b->bd_blkbits + 3)));
1273
1274         bb = e4b->bd_buddy;
1275         while (order <= e4b->bd_blkbits + 1) {
1276                 block = block >> 1;
1277                 if (!mb_test_bit(block, bb)) {
1278                         /* this block is part of buddy of order 'order' */
1279                         return order;
1280                 }
1281                 bb += bb_incr;
1282                 bb_incr >>= 1;
1283                 order++;
1284         }
1285         return 0;
1286 }
1287
1288 static void mb_clear_bits(void *bm, int cur, int len)
1289 {
1290         __u32 *addr;
1291
1292         len = cur + len;
1293         while (cur < len) {
1294                 if ((cur & 31) == 0 && (len - cur) >= 32) {
1295                         /* fast path: clear whole word at once */
1296                         addr = bm + (cur >> 3);
1297                         *addr = 0;
1298                         cur += 32;
1299                         continue;
1300                 }
1301                 mb_clear_bit(cur, bm);
1302                 cur++;
1303         }
1304 }
1305
1306 /* clear bits in given range
1307  * will return first found zero bit if any, -1 otherwise
1308  */
1309 static int mb_test_and_clear_bits(void *bm, int cur, int len)
1310 {
1311         __u32 *addr;
1312         int zero_bit = -1;
1313
1314         len = cur + len;
1315         while (cur < len) {
1316                 if ((cur & 31) == 0 && (len - cur) >= 32) {
1317                         /* fast path: clear whole word at once */
1318                         addr = bm + (cur >> 3);
1319                         if (*addr != (__u32)(-1) && zero_bit == -1)
1320                                 zero_bit = cur + mb_find_next_zero_bit(addr, 32, 0);
1321                         *addr = 0;
1322                         cur += 32;
1323                         continue;
1324                 }
1325                 if (!mb_test_and_clear_bit(cur, bm) && zero_bit == -1)
1326                         zero_bit = cur;
1327                 cur++;
1328         }
1329
1330         return zero_bit;
1331 }
1332
1333 void ext4_set_bits(void *bm, int cur, int len)
1334 {
1335         __u32 *addr;
1336
1337         len = cur + len;
1338         while (cur < len) {
1339                 if ((cur & 31) == 0 && (len - cur) >= 32) {
1340                         /* fast path: set whole word at once */
1341                         addr = bm + (cur >> 3);
1342                         *addr = 0xffffffff;
1343                         cur += 32;
1344                         continue;
1345                 }
1346                 mb_set_bit(cur, bm);
1347                 cur++;
1348         }
1349 }
1350
1351 /*
1352  * _________________________________________________________________ */
1353
1354 static inline int mb_buddy_adjust_border(int* bit, void* bitmap, int side)
1355 {
1356         if (mb_test_bit(*bit + side, bitmap)) {
1357                 mb_clear_bit(*bit, bitmap);
1358                 (*bit) -= side;
1359                 return 1;
1360         }
1361         else {
1362                 (*bit) += side;
1363                 mb_set_bit(*bit, bitmap);
1364                 return -1;
1365         }
1366 }
1367
1368 static void mb_buddy_mark_free(struct ext4_buddy *e4b, int first, int last)
1369 {
1370         int max;
1371         int order = 1;
1372         void *buddy = mb_find_buddy(e4b, order, &max);
1373
1374         while (buddy) {
1375                 void *buddy2;
1376
1377                 /* Bits in range [first; last] are known to be set since
1378                  * corresponding blocks were allocated. Bits in range
1379                  * (first; last) will stay set because they form buddies on
1380                  * upper layer. We just deal with borders if they don't
1381                  * align with upper layer and then go up.
1382                  * Releasing entire group is all about clearing
1383                  * single bit of highest order buddy.
1384                  */
1385
1386                 /* Example:
1387                  * ---------------------------------
1388                  * |   1   |   1   |   1   |   1   |
1389                  * ---------------------------------
1390                  * | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |
1391                  * ---------------------------------
1392                  *   0   1   2   3   4   5   6   7
1393                  *      \_____________________/
1394                  *
1395                  * Neither [1] nor [6] is aligned to above layer.
1396                  * Left neighbour [0] is free, so mark it busy,
1397                  * decrease bb_counters and extend range to
1398                  * [0; 6]
1399                  * Right neighbour [7] is busy. It can't be coaleasced with [6], so
1400                  * mark [6] free, increase bb_counters and shrink range to
1401                  * [0; 5].
1402                  * Then shift range to [0; 2], go up and do the same.
1403                  */
1404
1405
1406                 if (first & 1)
1407                         e4b->bd_info->bb_counters[order] += mb_buddy_adjust_border(&first, buddy, -1);
1408                 if (!(last & 1))
1409                         e4b->bd_info->bb_counters[order] += mb_buddy_adjust_border(&last, buddy, 1);
1410                 if (first > last)
1411                         break;
1412                 order++;
1413
1414                 if (first == last || !(buddy2 = mb_find_buddy(e4b, order, &max))) {
1415                         mb_clear_bits(buddy, first, last - first + 1);
1416                         e4b->bd_info->bb_counters[order - 1] += last - first + 1;
1417                         break;
1418                 }
1419                 first >>= 1;
1420                 last >>= 1;
1421                 buddy = buddy2;
1422         }
1423 }
1424
1425 static void mb_free_blocks(struct inode *inode, struct ext4_buddy *e4b,
1426                            int first, int count)
1427 {
1428         int left_is_free = 0;
1429         int right_is_free = 0;
1430         int block;
1431         int last = first + count - 1;
1432         struct super_block *sb = e4b->bd_sb;
1433
1434         if (WARN_ON(count == 0))
1435                 return;
1436         BUG_ON(last >= (sb->s_blocksize << 3));
1437         assert_spin_locked(ext4_group_lock_ptr(sb, e4b->bd_group));
1438         /* Don't bother if the block group is corrupt. */
1439         if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(e4b->bd_info)))
1440                 return;
1441
1442         mb_check_buddy(e4b);
1443         mb_free_blocks_double(inode, e4b, first, count);
1444
1445         e4b->bd_info->bb_free += count;
1446         if (first < e4b->bd_info->bb_first_free)
1447                 e4b->bd_info->bb_first_free = first;
1448
1449         /* access memory sequentially: check left neighbour,
1450          * clear range and then check right neighbour
1451          */
1452         if (first != 0)
1453                 left_is_free = !mb_test_bit(first - 1, e4b->bd_bitmap);
1454         block = mb_test_and_clear_bits(e4b->bd_bitmap, first, count);
1455         if (last + 1 < EXT4_SB(sb)->s_mb_maxs[0])
1456                 right_is_free = !mb_test_bit(last + 1, e4b->bd_bitmap);
1457
1458         if (unlikely(block != -1)) {
1459                 struct ext4_sb_info *sbi = EXT4_SB(sb);
1460                 ext4_fsblk_t blocknr;
1461
1462                 blocknr = ext4_group_first_block_no(sb, e4b->bd_group);
1463                 blocknr += EXT4_C2B(EXT4_SB(sb), block);
1464                 ext4_grp_locked_error(sb, e4b->bd_group,
1465                                       inode ? inode->i_ino : 0,
1466                                       blocknr,
1467                                       "freeing already freed block "
1468                                       "(bit %u); block bitmap corrupt.",
1469                                       block);
1470                 if (!EXT4_MB_GRP_BBITMAP_CORRUPT(e4b->bd_info))
1471                         percpu_counter_sub(&sbi->s_freeclusters_counter,
1472                                            e4b->bd_info->bb_free);
1473                 /* Mark the block group as corrupt. */
1474                 set_bit(EXT4_GROUP_INFO_BBITMAP_CORRUPT_BIT,
1475                         &e4b->bd_info->bb_state);
1476                 mb_regenerate_buddy(e4b);
1477                 goto done;
1478         }
1479
1480         /* let's maintain fragments counter */
1481         if (left_is_free && right_is_free)
1482                 e4b->bd_info->bb_fragments--;
1483         else if (!left_is_free && !right_is_free)
1484                 e4b->bd_info->bb_fragments++;
1485
1486         /* buddy[0] == bd_bitmap is a special case, so handle
1487          * it right away and let mb_buddy_mark_free stay free of
1488          * zero order checks.
1489          * Check if neighbours are to be coaleasced,
1490          * adjust bitmap bb_counters and borders appropriately.
1491          */
1492         if (first & 1) {
1493                 first += !left_is_free;
1494                 e4b->bd_info->bb_counters[0] += left_is_free ? -1 : 1;
1495         }
1496         if (!(last & 1)) {
1497                 last -= !right_is_free;
1498                 e4b->bd_info->bb_counters[0] += right_is_free ? -1 : 1;
1499         }
1500
1501         if (first <= last)
1502                 mb_buddy_mark_free(e4b, first >> 1, last >> 1);
1503
1504 done:
1505         mb_set_largest_free_order(sb, e4b->bd_info);
1506         mb_check_buddy(e4b);
1507 }
1508
1509 static int mb_find_extent(struct ext4_buddy *e4b, int block,
1510                                 int needed, struct ext4_free_extent *ex)
1511 {
1512         int next = block;
1513         int max, order;
1514         void *buddy;
1515
1516         assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
1517         BUG_ON(ex == NULL);
1518
1519         buddy = mb_find_buddy(e4b, 0, &max);
1520         BUG_ON(buddy == NULL);
1521         BUG_ON(block >= max);
1522         if (mb_test_bit(block, buddy)) {
1523                 ex->fe_len = 0;
1524                 ex->fe_start = 0;
1525                 ex->fe_group = 0;
1526                 return 0;
1527         }
1528
1529         /* find actual order */
1530         order = mb_find_order_for_block(e4b, block);
1531         block = block >> order;
1532
1533         ex->fe_len = 1 << order;
1534         ex->fe_start = block << order;
1535         ex->fe_group = e4b->bd_group;
1536
1537         /* calc difference from given start */
1538         next = next - ex->fe_start;
1539         ex->fe_len -= next;
1540         ex->fe_start += next;
1541
1542         while (needed > ex->fe_len &&
1543                mb_find_buddy(e4b, order, &max)) {
1544
1545                 if (block + 1 >= max)
1546                         break;
1547
1548                 next = (block + 1) * (1 << order);
1549                 if (mb_test_bit(next, e4b->bd_bitmap))
1550                         break;
1551
1552                 order = mb_find_order_for_block(e4b, next);
1553
1554                 block = next >> order;
1555                 ex->fe_len += 1 << order;
1556         }
1557
1558         if (ex->fe_start + ex->fe_len > EXT4_CLUSTERS_PER_GROUP(e4b->bd_sb)) {
1559                 /* Should never happen! (but apparently sometimes does?!?) */
1560                 WARN_ON(1);
1561                 ext4_grp_locked_error(e4b->bd_sb, e4b->bd_group, 0, 0,
1562                         "corruption or bug in mb_find_extent "
1563                         "block=%d, order=%d needed=%d ex=%u/%d/%d@%u",
1564                         block, order, needed, ex->fe_group, ex->fe_start,
1565                         ex->fe_len, ex->fe_logical);
1566                 ex->fe_len = 0;
1567                 ex->fe_start = 0;
1568                 ex->fe_group = 0;
1569         }
1570         return ex->fe_len;
1571 }
1572
1573 static int mb_mark_used(struct ext4_buddy *e4b, struct ext4_free_extent *ex)
1574 {
1575         int ord;
1576         int mlen = 0;
1577         int max = 0;
1578         int cur;
1579         int start = ex->fe_start;
1580         int len = ex->fe_len;
1581         unsigned ret = 0;
1582         int len0 = len;
1583         void *buddy;
1584
1585         BUG_ON(start + len > (e4b->bd_sb->s_blocksize << 3));
1586         BUG_ON(e4b->bd_group != ex->fe_group);
1587         assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
1588         mb_check_buddy(e4b);
1589         mb_mark_used_double(e4b, start, len);
1590
1591         e4b->bd_info->bb_free -= len;
1592         if (e4b->bd_info->bb_first_free == start)
1593                 e4b->bd_info->bb_first_free += len;
1594
1595         /* let's maintain fragments counter */
1596         if (start != 0)
1597                 mlen = !mb_test_bit(start - 1, e4b->bd_bitmap);
1598         if (start + len < EXT4_SB(e4b->bd_sb)->s_mb_maxs[0])
1599                 max = !mb_test_bit(start + len, e4b->bd_bitmap);
1600         if (mlen && max)
1601                 e4b->bd_info->bb_fragments++;
1602         else if (!mlen && !max)
1603                 e4b->bd_info->bb_fragments--;
1604
1605         /* let's maintain buddy itself */
1606         while (len) {
1607                 ord = mb_find_order_for_block(e4b, start);
1608
1609                 if (((start >> ord) << ord) == start && len >= (1 << ord)) {
1610                         /* the whole chunk may be allocated at once! */
1611                         mlen = 1 << ord;
1612                         buddy = mb_find_buddy(e4b, ord, &max);
1613                         BUG_ON((start >> ord) >= max);
1614                         mb_set_bit(start >> ord, buddy);
1615                         e4b->bd_info->bb_counters[ord]--;
1616                         start += mlen;
1617                         len -= mlen;
1618                         BUG_ON(len < 0);
1619                         continue;
1620                 }
1621
1622                 /* store for history */
1623                 if (ret == 0)
1624                         ret = len | (ord << 16);
1625
1626                 /* we have to split large buddy */
1627                 BUG_ON(ord <= 0);
1628                 buddy = mb_find_buddy(e4b, ord, &max);
1629                 mb_set_bit(start >> ord, buddy);
1630                 e4b->bd_info->bb_counters[ord]--;
1631
1632                 ord--;
1633                 cur = (start >> ord) & ~1U;
1634                 buddy = mb_find_buddy(e4b, ord, &max);
1635                 mb_clear_bit(cur, buddy);
1636                 mb_clear_bit(cur + 1, buddy);
1637                 e4b->bd_info->bb_counters[ord]++;
1638                 e4b->bd_info->bb_counters[ord]++;
1639         }
1640         mb_set_largest_free_order(e4b->bd_sb, e4b->bd_info);
1641
1642         ext4_set_bits(e4b->bd_bitmap, ex->fe_start, len0);
1643         mb_check_buddy(e4b);
1644
1645         return ret;
1646 }
1647
1648 /*
1649  * Must be called under group lock!
1650  */
1651 static void ext4_mb_use_best_found(struct ext4_allocation_context *ac,
1652                                         struct ext4_buddy *e4b)
1653 {
1654         struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1655         int ret;
1656
1657         BUG_ON(ac->ac_b_ex.fe_group != e4b->bd_group);
1658         BUG_ON(ac->ac_status == AC_STATUS_FOUND);
1659
1660         ac->ac_b_ex.fe_len = min(ac->ac_b_ex.fe_len, ac->ac_g_ex.fe_len);
1661         ac->ac_b_ex.fe_logical = ac->ac_g_ex.fe_logical;
1662         ret = mb_mark_used(e4b, &ac->ac_b_ex);
1663
1664         /* preallocation can change ac_b_ex, thus we store actually
1665          * allocated blocks for history */
1666         ac->ac_f_ex = ac->ac_b_ex;
1667
1668         ac->ac_status = AC_STATUS_FOUND;
1669         ac->ac_tail = ret & 0xffff;
1670         ac->ac_buddy = ret >> 16;
1671
1672         /*
1673          * take the page reference. We want the page to be pinned
1674          * so that we don't get a ext4_mb_init_cache_call for this
1675          * group until we update the bitmap. That would mean we
1676          * double allocate blocks. The reference is dropped
1677          * in ext4_mb_release_context
1678          */
1679         ac->ac_bitmap_page = e4b->bd_bitmap_page;
1680         get_page(ac->ac_bitmap_page);
1681         ac->ac_buddy_page = e4b->bd_buddy_page;
1682         get_page(ac->ac_buddy_page);
1683         /* store last allocated for subsequent stream allocation */
1684         if (ac->ac_flags & EXT4_MB_STREAM_ALLOC) {
1685                 spin_lock(&sbi->s_md_lock);
1686                 sbi->s_mb_last_group = ac->ac_f_ex.fe_group;
1687                 sbi->s_mb_last_start = ac->ac_f_ex.fe_start;
1688                 spin_unlock(&sbi->s_md_lock);
1689         }
1690 }
1691
1692 /*
1693  * regular allocator, for general purposes allocation
1694  */
1695
1696 static void ext4_mb_check_limits(struct ext4_allocation_context *ac,
1697                                         struct ext4_buddy *e4b,
1698                                         int finish_group)
1699 {
1700         struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1701         struct ext4_free_extent *bex = &ac->ac_b_ex;
1702         struct ext4_free_extent *gex = &ac->ac_g_ex;
1703         struct ext4_free_extent ex;
1704         int max;
1705
1706         if (ac->ac_status == AC_STATUS_FOUND)
1707                 return;
1708         /*
1709          * We don't want to scan for a whole year
1710          */
1711         if (ac->ac_found > sbi->s_mb_max_to_scan &&
1712                         !(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
1713                 ac->ac_status = AC_STATUS_BREAK;
1714                 return;
1715         }
1716
1717         /*
1718          * Haven't found good chunk so far, let's continue
1719          */
1720         if (bex->fe_len < gex->fe_len)
1721                 return;
1722
1723         if ((finish_group || ac->ac_found > sbi->s_mb_min_to_scan)
1724                         && bex->fe_group == e4b->bd_group) {
1725                 /* recheck chunk's availability - we don't know
1726                  * when it was found (within this lock-unlock
1727                  * period or not) */
1728                 max = mb_find_extent(e4b, bex->fe_start, gex->fe_len, &ex);
1729                 if (max >= gex->fe_len) {
1730                         ext4_mb_use_best_found(ac, e4b);
1731                         return;
1732                 }
1733         }
1734 }
1735
1736 /*
1737  * The routine checks whether found extent is good enough. If it is,
1738  * then the extent gets marked used and flag is set to the context
1739  * to stop scanning. Otherwise, the extent is compared with the
1740  * previous found extent and if new one is better, then it's stored
1741  * in the context. Later, the best found extent will be used, if
1742  * mballoc can't find good enough extent.
1743  *
1744  * FIXME: real allocation policy is to be designed yet!
1745  */
1746 static void ext4_mb_measure_extent(struct ext4_allocation_context *ac,
1747                                         struct ext4_free_extent *ex,
1748                                         struct ext4_buddy *e4b)
1749 {
1750         struct ext4_free_extent *bex = &ac->ac_b_ex;
1751         struct ext4_free_extent *gex = &ac->ac_g_ex;
1752
1753         BUG_ON(ex->fe_len <= 0);
1754         BUG_ON(ex->fe_len > EXT4_CLUSTERS_PER_GROUP(ac->ac_sb));
1755         BUG_ON(ex->fe_start >= EXT4_CLUSTERS_PER_GROUP(ac->ac_sb));
1756         BUG_ON(ac->ac_status != AC_STATUS_CONTINUE);
1757
1758         ac->ac_found++;
1759
1760         /*
1761          * The special case - take what you catch first
1762          */
1763         if (unlikely(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
1764                 *bex = *ex;
1765                 ext4_mb_use_best_found(ac, e4b);
1766                 return;
1767         }
1768
1769         /*
1770          * Let's check whether the chuck is good enough
1771          */
1772         if (ex->fe_len == gex->fe_len) {
1773                 *bex = *ex;
1774                 ext4_mb_use_best_found(ac, e4b);
1775                 return;
1776         }
1777
1778         /*
1779          * If this is first found extent, just store it in the context
1780          */
1781         if (bex->fe_len == 0) {
1782                 *bex = *ex;
1783                 return;
1784         }
1785
1786         /*
1787          * If new found extent is better, store it in the context
1788          */
1789         if (bex->fe_len < gex->fe_len) {
1790                 /* if the request isn't satisfied, any found extent
1791                  * larger than previous best one is better */
1792                 if (ex->fe_len > bex->fe_len)
1793                         *bex = *ex;
1794         } else if (ex->fe_len > gex->fe_len) {
1795                 /* if the request is satisfied, then we try to find
1796                  * an extent that still satisfy the request, but is
1797                  * smaller than previous one */
1798                 if (ex->fe_len < bex->fe_len)
1799                         *bex = *ex;
1800         }
1801
1802         ext4_mb_check_limits(ac, e4b, 0);
1803 }
1804
1805 static noinline_for_stack
1806 int ext4_mb_try_best_found(struct ext4_allocation_context *ac,
1807                                         struct ext4_buddy *e4b)
1808 {
1809         struct ext4_free_extent ex = ac->ac_b_ex;
1810         ext4_group_t group = ex.fe_group;
1811         int max;
1812         int err;
1813
1814         BUG_ON(ex.fe_len <= 0);
1815         err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
1816         if (err)
1817                 return err;
1818
1819         ext4_lock_group(ac->ac_sb, group);
1820         max = mb_find_extent(e4b, ex.fe_start, ex.fe_len, &ex);
1821
1822         if (max > 0) {
1823                 ac->ac_b_ex = ex;
1824                 ext4_mb_use_best_found(ac, e4b);
1825         }
1826
1827         ext4_unlock_group(ac->ac_sb, group);
1828         ext4_mb_unload_buddy(e4b);
1829
1830         return 0;
1831 }
1832
1833 static noinline_for_stack
1834 int ext4_mb_find_by_goal(struct ext4_allocation_context *ac,
1835                                 struct ext4_buddy *e4b)
1836 {
1837         ext4_group_t group = ac->ac_g_ex.fe_group;
1838         int max;
1839         int err;
1840         struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1841         struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
1842         struct ext4_free_extent ex;
1843
1844         if (!(ac->ac_flags & EXT4_MB_HINT_TRY_GOAL))
1845                 return 0;
1846         if (grp->bb_free == 0)
1847                 return 0;
1848
1849         err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
1850         if (err)
1851                 return err;
1852
1853         if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(e4b->bd_info))) {
1854                 ext4_mb_unload_buddy(e4b);
1855                 return 0;
1856         }
1857
1858         ext4_lock_group(ac->ac_sb, group);
1859         max = mb_find_extent(e4b, ac->ac_g_ex.fe_start,
1860                              ac->ac_g_ex.fe_len, &ex);
1861         ex.fe_logical = 0xDEADFA11; /* debug value */
1862
1863         if (max >= ac->ac_g_ex.fe_len && ac->ac_g_ex.fe_len == sbi->s_stripe) {
1864                 ext4_fsblk_t start;
1865
1866                 start = ext4_group_first_block_no(ac->ac_sb, e4b->bd_group) +
1867                         ex.fe_start;
1868                 /* use do_div to get remainder (would be 64-bit modulo) */
1869                 if (do_div(start, sbi->s_stripe) == 0) {
1870                         ac->ac_found++;
1871                         ac->ac_b_ex = ex;
1872                         ext4_mb_use_best_found(ac, e4b);
1873                 }
1874         } else if (max >= ac->ac_g_ex.fe_len) {
1875                 BUG_ON(ex.fe_len <= 0);
1876                 BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
1877                 BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
1878                 ac->ac_found++;
1879                 ac->ac_b_ex = ex;
1880                 ext4_mb_use_best_found(ac, e4b);
1881         } else if (max > 0 && (ac->ac_flags & EXT4_MB_HINT_MERGE)) {
1882                 /* Sometimes, caller may want to merge even small
1883                  * number of blocks to an existing extent */
1884                 BUG_ON(ex.fe_len <= 0);
1885                 BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
1886                 BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
1887                 ac->ac_found++;
1888                 ac->ac_b_ex = ex;
1889                 ext4_mb_use_best_found(ac, e4b);
1890         }
1891         ext4_unlock_group(ac->ac_sb, group);
1892         ext4_mb_unload_buddy(e4b);
1893
1894         return 0;
1895 }
1896
1897 /*
1898  * The routine scans buddy structures (not bitmap!) from given order
1899  * to max order and tries to find big enough chunk to satisfy the req
1900  */
1901 static noinline_for_stack
1902 void ext4_mb_simple_scan_group(struct ext4_allocation_context *ac,
1903                                         struct ext4_buddy *e4b)
1904 {
1905         struct super_block *sb = ac->ac_sb;
1906         struct ext4_group_info *grp = e4b->bd_info;
1907         void *buddy;
1908         int i;
1909         int k;
1910         int max;
1911
1912         BUG_ON(ac->ac_2order <= 0);
1913         for (i = ac->ac_2order; i <= sb->s_blocksize_bits + 1; i++) {
1914                 if (grp->bb_counters[i] == 0)
1915                         continue;
1916
1917                 buddy = mb_find_buddy(e4b, i, &max);
1918                 BUG_ON(buddy == NULL);
1919
1920                 k = mb_find_next_zero_bit(buddy, max, 0);
1921                 BUG_ON(k >= max);
1922
1923                 ac->ac_found++;
1924
1925                 ac->ac_b_ex.fe_len = 1 << i;
1926                 ac->ac_b_ex.fe_start = k << i;
1927                 ac->ac_b_ex.fe_group = e4b->bd_group;
1928
1929                 ext4_mb_use_best_found(ac, e4b);
1930
1931                 BUG_ON(ac->ac_b_ex.fe_len != ac->ac_g_ex.fe_len);
1932
1933                 if (EXT4_SB(sb)->s_mb_stats)
1934                         atomic_inc(&EXT4_SB(sb)->s_bal_2orders);
1935
1936                 break;
1937         }
1938 }
1939
1940 /*
1941  * The routine scans the group and measures all found extents.
1942  * In order to optimize scanning, caller must pass number of
1943  * free blocks in the group, so the routine can know upper limit.
1944  */
1945 static noinline_for_stack
1946 void ext4_mb_complex_scan_group(struct ext4_allocation_context *ac,
1947                                         struct ext4_buddy *e4b)
1948 {
1949         struct super_block *sb = ac->ac_sb;
1950         void *bitmap = e4b->bd_bitmap;
1951         struct ext4_free_extent ex;
1952         int i;
1953         int free;
1954
1955         free = e4b->bd_info->bb_free;
1956         if (WARN_ON(free <= 0))
1957                 return;
1958
1959         i = e4b->bd_info->bb_first_free;
1960
1961         while (free && ac->ac_status == AC_STATUS_CONTINUE) {
1962                 i = mb_find_next_zero_bit(bitmap,
1963                                                 EXT4_CLUSTERS_PER_GROUP(sb), i);
1964                 if (i >= EXT4_CLUSTERS_PER_GROUP(sb)) {
1965                         /*
1966                          * IF we have corrupt bitmap, we won't find any
1967                          * free blocks even though group info says we
1968                          * we have free blocks
1969                          */
1970                         ext4_grp_locked_error(sb, e4b->bd_group, 0, 0,
1971                                         "%d free clusters as per "
1972                                         "group info. But bitmap says 0",
1973                                         free);
1974                         break;
1975                 }
1976
1977                 mb_find_extent(e4b, i, ac->ac_g_ex.fe_len, &ex);
1978                 if (WARN_ON(ex.fe_len <= 0))
1979                         break;
1980                 if (free < ex.fe_len) {
1981                         ext4_grp_locked_error(sb, e4b->bd_group, 0, 0,
1982                                         "%d free clusters as per "
1983                                         "group info. But got %d blocks",
1984                                         free, ex.fe_len);
1985                         /*
1986                          * The number of free blocks differs. This mostly
1987                          * indicate that the bitmap is corrupt. So exit
1988                          * without claiming the space.
1989                          */
1990                         break;
1991                 }
1992                 ex.fe_logical = 0xDEADC0DE; /* debug value */
1993                 ext4_mb_measure_extent(ac, &ex, e4b);
1994
1995                 i += ex.fe_len;
1996                 free -= ex.fe_len;
1997         }
1998
1999         ext4_mb_check_limits(ac, e4b, 1);
2000 }
2001
2002 /*
2003  * This is a special case for storages like raid5
2004  * we try to find stripe-aligned chunks for stripe-size-multiple requests
2005  */
2006 static noinline_for_stack
2007 void ext4_mb_scan_aligned(struct ext4_allocation_context *ac,
2008                                  struct ext4_buddy *e4b)
2009 {
2010         struct super_block *sb = ac->ac_sb;
2011         struct ext4_sb_info *sbi = EXT4_SB(sb);
2012         void *bitmap = e4b->bd_bitmap;
2013         struct ext4_free_extent ex;
2014         ext4_fsblk_t first_group_block;
2015         ext4_fsblk_t a;
2016         ext4_grpblk_t i;
2017         int max;
2018
2019         BUG_ON(sbi->s_stripe == 0);
2020
2021         /* find first stripe-aligned block in group */
2022         first_group_block = ext4_group_first_block_no(sb, e4b->bd_group);
2023
2024         a = first_group_block + sbi->s_stripe - 1;
2025         do_div(a, sbi->s_stripe);
2026         i = (a * sbi->s_stripe) - first_group_block;
2027
2028         while (i < EXT4_CLUSTERS_PER_GROUP(sb)) {
2029                 if (!mb_test_bit(i, bitmap)) {
2030                         max = mb_find_extent(e4b, i, sbi->s_stripe, &ex);
2031                         if (max >= sbi->s_stripe) {
2032                                 ac->ac_found++;
2033                                 ex.fe_logical = 0xDEADF00D; /* debug value */
2034                                 ac->ac_b_ex = ex;
2035                                 ext4_mb_use_best_found(ac, e4b);
2036                                 break;
2037                         }
2038                 }
2039                 i += sbi->s_stripe;
2040         }
2041 }
2042
2043 /*
2044  * This is now called BEFORE we load the buddy bitmap.
2045  * Returns either 1 or 0 indicating that the group is either suitable
2046  * for the allocation or not. In addition it can also return negative
2047  * error code when something goes wrong.
2048  */
2049 static int ext4_mb_good_group(struct ext4_allocation_context *ac,
2050                                 ext4_group_t group, int cr)
2051 {
2052         unsigned free, fragments;
2053         int flex_size = ext4_flex_bg_size(EXT4_SB(ac->ac_sb));
2054         struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
2055
2056         BUG_ON(cr < 0 || cr >= 4);
2057
2058         free = grp->bb_free;
2059         if (free == 0)
2060                 return 0;
2061         if (cr <= 2 && free < ac->ac_g_ex.fe_len)
2062                 return 0;
2063
2064         if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(grp)))
2065                 return 0;
2066
2067         /* We only do this if the grp has never been initialized */
2068         if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
2069                 int ret = ext4_mb_init_group(ac->ac_sb, group, GFP_NOFS);
2070                 if (ret)
2071                         return ret;
2072         }
2073
2074         fragments = grp->bb_fragments;
2075         if (fragments == 0)
2076                 return 0;
2077
2078         switch (cr) {
2079         case 0:
2080                 BUG_ON(ac->ac_2order == 0);
2081
2082                 /* Avoid using the first bg of a flexgroup for data files */
2083                 if ((ac->ac_flags & EXT4_MB_HINT_DATA) &&
2084                     (flex_size >= EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME) &&
2085                     ((group % flex_size) == 0))
2086                         return 0;
2087
2088                 if ((ac->ac_2order > ac->ac_sb->s_blocksize_bits+1) ||
2089                     (free / fragments) >= ac->ac_g_ex.fe_len)
2090                         return 1;
2091
2092                 if (grp->bb_largest_free_order < ac->ac_2order)
2093                         return 0;
2094
2095                 return 1;
2096         case 1:
2097                 if ((free / fragments) >= ac->ac_g_ex.fe_len)
2098                         return 1;
2099                 break;
2100         case 2:
2101                 if (free >= ac->ac_g_ex.fe_len)
2102                         return 1;
2103                 break;
2104         case 3:
2105                 return 1;
2106         default:
2107                 BUG();
2108         }
2109
2110         return 0;
2111 }
2112
2113 static noinline_for_stack int
2114 ext4_mb_regular_allocator(struct ext4_allocation_context *ac)
2115 {
2116         ext4_group_t ngroups, group, i;
2117         int cr;
2118         int err = 0, first_err = 0;
2119         struct ext4_sb_info *sbi;
2120         struct super_block *sb;
2121         struct ext4_buddy e4b;
2122
2123         sb = ac->ac_sb;
2124         sbi = EXT4_SB(sb);
2125         ngroups = ext4_get_groups_count(sb);
2126         /* non-extent files are limited to low blocks/groups */
2127         if (!(ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS)))
2128                 ngroups = sbi->s_blockfile_groups;
2129
2130         BUG_ON(ac->ac_status == AC_STATUS_FOUND);
2131
2132         /* first, try the goal */
2133         err = ext4_mb_find_by_goal(ac, &e4b);
2134         if (err || ac->ac_status == AC_STATUS_FOUND)
2135                 goto out;
2136
2137         if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
2138                 goto out;
2139
2140         /*
2141          * ac->ac2_order is set only if the fe_len is a power of 2
2142          * if ac2_order is set we also set criteria to 0 so that we
2143          * try exact allocation using buddy.
2144          */
2145         i = fls(ac->ac_g_ex.fe_len);
2146         ac->ac_2order = 0;
2147         /*
2148          * We search using buddy data only if the order of the request
2149          * is greater than equal to the sbi_s_mb_order2_reqs
2150          * You can tune it via /sys/fs/ext4/<partition>/mb_order2_req
2151          * We also support searching for power-of-two requests only for
2152          * requests upto maximum buddy size we have constructed.
2153          */
2154         if (i >= sbi->s_mb_order2_reqs && i <= sb->s_blocksize_bits + 2) {
2155                 /*
2156                  * This should tell if fe_len is exactly power of 2
2157                  */
2158                 if ((ac->ac_g_ex.fe_len & (~(1 << (i - 1)))) == 0)
2159                         ac->ac_2order = array_index_nospec(i - 1,
2160                                                            sb->s_blocksize_bits + 2);
2161         }
2162
2163         /* if stream allocation is enabled, use global goal */
2164         if (ac->ac_flags & EXT4_MB_STREAM_ALLOC) {
2165                 /* TBD: may be hot point */
2166                 spin_lock(&sbi->s_md_lock);
2167                 ac->ac_g_ex.fe_group = sbi->s_mb_last_group;
2168                 ac->ac_g_ex.fe_start = sbi->s_mb_last_start;
2169                 spin_unlock(&sbi->s_md_lock);
2170         }
2171
2172         /* Let's just scan groups to find more-less suitable blocks */
2173         cr = ac->ac_2order ? 0 : 1;
2174         /*
2175          * cr == 0 try to get exact allocation,
2176          * cr == 3  try to get anything
2177          */
2178 repeat:
2179         for (; cr < 4 && ac->ac_status == AC_STATUS_CONTINUE; cr++) {
2180                 ac->ac_criteria = cr;
2181                 /*
2182                  * searching for the right group start
2183                  * from the goal value specified
2184                  */
2185                 group = ac->ac_g_ex.fe_group;
2186
2187                 for (i = 0; i < ngroups; group++, i++) {
2188                         int ret = 0;
2189                         cond_resched();
2190                         /*
2191                          * Artificially restricted ngroups for non-extent
2192                          * files makes group > ngroups possible on first loop.
2193                          */
2194                         if (group >= ngroups)
2195                                 group = 0;
2196
2197                         /* This now checks without needing the buddy page */
2198                         ret = ext4_mb_good_group(ac, group, cr);
2199                         if (ret <= 0) {
2200                                 if (!first_err)
2201                                         first_err = ret;
2202                                 continue;
2203                         }
2204
2205                         err = ext4_mb_load_buddy(sb, group, &e4b);
2206                         if (err)
2207                                 goto out;
2208
2209                         ext4_lock_group(sb, group);
2210
2211                         /*
2212                          * We need to check again after locking the
2213                          * block group
2214                          */
2215                         ret = ext4_mb_good_group(ac, group, cr);
2216                         if (ret <= 0) {
2217                                 ext4_unlock_group(sb, group);
2218                                 ext4_mb_unload_buddy(&e4b);
2219                                 if (!first_err)
2220                                         first_err = ret;
2221                                 continue;
2222                         }
2223
2224                         ac->ac_groups_scanned++;
2225                         if (cr == 0)
2226                                 ext4_mb_simple_scan_group(ac, &e4b);
2227                         else if (cr == 1 && sbi->s_stripe &&
2228                                         !(ac->ac_g_ex.fe_len % sbi->s_stripe))
2229                                 ext4_mb_scan_aligned(ac, &e4b);
2230                         else
2231                                 ext4_mb_complex_scan_group(ac, &e4b);
2232
2233                         ext4_unlock_group(sb, group);
2234                         ext4_mb_unload_buddy(&e4b);
2235
2236                         if (ac->ac_status != AC_STATUS_CONTINUE)
2237                                 break;
2238                 }
2239         }
2240
2241         if (ac->ac_b_ex.fe_len > 0 && ac->ac_status != AC_STATUS_FOUND &&
2242             !(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
2243                 /*
2244                  * We've been searching too long. Let's try to allocate
2245                  * the best chunk we've found so far
2246                  */
2247
2248                 ext4_mb_try_best_found(ac, &e4b);
2249                 if (ac->ac_status != AC_STATUS_FOUND) {
2250                         /*
2251                          * Someone more lucky has already allocated it.
2252                          * The only thing we can do is just take first
2253                          * found block(s)
2254                         printk(KERN_DEBUG "EXT4-fs: someone won our chunk\n");
2255                          */
2256                         ac->ac_b_ex.fe_group = 0;
2257                         ac->ac_b_ex.fe_start = 0;
2258                         ac->ac_b_ex.fe_len = 0;
2259                         ac->ac_status = AC_STATUS_CONTINUE;
2260                         ac->ac_flags |= EXT4_MB_HINT_FIRST;
2261                         cr = 3;
2262                         atomic_inc(&sbi->s_mb_lost_chunks);
2263                         goto repeat;
2264                 }
2265         }
2266 out:
2267         if (!err && ac->ac_status != AC_STATUS_FOUND && first_err)
2268                 err = first_err;
2269         return err;
2270 }
2271
2272 static void *ext4_mb_seq_groups_start(struct seq_file *seq, loff_t *pos)
2273 {
2274         struct super_block *sb = seq->private;
2275         ext4_group_t group;
2276
2277         if (*pos < 0 || *pos >= ext4_get_groups_count(sb))
2278                 return NULL;
2279         group = *pos + 1;
2280         return (void *) ((unsigned long) group);
2281 }
2282
2283 static void *ext4_mb_seq_groups_next(struct seq_file *seq, void *v, loff_t *pos)
2284 {
2285         struct super_block *sb = seq->private;
2286         ext4_group_t group;
2287
2288         ++*pos;
2289         if (*pos < 0 || *pos >= ext4_get_groups_count(sb))
2290                 return NULL;
2291         group = *pos + 1;
2292         return (void *) ((unsigned long) group);
2293 }
2294
2295 static int ext4_mb_seq_groups_show(struct seq_file *seq, void *v)
2296 {
2297         struct super_block *sb = seq->private;
2298         ext4_group_t group = (ext4_group_t) ((unsigned long) v);
2299         int i;
2300         int err, buddy_loaded = 0;
2301         struct ext4_buddy e4b;
2302         struct ext4_group_info *grinfo;
2303         unsigned char blocksize_bits = min_t(unsigned char,
2304                                              sb->s_blocksize_bits,
2305                                              EXT4_MAX_BLOCK_LOG_SIZE);
2306         struct sg {
2307                 struct ext4_group_info info;
2308                 ext4_grpblk_t counters[EXT4_MAX_BLOCK_LOG_SIZE + 2];
2309         } sg;
2310
2311         group--;
2312         if (group == 0)
2313                 seq_puts(seq, "#group: free  frags first ["
2314                               " 2^0   2^1   2^2   2^3   2^4   2^5   2^6  "
2315                               " 2^7   2^8   2^9   2^10  2^11  2^12  2^13  ]\n");
2316
2317         i = (blocksize_bits + 2) * sizeof(sg.info.bb_counters[0]) +
2318                 sizeof(struct ext4_group_info);
2319
2320         grinfo = ext4_get_group_info(sb, group);
2321         /* Load the group info in memory only if not already loaded. */
2322         if (unlikely(EXT4_MB_GRP_NEED_INIT(grinfo))) {
2323                 err = ext4_mb_load_buddy(sb, group, &e4b);
2324                 if (err) {
2325                         seq_printf(seq, "#%-5u: I/O error\n", group);
2326                         return 0;
2327                 }
2328                 buddy_loaded = 1;
2329         }
2330
2331         memcpy(&sg, ext4_get_group_info(sb, group), i);
2332
2333         if (buddy_loaded)
2334                 ext4_mb_unload_buddy(&e4b);
2335
2336         seq_printf(seq, "#%-5u: %-5u %-5u %-5u [", group, sg.info.bb_free,
2337                         sg.info.bb_fragments, sg.info.bb_first_free);
2338         for (i = 0; i <= 13; i++)
2339                 seq_printf(seq, " %-5u", i <= blocksize_bits + 1 ?
2340                                 sg.info.bb_counters[i] : 0);
2341         seq_printf(seq, " ]\n");
2342
2343         return 0;
2344 }
2345
2346 static void ext4_mb_seq_groups_stop(struct seq_file *seq, void *v)
2347 {
2348 }
2349
2350 static const struct seq_operations ext4_mb_seq_groups_ops = {
2351         .start  = ext4_mb_seq_groups_start,
2352         .next   = ext4_mb_seq_groups_next,
2353         .stop   = ext4_mb_seq_groups_stop,
2354         .show   = ext4_mb_seq_groups_show,
2355 };
2356
2357 static int ext4_mb_seq_groups_open(struct inode *inode, struct file *file)
2358 {
2359         struct super_block *sb = PDE_DATA(inode);
2360         int rc;
2361
2362         rc = seq_open(file, &ext4_mb_seq_groups_ops);
2363         if (rc == 0) {
2364                 struct seq_file *m = file->private_data;
2365                 m->private = sb;
2366         }
2367         return rc;
2368
2369 }
2370
2371 const struct file_operations ext4_seq_mb_groups_fops = {
2372         .open           = ext4_mb_seq_groups_open,
2373         .read           = seq_read,
2374         .llseek         = seq_lseek,
2375         .release        = seq_release,
2376 };
2377
2378 static struct kmem_cache *get_groupinfo_cache(int blocksize_bits)
2379 {
2380         int cache_index = blocksize_bits - EXT4_MIN_BLOCK_LOG_SIZE;
2381         struct kmem_cache *cachep = ext4_groupinfo_caches[cache_index];
2382
2383         BUG_ON(!cachep);
2384         return cachep;
2385 }
2386
2387 /*
2388  * Allocate the top-level s_group_info array for the specified number
2389  * of groups
2390  */
2391 int ext4_mb_alloc_groupinfo(struct super_block *sb, ext4_group_t ngroups)
2392 {
2393         struct ext4_sb_info *sbi = EXT4_SB(sb);
2394         unsigned size;
2395         struct ext4_group_info ***old_groupinfo, ***new_groupinfo;
2396
2397         size = (ngroups + EXT4_DESC_PER_BLOCK(sb) - 1) >>
2398                 EXT4_DESC_PER_BLOCK_BITS(sb);
2399         if (size <= sbi->s_group_info_size)
2400                 return 0;
2401
2402         size = roundup_pow_of_two(sizeof(*sbi->s_group_info) * size);
2403         new_groupinfo = kvzalloc(size, GFP_KERNEL);
2404         if (!new_groupinfo) {
2405                 ext4_msg(sb, KERN_ERR, "can't allocate buddy meta group");
2406                 return -ENOMEM;
2407         }
2408         rcu_read_lock();
2409         old_groupinfo = rcu_dereference(sbi->s_group_info);
2410         if (old_groupinfo)
2411                 memcpy(new_groupinfo, old_groupinfo,
2412                        sbi->s_group_info_size * sizeof(*sbi->s_group_info));
2413         rcu_read_unlock();
2414         rcu_assign_pointer(sbi->s_group_info, new_groupinfo);
2415         sbi->s_group_info_size = size / sizeof(*sbi->s_group_info);
2416         if (old_groupinfo)
2417                 ext4_kvfree_array_rcu(old_groupinfo);
2418         ext4_debug("allocated s_groupinfo array for %d meta_bg's\n", 
2419                    sbi->s_group_info_size);
2420         return 0;
2421 }
2422
2423 /* Create and initialize ext4_group_info data for the given group. */
2424 int ext4_mb_add_groupinfo(struct super_block *sb, ext4_group_t group,
2425                           struct ext4_group_desc *desc)
2426 {
2427         int i;
2428         int metalen = 0;
2429         int idx = group >> EXT4_DESC_PER_BLOCK_BITS(sb);
2430         struct ext4_sb_info *sbi = EXT4_SB(sb);
2431         struct ext4_group_info **meta_group_info;
2432         struct kmem_cache *cachep = get_groupinfo_cache(sb->s_blocksize_bits);
2433
2434         /*
2435          * First check if this group is the first of a reserved block.
2436          * If it's true, we have to allocate a new table of pointers
2437          * to ext4_group_info structures
2438          */
2439         if (group % EXT4_DESC_PER_BLOCK(sb) == 0) {
2440                 metalen = sizeof(*meta_group_info) <<
2441                         EXT4_DESC_PER_BLOCK_BITS(sb);
2442                 meta_group_info = kmalloc(metalen, GFP_NOFS);
2443                 if (meta_group_info == NULL) {
2444                         ext4_msg(sb, KERN_ERR, "can't allocate mem "
2445                                  "for a buddy group");
2446                         goto exit_meta_group_info;
2447                 }
2448                 rcu_read_lock();
2449                 rcu_dereference(sbi->s_group_info)[idx] = meta_group_info;
2450                 rcu_read_unlock();
2451         }
2452
2453         meta_group_info = sbi_array_rcu_deref(sbi, s_group_info, idx);
2454         i = group & (EXT4_DESC_PER_BLOCK(sb) - 1);
2455
2456         meta_group_info[i] = kmem_cache_zalloc(cachep, GFP_NOFS);
2457         if (meta_group_info[i] == NULL) {
2458                 ext4_msg(sb, KERN_ERR, "can't allocate buddy mem");
2459                 goto exit_group_info;
2460         }
2461         set_bit(EXT4_GROUP_INFO_NEED_INIT_BIT,
2462                 &(meta_group_info[i]->bb_state));
2463
2464         /*
2465          * initialize bb_free to be able to skip
2466          * empty groups without initialization
2467          */
2468         if (ext4_has_group_desc_csum(sb) &&
2469             (desc->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))) {
2470                 meta_group_info[i]->bb_free =
2471                         ext4_free_clusters_after_init(sb, group, desc);
2472         } else {
2473                 meta_group_info[i]->bb_free =
2474                         ext4_free_group_clusters(sb, desc);
2475         }
2476
2477         INIT_LIST_HEAD(&meta_group_info[i]->bb_prealloc_list);
2478         init_rwsem(&meta_group_info[i]->alloc_sem);
2479         meta_group_info[i]->bb_free_root = RB_ROOT;
2480         meta_group_info[i]->bb_largest_free_order = -1;  /* uninit */
2481
2482 #ifdef DOUBLE_CHECK
2483         {
2484                 struct buffer_head *bh;
2485                 meta_group_info[i]->bb_bitmap =
2486                         kmalloc(sb->s_blocksize, GFP_NOFS);
2487                 BUG_ON(meta_group_info[i]->bb_bitmap == NULL);
2488                 bh = ext4_read_block_bitmap(sb, group);
2489                 BUG_ON(IS_ERR_OR_NULL(bh));
2490                 memcpy(meta_group_info[i]->bb_bitmap, bh->b_data,
2491                         sb->s_blocksize);
2492                 put_bh(bh);
2493         }
2494 #endif
2495
2496         return 0;
2497
2498 exit_group_info:
2499         /* If a meta_group_info table has been allocated, release it now */
2500         if (group % EXT4_DESC_PER_BLOCK(sb) == 0) {
2501                 struct ext4_group_info ***group_info;
2502
2503                 rcu_read_lock();
2504                 group_info = rcu_dereference(sbi->s_group_info);
2505                 kfree(group_info[idx]);
2506                 group_info[idx] = NULL;
2507                 rcu_read_unlock();
2508         }
2509 exit_meta_group_info:
2510         return -ENOMEM;
2511 } /* ext4_mb_add_groupinfo */
2512
2513 static int ext4_mb_init_backend(struct super_block *sb)
2514 {
2515         ext4_group_t ngroups = ext4_get_groups_count(sb);
2516         ext4_group_t i;
2517         struct ext4_sb_info *sbi = EXT4_SB(sb);
2518         int err;
2519         struct ext4_group_desc *desc;
2520         struct ext4_group_info ***group_info;
2521         struct kmem_cache *cachep;
2522
2523         err = ext4_mb_alloc_groupinfo(sb, ngroups);
2524         if (err)
2525                 return err;
2526
2527         sbi->s_buddy_cache = new_inode(sb);
2528         if (sbi->s_buddy_cache == NULL) {
2529                 ext4_msg(sb, KERN_ERR, "can't get new inode");
2530                 goto err_freesgi;
2531         }
2532         /* To avoid potentially colliding with an valid on-disk inode number,
2533          * use EXT4_BAD_INO for the buddy cache inode number.  This inode is
2534          * not in the inode hash, so it should never be found by iget(), but
2535          * this will avoid confusion if it ever shows up during debugging. */
2536         sbi->s_buddy_cache->i_ino = EXT4_BAD_INO;
2537         EXT4_I(sbi->s_buddy_cache)->i_disksize = 0;
2538         for (i = 0; i < ngroups; i++) {
2539                 desc = ext4_get_group_desc(sb, i, NULL);
2540                 if (desc == NULL) {
2541                         ext4_msg(sb, KERN_ERR, "can't read descriptor %u", i);
2542                         goto err_freebuddy;
2543                 }
2544                 if (ext4_mb_add_groupinfo(sb, i, desc) != 0)
2545                         goto err_freebuddy;
2546         }
2547
2548         return 0;
2549
2550 err_freebuddy:
2551         cachep = get_groupinfo_cache(sb->s_blocksize_bits);
2552         while (i-- > 0)
2553                 kmem_cache_free(cachep, ext4_get_group_info(sb, i));
2554         i = sbi->s_group_info_size;
2555         rcu_read_lock();
2556         group_info = rcu_dereference(sbi->s_group_info);
2557         while (i-- > 0)
2558                 kfree(group_info[i]);
2559         rcu_read_unlock();
2560         iput(sbi->s_buddy_cache);
2561 err_freesgi:
2562         rcu_read_lock();
2563         kvfree(rcu_dereference(sbi->s_group_info));
2564         rcu_read_unlock();
2565         return -ENOMEM;
2566 }
2567
2568 static void ext4_groupinfo_destroy_slabs(void)
2569 {
2570         int i;
2571
2572         for (i = 0; i < NR_GRPINFO_CACHES; i++) {
2573                 if (ext4_groupinfo_caches[i])
2574                         kmem_cache_destroy(ext4_groupinfo_caches[i]);
2575                 ext4_groupinfo_caches[i] = NULL;
2576         }
2577 }
2578
2579 static int ext4_groupinfo_create_slab(size_t size)
2580 {
2581         static DEFINE_MUTEX(ext4_grpinfo_slab_create_mutex);
2582         int slab_size;
2583         int blocksize_bits = order_base_2(size);
2584         int cache_index = blocksize_bits - EXT4_MIN_BLOCK_LOG_SIZE;
2585         struct kmem_cache *cachep;
2586
2587         if (cache_index >= NR_GRPINFO_CACHES)
2588                 return -EINVAL;
2589
2590         if (unlikely(cache_index < 0))
2591                 cache_index = 0;
2592
2593         mutex_lock(&ext4_grpinfo_slab_create_mutex);
2594         if (ext4_groupinfo_caches[cache_index]) {
2595                 mutex_unlock(&ext4_grpinfo_slab_create_mutex);
2596                 return 0;       /* Already created */
2597         }
2598
2599         slab_size = offsetof(struct ext4_group_info,
2600                                 bb_counters[blocksize_bits + 2]);
2601
2602         cachep = kmem_cache_create(ext4_groupinfo_slab_names[cache_index],
2603                                         slab_size, 0, SLAB_RECLAIM_ACCOUNT,
2604                                         NULL);
2605
2606         ext4_groupinfo_caches[cache_index] = cachep;
2607
2608         mutex_unlock(&ext4_grpinfo_slab_create_mutex);
2609         if (!cachep) {
2610                 printk(KERN_EMERG
2611                        "EXT4-fs: no memory for groupinfo slab cache\n");
2612                 return -ENOMEM;
2613         }
2614
2615         return 0;
2616 }
2617
2618 int ext4_mb_init(struct super_block *sb)
2619 {
2620         struct ext4_sb_info *sbi = EXT4_SB(sb);
2621         unsigned i, j;
2622         unsigned offset, offset_incr;
2623         unsigned max;
2624         int ret;
2625
2626         i = (sb->s_blocksize_bits + 2) * sizeof(*sbi->s_mb_offsets);
2627
2628         sbi->s_mb_offsets = kmalloc(i, GFP_KERNEL);
2629         if (sbi->s_mb_offsets == NULL) {
2630                 ret = -ENOMEM;
2631                 goto out;
2632         }
2633
2634         i = (sb->s_blocksize_bits + 2) * sizeof(*sbi->s_mb_maxs);
2635         sbi->s_mb_maxs = kmalloc(i, GFP_KERNEL);
2636         if (sbi->s_mb_maxs == NULL) {
2637                 ret = -ENOMEM;
2638                 goto out;
2639         }
2640
2641         ret = ext4_groupinfo_create_slab(sb->s_blocksize);
2642         if (ret < 0)
2643                 goto out;
2644
2645         /* order 0 is regular bitmap */
2646         sbi->s_mb_maxs[0] = sb->s_blocksize << 3;
2647         sbi->s_mb_offsets[0] = 0;
2648
2649         i = 1;
2650         offset = 0;
2651         offset_incr = 1 << (sb->s_blocksize_bits - 1);
2652         max = sb->s_blocksize << 2;
2653         do {
2654                 sbi->s_mb_offsets[i] = offset;
2655                 sbi->s_mb_maxs[i] = max;
2656                 offset += offset_incr;
2657                 offset_incr = offset_incr >> 1;
2658                 max = max >> 1;
2659                 i++;
2660         } while (i <= sb->s_blocksize_bits + 1);
2661
2662         spin_lock_init(&sbi->s_md_lock);
2663         spin_lock_init(&sbi->s_bal_lock);
2664         sbi->s_mb_free_pending = 0;
2665         INIT_LIST_HEAD(&sbi->s_freed_data_list);
2666
2667         sbi->s_mb_max_to_scan = MB_DEFAULT_MAX_TO_SCAN;
2668         sbi->s_mb_min_to_scan = MB_DEFAULT_MIN_TO_SCAN;
2669         sbi->s_mb_stats = MB_DEFAULT_STATS;
2670         sbi->s_mb_stream_request = MB_DEFAULT_STREAM_THRESHOLD;
2671         sbi->s_mb_order2_reqs = MB_DEFAULT_ORDER2_REQS;
2672         /*
2673          * The default group preallocation is 512, which for 4k block
2674          * sizes translates to 2 megabytes.  However for bigalloc file
2675          * systems, this is probably too big (i.e, if the cluster size
2676          * is 1 megabyte, then group preallocation size becomes half a
2677          * gigabyte!).  As a default, we will keep a two megabyte
2678          * group pralloc size for cluster sizes up to 64k, and after
2679          * that, we will force a minimum group preallocation size of
2680          * 32 clusters.  This translates to 8 megs when the cluster
2681          * size is 256k, and 32 megs when the cluster size is 1 meg,
2682          * which seems reasonable as a default.
2683          */
2684         sbi->s_mb_group_prealloc = max(MB_DEFAULT_GROUP_PREALLOC >>
2685                                        sbi->s_cluster_bits, 32);
2686         /*
2687          * If there is a s_stripe > 1, then we set the s_mb_group_prealloc
2688          * to the lowest multiple of s_stripe which is bigger than
2689          * the s_mb_group_prealloc as determined above. We want
2690          * the preallocation size to be an exact multiple of the
2691          * RAID stripe size so that preallocations don't fragment
2692          * the stripes.
2693          */
2694         if (sbi->s_stripe > 1) {
2695                 sbi->s_mb_group_prealloc = roundup(
2696                         sbi->s_mb_group_prealloc, sbi->s_stripe);
2697         }
2698
2699         sbi->s_locality_groups = alloc_percpu(struct ext4_locality_group);
2700         if (sbi->s_locality_groups == NULL) {
2701                 ret = -ENOMEM;
2702                 goto out;
2703         }
2704         for_each_possible_cpu(i) {
2705                 struct ext4_locality_group *lg;
2706                 lg = per_cpu_ptr(sbi->s_locality_groups, i);
2707                 mutex_init(&lg->lg_mutex);
2708                 for (j = 0; j < PREALLOC_TB_SIZE; j++)
2709                         INIT_LIST_HEAD(&lg->lg_prealloc_list[j]);
2710                 spin_lock_init(&lg->lg_prealloc_lock);
2711         }
2712
2713         /* init file for buddy data */
2714         ret = ext4_mb_init_backend(sb);
2715         if (ret != 0)
2716                 goto out_free_locality_groups;
2717
2718         return 0;
2719
2720 out_free_locality_groups:
2721         free_percpu(sbi->s_locality_groups);
2722         sbi->s_locality_groups = NULL;
2723 out:
2724         kfree(sbi->s_mb_offsets);
2725         sbi->s_mb_offsets = NULL;
2726         kfree(sbi->s_mb_maxs);
2727         sbi->s_mb_maxs = NULL;
2728         return ret;
2729 }
2730
2731 /* need to called with the ext4 group lock held */
2732 static void ext4_mb_cleanup_pa(struct ext4_group_info *grp)
2733 {
2734         struct ext4_prealloc_space *pa;
2735         struct list_head *cur, *tmp;
2736         int count = 0;
2737
2738         list_for_each_safe(cur, tmp, &grp->bb_prealloc_list) {
2739                 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
2740                 list_del(&pa->pa_group_list);
2741                 count++;
2742                 kmem_cache_free(ext4_pspace_cachep, pa);
2743         }
2744         if (count)
2745                 mb_debug(1, "mballoc: %u PAs left\n", count);
2746
2747 }
2748
2749 int ext4_mb_release(struct super_block *sb)
2750 {
2751         ext4_group_t ngroups = ext4_get_groups_count(sb);
2752         ext4_group_t i;
2753         int num_meta_group_infos;
2754         struct ext4_group_info *grinfo, ***group_info;
2755         struct ext4_sb_info *sbi = EXT4_SB(sb);
2756         struct kmem_cache *cachep = get_groupinfo_cache(sb->s_blocksize_bits);
2757
2758         if (sbi->s_group_info) {
2759                 for (i = 0; i < ngroups; i++) {
2760                         grinfo = ext4_get_group_info(sb, i);
2761 #ifdef DOUBLE_CHECK
2762                         kfree(grinfo->bb_bitmap);
2763 #endif
2764                         ext4_lock_group(sb, i);
2765                         ext4_mb_cleanup_pa(grinfo);
2766                         ext4_unlock_group(sb, i);
2767                         kmem_cache_free(cachep, grinfo);
2768                 }
2769                 num_meta_group_infos = (ngroups +
2770                                 EXT4_DESC_PER_BLOCK(sb) - 1) >>
2771                         EXT4_DESC_PER_BLOCK_BITS(sb);
2772                 rcu_read_lock();
2773                 group_info = rcu_dereference(sbi->s_group_info);
2774                 for (i = 0; i < num_meta_group_infos; i++)
2775                         kfree(group_info[i]);
2776                 kvfree(group_info);
2777                 rcu_read_unlock();
2778         }
2779         kfree(sbi->s_mb_offsets);
2780         kfree(sbi->s_mb_maxs);
2781         iput(sbi->s_buddy_cache);
2782         if (sbi->s_mb_stats) {
2783                 ext4_msg(sb, KERN_INFO,
2784                        "mballoc: %u blocks %u reqs (%u success)",
2785                                 atomic_read(&sbi->s_bal_allocated),
2786                                 atomic_read(&sbi->s_bal_reqs),
2787                                 atomic_read(&sbi->s_bal_success));
2788                 ext4_msg(sb, KERN_INFO,
2789                       "mballoc: %u extents scanned, %u goal hits, "
2790                                 "%u 2^N hits, %u breaks, %u lost",
2791                                 atomic_read(&sbi->s_bal_ex_scanned),
2792                                 atomic_read(&sbi->s_bal_goals),
2793                                 atomic_read(&sbi->s_bal_2orders),
2794                                 atomic_read(&sbi->s_bal_breaks),
2795                                 atomic_read(&sbi->s_mb_lost_chunks));
2796                 ext4_msg(sb, KERN_INFO,
2797                        "mballoc: %lu generated and it took %Lu",
2798                                 sbi->s_mb_buddies_generated,
2799                                 sbi->s_mb_generation_time);
2800                 ext4_msg(sb, KERN_INFO,
2801                        "mballoc: %u preallocated, %u discarded",
2802                                 atomic_read(&sbi->s_mb_preallocated),
2803                                 atomic_read(&sbi->s_mb_discarded));
2804         }
2805
2806         free_percpu(sbi->s_locality_groups);
2807
2808         return 0;
2809 }
2810
2811 static inline int ext4_issue_discard(struct super_block *sb,
2812                 ext4_group_t block_group, ext4_grpblk_t cluster, int count,
2813                 struct bio **biop)
2814 {
2815         ext4_fsblk_t discard_block;
2816
2817         discard_block = (EXT4_C2B(EXT4_SB(sb), cluster) +
2818                          ext4_group_first_block_no(sb, block_group));
2819         count = EXT4_C2B(EXT4_SB(sb), count);
2820         trace_ext4_discard_blocks(sb,
2821                         (unsigned long long) discard_block, count);
2822         if (biop) {
2823                 return __blkdev_issue_discard(sb->s_bdev,
2824                         (sector_t)discard_block << (sb->s_blocksize_bits - 9),
2825                         (sector_t)count << (sb->s_blocksize_bits - 9),
2826                         GFP_NOFS, 0, biop);
2827         } else
2828                 return sb_issue_discard(sb, discard_block, count, GFP_NOFS, 0);
2829 }
2830
2831 static void ext4_free_data_in_buddy(struct super_block *sb,
2832                                     struct ext4_free_data *entry)
2833 {
2834         struct ext4_buddy e4b;
2835         struct ext4_group_info *db;
2836         int err, count = 0, count2 = 0;
2837
2838         mb_debug(1, "gonna free %u blocks in group %u (0x%p):",
2839                  entry->efd_count, entry->efd_group, entry);
2840
2841         err = ext4_mb_load_buddy(sb, entry->efd_group, &e4b);
2842         /* we expect to find existing buddy because it's pinned */
2843         BUG_ON(err != 0);
2844
2845         spin_lock(&EXT4_SB(sb)->s_md_lock);
2846         EXT4_SB(sb)->s_mb_free_pending -= entry->efd_count;
2847         spin_unlock(&EXT4_SB(sb)->s_md_lock);
2848
2849         db = e4b.bd_info;
2850         /* there are blocks to put in buddy to make them really free */
2851         count += entry->efd_count;
2852         count2++;
2853         ext4_lock_group(sb, entry->efd_group);
2854         /* Take it out of per group rb tree */
2855         rb_erase(&entry->efd_node, &(db->bb_free_root));
2856         mb_free_blocks(NULL, &e4b, entry->efd_start_cluster, entry->efd_count);
2857
2858         /*
2859          * Clear the trimmed flag for the group so that the next
2860          * ext4_trim_fs can trim it.
2861          * If the volume is mounted with -o discard, online discard
2862          * is supported and the free blocks will be trimmed online.
2863          */
2864         if (!test_opt(sb, DISCARD))
2865                 EXT4_MB_GRP_CLEAR_TRIMMED(db);
2866
2867         if (!db->bb_free_root.rb_node) {
2868                 /* No more items in the per group rb tree
2869                  * balance refcounts from ext4_mb_free_metadata()
2870                  */
2871                 put_page(e4b.bd_buddy_page);
2872                 put_page(e4b.bd_bitmap_page);
2873         }
2874         ext4_unlock_group(sb, entry->efd_group);
2875         kmem_cache_free(ext4_free_data_cachep, entry);
2876         ext4_mb_unload_buddy(&e4b);
2877
2878         mb_debug(1, "freed %u blocks in %u structures\n", count, count2);
2879 }
2880
2881 /*
2882  * This function is called by the jbd2 layer once the commit has finished,
2883  * so we know we can free the blocks that were released with that commit.
2884  */
2885 void ext4_process_freed_data(struct super_block *sb, tid_t commit_tid)
2886 {
2887         struct ext4_sb_info *sbi = EXT4_SB(sb);
2888         struct ext4_free_data *entry, *tmp;
2889         struct bio *discard_bio = NULL;
2890         struct list_head freed_data_list;
2891         struct list_head *cut_pos = NULL;
2892         int err;
2893
2894         INIT_LIST_HEAD(&freed_data_list);
2895
2896         spin_lock(&sbi->s_md_lock);
2897         list_for_each_entry(entry, &sbi->s_freed_data_list, efd_list) {
2898                 if (entry->efd_tid != commit_tid)
2899                         break;
2900                 cut_pos = &entry->efd_list;
2901         }
2902         if (cut_pos)
2903                 list_cut_position(&freed_data_list, &sbi->s_freed_data_list,
2904                                   cut_pos);
2905         spin_unlock(&sbi->s_md_lock);
2906
2907         if (test_opt(sb, DISCARD)) {
2908                 list_for_each_entry(entry, &freed_data_list, efd_list) {
2909                         err = ext4_issue_discard(sb, entry->efd_group,
2910                                                  entry->efd_start_cluster,
2911                                                  entry->efd_count,
2912                                                  &discard_bio);
2913                         if (err && err != -EOPNOTSUPP) {
2914                                 ext4_msg(sb, KERN_WARNING, "discard request in"
2915                                          " group:%d block:%d count:%d failed"
2916                                          " with %d", entry->efd_group,
2917                                          entry->efd_start_cluster,
2918                                          entry->efd_count, err);
2919                         } else if (err == -EOPNOTSUPP)
2920                                 break;
2921                 }
2922
2923                 if (discard_bio) {
2924                         submit_bio_wait(discard_bio);
2925                         bio_put(discard_bio);
2926                 }
2927         }
2928
2929         list_for_each_entry_safe(entry, tmp, &freed_data_list, efd_list)
2930                 ext4_free_data_in_buddy(sb, entry);
2931 }
2932
2933 int __init ext4_init_mballoc(void)
2934 {
2935         ext4_pspace_cachep = KMEM_CACHE(ext4_prealloc_space,
2936                                         SLAB_RECLAIM_ACCOUNT);
2937         if (ext4_pspace_cachep == NULL)
2938                 return -ENOMEM;
2939
2940         ext4_ac_cachep = KMEM_CACHE(ext4_allocation_context,
2941                                     SLAB_RECLAIM_ACCOUNT);
2942         if (ext4_ac_cachep == NULL) {
2943                 kmem_cache_destroy(ext4_pspace_cachep);
2944                 return -ENOMEM;
2945         }
2946
2947         ext4_free_data_cachep = KMEM_CACHE(ext4_free_data,
2948                                            SLAB_RECLAIM_ACCOUNT);
2949         if (ext4_free_data_cachep == NULL) {
2950                 kmem_cache_destroy(ext4_pspace_cachep);
2951                 kmem_cache_destroy(ext4_ac_cachep);
2952                 return -ENOMEM;
2953         }
2954         return 0;
2955 }
2956
2957 void ext4_exit_mballoc(void)
2958 {
2959         /*
2960          * Wait for completion of call_rcu()'s on ext4_pspace_cachep
2961          * before destroying the slab cache.
2962          */
2963         rcu_barrier();
2964         kmem_cache_destroy(ext4_pspace_cachep);
2965         kmem_cache_destroy(ext4_ac_cachep);
2966         kmem_cache_destroy(ext4_free_data_cachep);
2967         ext4_groupinfo_destroy_slabs();
2968 }
2969
2970
2971 /*
2972  * Check quota and mark chosen space (ac->ac_b_ex) non-free in bitmaps
2973  * Returns 0 if success or error code
2974  */
2975 static noinline_for_stack int
2976 ext4_mb_mark_diskspace_used(struct ext4_allocation_context *ac,
2977                                 handle_t *handle, unsigned int reserv_clstrs)
2978 {
2979         struct buffer_head *bitmap_bh = NULL;
2980         struct ext4_group_desc *gdp;
2981         struct buffer_head *gdp_bh;
2982         struct ext4_sb_info *sbi;
2983         struct super_block *sb;
2984         ext4_fsblk_t block;
2985         int err, len;
2986
2987         BUG_ON(ac->ac_status != AC_STATUS_FOUND);
2988         BUG_ON(ac->ac_b_ex.fe_len <= 0);
2989
2990         sb = ac->ac_sb;
2991         sbi = EXT4_SB(sb);
2992
2993         bitmap_bh = ext4_read_block_bitmap(sb, ac->ac_b_ex.fe_group);
2994         if (IS_ERR(bitmap_bh)) {
2995                 err = PTR_ERR(bitmap_bh);
2996                 bitmap_bh = NULL;
2997                 goto out_err;
2998         }
2999
3000         BUFFER_TRACE(bitmap_bh, "getting write access");
3001         err = ext4_journal_get_write_access(handle, bitmap_bh);
3002         if (err)
3003                 goto out_err;
3004
3005         err = -EIO;
3006         gdp = ext4_get_group_desc(sb, ac->ac_b_ex.fe_group, &gdp_bh);
3007         if (!gdp)
3008                 goto out_err;
3009
3010         ext4_debug("using block group %u(%d)\n", ac->ac_b_ex.fe_group,
3011                         ext4_free_group_clusters(sb, gdp));
3012
3013         BUFFER_TRACE(gdp_bh, "get_write_access");
3014         err = ext4_journal_get_write_access(handle, gdp_bh);
3015         if (err)
3016                 goto out_err;
3017
3018         block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
3019
3020         len = EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
3021         if (!ext4_inode_block_valid(ac->ac_inode, block, len)) {
3022                 ext4_error(sb, "Allocating blocks %llu-%llu which overlap "
3023                            "fs metadata", block, block+len);
3024                 /* File system mounted not to panic on error
3025                  * Fix the bitmap and return EFSCORRUPTED
3026                  * We leak some of the blocks here.
3027                  */
3028                 ext4_lock_group(sb, ac->ac_b_ex.fe_group);
3029                 ext4_set_bits(bitmap_bh->b_data, ac->ac_b_ex.fe_start,
3030                               ac->ac_b_ex.fe_len);
3031                 ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3032                 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
3033                 if (!err)
3034                         err = -EFSCORRUPTED;
3035                 goto out_err;
3036         }
3037
3038         ext4_lock_group(sb, ac->ac_b_ex.fe_group);
3039 #ifdef AGGRESSIVE_CHECK
3040         {
3041                 int i;
3042                 for (i = 0; i < ac->ac_b_ex.fe_len; i++) {
3043                         BUG_ON(mb_test_bit(ac->ac_b_ex.fe_start + i,
3044                                                 bitmap_bh->b_data));
3045                 }
3046         }
3047 #endif
3048         ext4_set_bits(bitmap_bh->b_data, ac->ac_b_ex.fe_start,
3049                       ac->ac_b_ex.fe_len);
3050         if (ext4_has_group_desc_csum(sb) &&
3051             (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))) {
3052                 gdp->bg_flags &= cpu_to_le16(~EXT4_BG_BLOCK_UNINIT);
3053                 ext4_free_group_clusters_set(sb, gdp,
3054                                              ext4_free_clusters_after_init(sb,
3055                                                 ac->ac_b_ex.fe_group, gdp));
3056         }
3057         len = ext4_free_group_clusters(sb, gdp) - ac->ac_b_ex.fe_len;
3058         ext4_free_group_clusters_set(sb, gdp, len);
3059         ext4_block_bitmap_csum_set(sb, ac->ac_b_ex.fe_group, gdp, bitmap_bh);
3060         ext4_group_desc_csum_set(sb, ac->ac_b_ex.fe_group, gdp);
3061
3062         ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3063         percpu_counter_sub(&sbi->s_freeclusters_counter, ac->ac_b_ex.fe_len);
3064         /*
3065          * Now reduce the dirty block count also. Should not go negative
3066          */
3067         if (!(ac->ac_flags & EXT4_MB_DELALLOC_RESERVED))
3068                 /* release all the reserved blocks if non delalloc */
3069                 percpu_counter_sub(&sbi->s_dirtyclusters_counter,
3070                                    reserv_clstrs);
3071
3072         if (sbi->s_log_groups_per_flex) {
3073                 ext4_group_t flex_group = ext4_flex_group(sbi,
3074                                                           ac->ac_b_ex.fe_group);
3075                 atomic64_sub(ac->ac_b_ex.fe_len,
3076                              &sbi_array_rcu_deref(sbi, s_flex_groups,
3077                                                   flex_group)->free_clusters);
3078         }
3079
3080         err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
3081         if (err)
3082                 goto out_err;
3083         err = ext4_handle_dirty_metadata(handle, NULL, gdp_bh);
3084
3085 out_err:
3086         brelse(bitmap_bh);
3087         return err;
3088 }
3089
3090 /*
3091  * here we normalize request for locality group
3092  * Group request are normalized to s_mb_group_prealloc, which goes to
3093  * s_strip if we set the same via mount option.
3094  * s_mb_group_prealloc can be configured via
3095  * /sys/fs/ext4/<partition>/mb_group_prealloc
3096  *
3097  * XXX: should we try to preallocate more than the group has now?
3098  */
3099 static void ext4_mb_normalize_group_request(struct ext4_allocation_context *ac)
3100 {
3101         struct super_block *sb = ac->ac_sb;
3102         struct ext4_locality_group *lg = ac->ac_lg;
3103
3104         BUG_ON(lg == NULL);
3105         ac->ac_g_ex.fe_len = EXT4_SB(sb)->s_mb_group_prealloc;
3106         mb_debug(1, "#%u: goal %u blocks for locality group\n",
3107                 current->pid, ac->ac_g_ex.fe_len);
3108 }
3109
3110 /*
3111  * Normalization means making request better in terms of
3112  * size and alignment
3113  */
3114 static noinline_for_stack void
3115 ext4_mb_normalize_request(struct ext4_allocation_context *ac,
3116                                 struct ext4_allocation_request *ar)
3117 {
3118         struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3119         int bsbits, max;
3120         ext4_lblk_t end;
3121         loff_t size, start_off;
3122         loff_t orig_size __maybe_unused;
3123         ext4_lblk_t start;
3124         struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
3125         struct ext4_prealloc_space *pa;
3126
3127         /* do normalize only data requests, metadata requests
3128            do not need preallocation */
3129         if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
3130                 return;
3131
3132         /* sometime caller may want exact blocks */
3133         if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
3134                 return;
3135
3136         /* caller may indicate that preallocation isn't
3137          * required (it's a tail, for example) */
3138         if (ac->ac_flags & EXT4_MB_HINT_NOPREALLOC)
3139                 return;
3140
3141         if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC) {
3142                 ext4_mb_normalize_group_request(ac);
3143                 return ;
3144         }
3145
3146         bsbits = ac->ac_sb->s_blocksize_bits;
3147
3148         /* first, let's learn actual file size
3149          * given current request is allocated */
3150         size = ac->ac_o_ex.fe_logical + EXT4_C2B(sbi, ac->ac_o_ex.fe_len);
3151         size = size << bsbits;
3152         if (size < i_size_read(ac->ac_inode))
3153                 size = i_size_read(ac->ac_inode);
3154         orig_size = size;
3155
3156         /* max size of free chunks */
3157         max = 2 << bsbits;
3158
3159 #define NRL_CHECK_SIZE(req, size, max, chunk_size)      \
3160                 (req <= (size) || max <= (chunk_size))
3161
3162         /* first, try to predict filesize */
3163         /* XXX: should this table be tunable? */
3164         start_off = 0;
3165         if (size <= 16 * 1024) {
3166                 size = 16 * 1024;
3167         } else if (size <= 32 * 1024) {
3168                 size = 32 * 1024;
3169         } else if (size <= 64 * 1024) {
3170                 size = 64 * 1024;
3171         } else if (size <= 128 * 1024) {
3172                 size = 128 * 1024;
3173         } else if (size <= 256 * 1024) {
3174                 size = 256 * 1024;
3175         } else if (size <= 512 * 1024) {
3176                 size = 512 * 1024;
3177         } else if (size <= 1024 * 1024) {
3178                 size = 1024 * 1024;
3179         } else if (NRL_CHECK_SIZE(size, 4 * 1024 * 1024, max, 2 * 1024)) {
3180                 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
3181                                                 (21 - bsbits)) << 21;
3182                 size = 2 * 1024 * 1024;
3183         } else if (NRL_CHECK_SIZE(size, 8 * 1024 * 1024, max, 4 * 1024)) {
3184                 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
3185                                                         (22 - bsbits)) << 22;
3186                 size = 4 * 1024 * 1024;
3187         } else if (NRL_CHECK_SIZE(ac->ac_o_ex.fe_len,
3188                                         (8<<20)>>bsbits, max, 8 * 1024)) {
3189                 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
3190                                                         (23 - bsbits)) << 23;
3191                 size = 8 * 1024 * 1024;
3192         } else {
3193                 start_off = (loff_t) ac->ac_o_ex.fe_logical << bsbits;
3194                 size      = (loff_t) EXT4_C2B(EXT4_SB(ac->ac_sb),
3195                                               ac->ac_o_ex.fe_len) << bsbits;
3196         }
3197         size = size >> bsbits;
3198         start = start_off >> bsbits;
3199
3200         /*
3201          * For tiny groups (smaller than 8MB) the chosen allocation
3202          * alignment may be larger than group size. Make sure the
3203          * alignment does not move allocation to a different group which
3204          * makes mballoc fail assertions later.
3205          */
3206         start = max(start, rounddown(ac->ac_o_ex.fe_logical,
3207                         (ext4_lblk_t)EXT4_BLOCKS_PER_GROUP(ac->ac_sb)));
3208
3209         /* don't cover already allocated blocks in selected range */
3210         if (ar->pleft && start <= ar->lleft) {
3211                 size -= ar->lleft + 1 - start;
3212                 start = ar->lleft + 1;
3213         }
3214         if (ar->pright && start + size - 1 >= ar->lright)
3215                 size -= start + size - ar->lright;
3216
3217         /*
3218          * Trim allocation request for filesystems with artificially small
3219          * groups.
3220          */
3221         if (size > EXT4_BLOCKS_PER_GROUP(ac->ac_sb))
3222                 size = EXT4_BLOCKS_PER_GROUP(ac->ac_sb);
3223
3224         end = start + size;
3225
3226         /* check we don't cross already preallocated blocks */
3227         rcu_read_lock();
3228         list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3229                 ext4_lblk_t pa_end;
3230
3231                 if (pa->pa_deleted)
3232                         continue;
3233                 spin_lock(&pa->pa_lock);
3234                 if (pa->pa_deleted) {
3235                         spin_unlock(&pa->pa_lock);
3236                         continue;
3237                 }
3238
3239                 pa_end = pa->pa_lstart + EXT4_C2B(EXT4_SB(ac->ac_sb),
3240                                                   pa->pa_len);
3241
3242                 /* PA must not overlap original request */
3243                 BUG_ON(!(ac->ac_o_ex.fe_logical >= pa_end ||
3244                         ac->ac_o_ex.fe_logical < pa->pa_lstart));
3245
3246                 /* skip PAs this normalized request doesn't overlap with */
3247                 if (pa->pa_lstart >= end || pa_end <= start) {
3248                         spin_unlock(&pa->pa_lock);
3249                         continue;
3250                 }
3251                 BUG_ON(pa->pa_lstart <= start && pa_end >= end);
3252
3253                 /* adjust start or end to be adjacent to this pa */
3254                 if (pa_end <= ac->ac_o_ex.fe_logical) {
3255                         BUG_ON(pa_end < start);
3256                         start = pa_end;
3257                 } else if (pa->pa_lstart > ac->ac_o_ex.fe_logical) {
3258                         BUG_ON(pa->pa_lstart > end);
3259                         end = pa->pa_lstart;
3260                 }
3261                 spin_unlock(&pa->pa_lock);
3262         }
3263         rcu_read_unlock();
3264         size = end - start;
3265
3266         /* XXX: extra loop to check we really don't overlap preallocations */
3267         rcu_read_lock();
3268         list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3269                 ext4_lblk_t pa_end;
3270
3271                 spin_lock(&pa->pa_lock);
3272                 if (pa->pa_deleted == 0) {
3273                         pa_end = pa->pa_lstart + EXT4_C2B(EXT4_SB(ac->ac_sb),
3274                                                           pa->pa_len);
3275                         BUG_ON(!(start >= pa_end || end <= pa->pa_lstart));
3276                 }
3277                 spin_unlock(&pa->pa_lock);
3278         }
3279         rcu_read_unlock();
3280
3281         if (start + size <= ac->ac_o_ex.fe_logical &&
3282                         start > ac->ac_o_ex.fe_logical) {
3283                 ext4_msg(ac->ac_sb, KERN_ERR,
3284                          "start %lu, size %lu, fe_logical %lu",
3285                          (unsigned long) start, (unsigned long) size,
3286                          (unsigned long) ac->ac_o_ex.fe_logical);
3287                 BUG();
3288         }
3289         BUG_ON(size <= 0 || size > EXT4_BLOCKS_PER_GROUP(ac->ac_sb));
3290
3291         /* now prepare goal request */
3292
3293         /* XXX: is it better to align blocks WRT to logical
3294          * placement or satisfy big request as is */
3295         ac->ac_g_ex.fe_logical = start;
3296         ac->ac_g_ex.fe_len = EXT4_NUM_B2C(sbi, size);
3297
3298         /* define goal start in order to merge */
3299         if (ar->pright && (ar->lright == (start + size))) {
3300                 /* merge to the right */
3301                 ext4_get_group_no_and_offset(ac->ac_sb, ar->pright - size,
3302                                                 &ac->ac_f_ex.fe_group,
3303                                                 &ac->ac_f_ex.fe_start);
3304                 ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
3305         }
3306         if (ar->pleft && (ar->lleft + 1 == start)) {
3307                 /* merge to the left */
3308                 ext4_get_group_no_and_offset(ac->ac_sb, ar->pleft + 1,
3309                                                 &ac->ac_f_ex.fe_group,
3310                                                 &ac->ac_f_ex.fe_start);
3311                 ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
3312         }
3313
3314         mb_debug(1, "goal: %u(was %u) blocks at %u\n", (unsigned) size,
3315                 (unsigned) orig_size, (unsigned) start);
3316 }
3317
3318 static void ext4_mb_collect_stats(struct ext4_allocation_context *ac)
3319 {
3320         struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3321
3322         if (sbi->s_mb_stats && ac->ac_g_ex.fe_len > 1) {
3323                 atomic_inc(&sbi->s_bal_reqs);
3324                 atomic_add(ac->ac_b_ex.fe_len, &sbi->s_bal_allocated);
3325                 if (ac->ac_b_ex.fe_len >= ac->ac_o_ex.fe_len)
3326                         atomic_inc(&sbi->s_bal_success);
3327                 atomic_add(ac->ac_found, &sbi->s_bal_ex_scanned);
3328                 if (ac->ac_g_ex.fe_start == ac->ac_b_ex.fe_start &&
3329                                 ac->ac_g_ex.fe_group == ac->ac_b_ex.fe_group)
3330                         atomic_inc(&sbi->s_bal_goals);
3331                 if (ac->ac_found > sbi->s_mb_max_to_scan)
3332                         atomic_inc(&sbi->s_bal_breaks);
3333         }
3334
3335         if (ac->ac_op == EXT4_MB_HISTORY_ALLOC)
3336                 trace_ext4_mballoc_alloc(ac);
3337         else
3338                 trace_ext4_mballoc_prealloc(ac);
3339 }
3340
3341 /*
3342  * Called on failure; free up any blocks from the inode PA for this
3343  * context.  We don't need this for MB_GROUP_PA because we only change
3344  * pa_free in ext4_mb_release_context(), but on failure, we've already
3345  * zeroed out ac->ac_b_ex.fe_len, so group_pa->pa_free is not changed.
3346  */
3347 static void ext4_discard_allocated_blocks(struct ext4_allocation_context *ac)
3348 {
3349         struct ext4_prealloc_space *pa = ac->ac_pa;
3350         struct ext4_buddy e4b;
3351         int err;
3352
3353         if (pa == NULL) {
3354                 if (ac->ac_f_ex.fe_len == 0)
3355                         return;
3356                 err = ext4_mb_load_buddy(ac->ac_sb, ac->ac_f_ex.fe_group, &e4b);
3357                 if (err) {
3358                         /*
3359                          * This should never happen since we pin the
3360                          * pages in the ext4_allocation_context so
3361                          * ext4_mb_load_buddy() should never fail.
3362                          */
3363                         WARN(1, "mb_load_buddy failed (%d)", err);
3364                         return;
3365                 }
3366                 ext4_lock_group(ac->ac_sb, ac->ac_f_ex.fe_group);
3367                 mb_free_blocks(ac->ac_inode, &e4b, ac->ac_f_ex.fe_start,
3368                                ac->ac_f_ex.fe_len);
3369                 ext4_unlock_group(ac->ac_sb, ac->ac_f_ex.fe_group);
3370                 ext4_mb_unload_buddy(&e4b);
3371                 return;
3372         }
3373         if (pa->pa_type == MB_INODE_PA)
3374                 pa->pa_free += ac->ac_b_ex.fe_len;
3375 }
3376
3377 /*
3378  * use blocks preallocated to inode
3379  */
3380 static void ext4_mb_use_inode_pa(struct ext4_allocation_context *ac,
3381                                 struct ext4_prealloc_space *pa)
3382 {
3383         struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3384         ext4_fsblk_t start;
3385         ext4_fsblk_t end;
3386         int len;
3387
3388         /* found preallocated blocks, use them */
3389         start = pa->pa_pstart + (ac->ac_o_ex.fe_logical - pa->pa_lstart);
3390         end = min(pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len),
3391                   start + EXT4_C2B(sbi, ac->ac_o_ex.fe_len));
3392         len = EXT4_NUM_B2C(sbi, end - start);
3393         ext4_get_group_no_and_offset(ac->ac_sb, start, &ac->ac_b_ex.fe_group,
3394                                         &ac->ac_b_ex.fe_start);
3395         ac->ac_b_ex.fe_len = len;
3396         ac->ac_status = AC_STATUS_FOUND;
3397         ac->ac_pa = pa;
3398
3399         BUG_ON(start < pa->pa_pstart);
3400         BUG_ON(end > pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len));
3401         BUG_ON(pa->pa_free < len);
3402         pa->pa_free -= len;
3403
3404         mb_debug(1, "use %llu/%u from inode pa %p\n", start, len, pa);
3405 }
3406
3407 /*
3408  * use blocks preallocated to locality group
3409  */
3410 static void ext4_mb_use_group_pa(struct ext4_allocation_context *ac,
3411                                 struct ext4_prealloc_space *pa)
3412 {
3413         unsigned int len = ac->ac_o_ex.fe_len;
3414
3415         ext4_get_group_no_and_offset(ac->ac_sb, pa->pa_pstart,
3416                                         &ac->ac_b_ex.fe_group,
3417                                         &ac->ac_b_ex.fe_start);
3418         ac->ac_b_ex.fe_len = len;
3419         ac->ac_status = AC_STATUS_FOUND;
3420         ac->ac_pa = pa;
3421
3422         /* we don't correct pa_pstart or pa_plen here to avoid
3423          * possible race when the group is being loaded concurrently
3424          * instead we correct pa later, after blocks are marked
3425          * in on-disk bitmap -- see ext4_mb_release_context()
3426          * Other CPUs are prevented from allocating from this pa by lg_mutex
3427          */
3428         mb_debug(1, "use %u/%u from group pa %p\n", pa->pa_lstart-len, len, pa);
3429 }
3430
3431 /*
3432  * Return the prealloc space that have minimal distance
3433  * from the goal block. @cpa is the prealloc
3434  * space that is having currently known minimal distance
3435  * from the goal block.
3436  */
3437 static struct ext4_prealloc_space *
3438 ext4_mb_check_group_pa(ext4_fsblk_t goal_block,
3439                         struct ext4_prealloc_space *pa,
3440                         struct ext4_prealloc_space *cpa)
3441 {
3442         ext4_fsblk_t cur_distance, new_distance;
3443
3444         if (cpa == NULL) {
3445                 atomic_inc(&pa->pa_count);
3446                 return pa;
3447         }
3448         cur_distance = abs(goal_block - cpa->pa_pstart);
3449         new_distance = abs(goal_block - pa->pa_pstart);
3450
3451         if (cur_distance <= new_distance)
3452                 return cpa;
3453
3454         /* drop the previous reference */
3455         atomic_dec(&cpa->pa_count);
3456         atomic_inc(&pa->pa_count);
3457         return pa;
3458 }
3459
3460 /*
3461  * search goal blocks in preallocated space
3462  */
3463 static noinline_for_stack int
3464 ext4_mb_use_preallocated(struct ext4_allocation_context *ac)
3465 {
3466         struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3467         int order, i;
3468         struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
3469         struct ext4_locality_group *lg;
3470         struct ext4_prealloc_space *pa, *cpa = NULL;
3471         ext4_fsblk_t goal_block;
3472
3473         /* only data can be preallocated */
3474         if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
3475                 return 0;
3476
3477         /* first, try per-file preallocation */
3478         rcu_read_lock();
3479         list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3480
3481                 /* all fields in this condition don't change,
3482                  * so we can skip locking for them */
3483                 if (ac->ac_o_ex.fe_logical < pa->pa_lstart ||
3484                     ac->ac_o_ex.fe_logical >= (pa->pa_lstart +
3485                                                EXT4_C2B(sbi, pa->pa_len)))
3486                         continue;
3487
3488                 /* non-extent files can't have physical blocks past 2^32 */
3489                 if (!(ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS)) &&
3490                     (pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len) >
3491                      EXT4_MAX_BLOCK_FILE_PHYS))
3492                         continue;
3493
3494                 /* found preallocated blocks, use them */
3495                 spin_lock(&pa->pa_lock);
3496                 if (pa->pa_deleted == 0 && pa->pa_free) {
3497                         atomic_inc(&pa->pa_count);
3498                         ext4_mb_use_inode_pa(ac, pa);
3499                         spin_unlock(&pa->pa_lock);
3500                         ac->ac_criteria = 10;
3501                         rcu_read_unlock();
3502                         return 1;
3503                 }
3504                 spin_unlock(&pa->pa_lock);
3505         }
3506         rcu_read_unlock();
3507
3508         /* can we use group allocation? */
3509         if (!(ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC))
3510                 return 0;
3511
3512         /* inode may have no locality group for some reason */
3513         lg = ac->ac_lg;
3514         if (lg == NULL)
3515                 return 0;
3516         order  = fls(ac->ac_o_ex.fe_len) - 1;
3517         if (order > PREALLOC_TB_SIZE - 1)
3518                 /* The max size of hash table is PREALLOC_TB_SIZE */
3519                 order = PREALLOC_TB_SIZE - 1;
3520
3521         goal_block = ext4_grp_offs_to_block(ac->ac_sb, &ac->ac_g_ex);
3522         /*
3523          * search for the prealloc space that is having
3524          * minimal distance from the goal block.
3525          */
3526         for (i = order; i < PREALLOC_TB_SIZE; i++) {
3527                 rcu_read_lock();
3528                 list_for_each_entry_rcu(pa, &lg->lg_prealloc_list[i],
3529                                         pa_inode_list) {
3530                         spin_lock(&pa->pa_lock);
3531                         if (pa->pa_deleted == 0 &&
3532                                         pa->pa_free >= ac->ac_o_ex.fe_len) {
3533
3534                                 cpa = ext4_mb_check_group_pa(goal_block,
3535                                                                 pa, cpa);
3536                         }
3537                         spin_unlock(&pa->pa_lock);
3538                 }
3539                 rcu_read_unlock();
3540         }
3541         if (cpa) {
3542                 ext4_mb_use_group_pa(ac, cpa);
3543                 ac->ac_criteria = 20;
3544                 return 1;
3545         }
3546         return 0;
3547 }
3548
3549 /*
3550  * the function goes through all block freed in the group
3551  * but not yet committed and marks them used in in-core bitmap.
3552  * buddy must be generated from this bitmap
3553  * Need to be called with the ext4 group lock held
3554  */
3555 static void ext4_mb_generate_from_freelist(struct super_block *sb, void *bitmap,
3556                                                 ext4_group_t group)
3557 {
3558         struct rb_node *n;
3559         struct ext4_group_info *grp;
3560         struct ext4_free_data *entry;
3561
3562         grp = ext4_get_group_info(sb, group);
3563         n = rb_first(&(grp->bb_free_root));
3564
3565         while (n) {
3566                 entry = rb_entry(n, struct ext4_free_data, efd_node);
3567                 ext4_set_bits(bitmap, entry->efd_start_cluster, entry->efd_count);
3568                 n = rb_next(n);
3569         }
3570         return;
3571 }
3572
3573 /*
3574  * the function goes through all preallocation in this group and marks them
3575  * used in in-core bitmap. buddy must be generated from this bitmap
3576  * Need to be called with ext4 group lock held
3577  */
3578 static noinline_for_stack
3579 void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
3580                                         ext4_group_t group)
3581 {
3582         struct ext4_group_info *grp = ext4_get_group_info(sb, group);
3583         struct ext4_prealloc_space *pa;
3584         struct list_head *cur;
3585         ext4_group_t groupnr;
3586         ext4_grpblk_t start;
3587         int preallocated = 0;
3588         int len;
3589
3590         /* all form of preallocation discards first load group,
3591          * so the only competing code is preallocation use.
3592          * we don't need any locking here
3593          * notice we do NOT ignore preallocations with pa_deleted
3594          * otherwise we could leave used blocks available for
3595          * allocation in buddy when concurrent ext4_mb_put_pa()
3596          * is dropping preallocation
3597          */
3598         list_for_each(cur, &grp->bb_prealloc_list) {
3599                 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
3600                 spin_lock(&pa->pa_lock);
3601                 ext4_get_group_no_and_offset(sb, pa->pa_pstart,
3602                                              &groupnr, &start);
3603                 len = pa->pa_len;
3604                 spin_unlock(&pa->pa_lock);
3605                 if (unlikely(len == 0))
3606                         continue;
3607                 BUG_ON(groupnr != group);
3608                 ext4_set_bits(bitmap, start, len);
3609                 preallocated += len;
3610         }
3611         mb_debug(1, "preallocated %u for group %u\n", preallocated, group);
3612 }
3613
3614 static void ext4_mb_pa_callback(struct rcu_head *head)
3615 {
3616         struct ext4_prealloc_space *pa;
3617         pa = container_of(head, struct ext4_prealloc_space, u.pa_rcu);
3618
3619         BUG_ON(atomic_read(&pa->pa_count));
3620         BUG_ON(pa->pa_deleted == 0);
3621         kmem_cache_free(ext4_pspace_cachep, pa);
3622 }
3623
3624 /*
3625  * drops a reference to preallocated space descriptor
3626  * if this was the last reference and the space is consumed
3627  */
3628 static void ext4_mb_put_pa(struct ext4_allocation_context *ac,
3629                         struct super_block *sb, struct ext4_prealloc_space *pa)
3630 {
3631         ext4_group_t grp;
3632         ext4_fsblk_t grp_blk;
3633
3634         /* in this short window concurrent discard can set pa_deleted */
3635         spin_lock(&pa->pa_lock);
3636         if (!atomic_dec_and_test(&pa->pa_count) || pa->pa_free != 0) {
3637                 spin_unlock(&pa->pa_lock);
3638                 return;
3639         }
3640
3641         if (pa->pa_deleted == 1) {
3642                 spin_unlock(&pa->pa_lock);
3643                 return;
3644         }
3645
3646         pa->pa_deleted = 1;
3647         spin_unlock(&pa->pa_lock);
3648
3649         grp_blk = pa->pa_pstart;
3650         /*
3651          * If doing group-based preallocation, pa_pstart may be in the
3652          * next group when pa is used up
3653          */
3654         if (pa->pa_type == MB_GROUP_PA)
3655                 grp_blk--;
3656
3657         grp = ext4_get_group_number(sb, grp_blk);
3658
3659         /*
3660          * possible race:
3661          *
3662          *  P1 (buddy init)                     P2 (regular allocation)
3663          *                                      find block B in PA
3664          *  copy on-disk bitmap to buddy
3665          *                                      mark B in on-disk bitmap
3666          *                                      drop PA from group
3667          *  mark all PAs in buddy
3668          *
3669          * thus, P1 initializes buddy with B available. to prevent this
3670          * we make "copy" and "mark all PAs" atomic and serialize "drop PA"
3671          * against that pair
3672          */
3673         ext4_lock_group(sb, grp);
3674         list_del(&pa->pa_group_list);
3675         ext4_unlock_group(sb, grp);
3676
3677         spin_lock(pa->pa_obj_lock);
3678         list_del_rcu(&pa->pa_inode_list);
3679         spin_unlock(pa->pa_obj_lock);
3680
3681         call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
3682 }
3683
3684 /*
3685  * creates new preallocated space for given inode
3686  */
3687 static noinline_for_stack int
3688 ext4_mb_new_inode_pa(struct ext4_allocation_context *ac)
3689 {
3690         struct super_block *sb = ac->ac_sb;
3691         struct ext4_sb_info *sbi = EXT4_SB(sb);
3692         struct ext4_prealloc_space *pa;
3693         struct ext4_group_info *grp;
3694         struct ext4_inode_info *ei;
3695
3696         /* preallocate only when found space is larger then requested */
3697         BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
3698         BUG_ON(ac->ac_status != AC_STATUS_FOUND);
3699         BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
3700
3701         pa = kmem_cache_alloc(ext4_pspace_cachep, GFP_NOFS);
3702         if (pa == NULL)
3703                 return -ENOMEM;
3704
3705         if (ac->ac_b_ex.fe_len < ac->ac_g_ex.fe_len) {
3706                 int winl;
3707                 int wins;
3708                 int win;
3709                 int offs;
3710
3711                 /* we can't allocate as much as normalizer wants.
3712                  * so, found space must get proper lstart
3713                  * to cover original request */
3714                 BUG_ON(ac->ac_g_ex.fe_logical > ac->ac_o_ex.fe_logical);
3715                 BUG_ON(ac->ac_g_ex.fe_len < ac->ac_o_ex.fe_len);
3716
3717                 /* we're limited by original request in that
3718                  * logical block must be covered any way
3719                  * winl is window we can move our chunk within */
3720                 winl = ac->ac_o_ex.fe_logical - ac->ac_g_ex.fe_logical;
3721
3722                 /* also, we should cover whole original request */
3723                 wins = EXT4_C2B(sbi, ac->ac_b_ex.fe_len - ac->ac_o_ex.fe_len);
3724
3725                 /* the smallest one defines real window */
3726                 win = min(winl, wins);
3727
3728                 offs = ac->ac_o_ex.fe_logical %
3729                         EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
3730                 if (offs && offs < win)
3731                         win = offs;
3732
3733                 ac->ac_b_ex.fe_logical = ac->ac_o_ex.fe_logical -
3734                         EXT4_NUM_B2C(sbi, win);
3735                 BUG_ON(ac->ac_o_ex.fe_logical < ac->ac_b_ex.fe_logical);
3736                 BUG_ON(ac->ac_o_ex.fe_len > ac->ac_b_ex.fe_len);
3737         }
3738
3739         /* preallocation can change ac_b_ex, thus we store actually
3740          * allocated blocks for history */
3741         ac->ac_f_ex = ac->ac_b_ex;
3742
3743         pa->pa_lstart = ac->ac_b_ex.fe_logical;
3744         pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
3745         pa->pa_len = ac->ac_b_ex.fe_len;
3746         pa->pa_free = pa->pa_len;
3747         atomic_set(&pa->pa_count, 1);
3748         spin_lock_init(&pa->pa_lock);
3749         INIT_LIST_HEAD(&pa->pa_inode_list);
3750         INIT_LIST_HEAD(&pa->pa_group_list);
3751         pa->pa_deleted = 0;
3752         pa->pa_type = MB_INODE_PA;
3753
3754         mb_debug(1, "new inode pa %p: %llu/%u for %u\n", pa,
3755                         pa->pa_pstart, pa->pa_len, pa->pa_lstart);
3756         trace_ext4_mb_new_inode_pa(ac, pa);
3757
3758         ext4_mb_use_inode_pa(ac, pa);
3759         atomic_add(pa->pa_free, &sbi->s_mb_preallocated);
3760
3761         ei = EXT4_I(ac->ac_inode);
3762         grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
3763
3764         pa->pa_obj_lock = &ei->i_prealloc_lock;
3765         pa->pa_inode = ac->ac_inode;
3766
3767         ext4_lock_group(sb, ac->ac_b_ex.fe_group);
3768         list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
3769         ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3770
3771         spin_lock(pa->pa_obj_lock);
3772         list_add_rcu(&pa->pa_inode_list, &ei->i_prealloc_list);
3773         spin_unlock(pa->pa_obj_lock);
3774
3775         return 0;
3776 }
3777
3778 /*
3779  * creates new preallocated space for locality group inodes belongs to
3780  */
3781 static noinline_for_stack int
3782 ext4_mb_new_group_pa(struct ext4_allocation_context *ac)
3783 {
3784         struct super_block *sb = ac->ac_sb;
3785         struct ext4_locality_group *lg;
3786         struct ext4_prealloc_space *pa;
3787         struct ext4_group_info *grp;
3788
3789         /* preallocate only when found space is larger then requested */
3790         BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
3791         BUG_ON(ac->ac_status != AC_STATUS_FOUND);
3792         BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
3793
3794         BUG_ON(ext4_pspace_cachep == NULL);
3795         pa = kmem_cache_alloc(ext4_pspace_cachep, GFP_NOFS);
3796         if (pa == NULL)
3797                 return -ENOMEM;
3798
3799         /* preallocation can change ac_b_ex, thus we store actually
3800          * allocated blocks for history */
3801         ac->ac_f_ex = ac->ac_b_ex;
3802
3803         pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
3804         pa->pa_lstart = pa->pa_pstart;
3805         pa->pa_len = ac->ac_b_ex.fe_len;
3806         pa->pa_free = pa->pa_len;
3807         atomic_set(&pa->pa_count, 1);
3808         spin_lock_init(&pa->pa_lock);
3809         INIT_LIST_HEAD(&pa->pa_inode_list);
3810         INIT_LIST_HEAD(&pa->pa_group_list);
3811         pa->pa_deleted = 0;
3812         pa->pa_type = MB_GROUP_PA;
3813
3814         mb_debug(1, "new group pa %p: %llu/%u for %u\n", pa,
3815                         pa->pa_pstart, pa->pa_len, pa->pa_lstart);
3816         trace_ext4_mb_new_group_pa(ac, pa);
3817
3818         ext4_mb_use_group_pa(ac, pa);
3819         atomic_add(pa->pa_free, &EXT4_SB(sb)->s_mb_preallocated);
3820
3821         grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
3822         lg = ac->ac_lg;
3823         BUG_ON(lg == NULL);
3824
3825         pa->pa_obj_lock = &lg->lg_prealloc_lock;
3826         pa->pa_inode = NULL;
3827
3828         ext4_lock_group(sb, ac->ac_b_ex.fe_group);
3829         list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
3830         ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3831
3832         /*
3833          * We will later add the new pa to the right bucket
3834          * after updating the pa_free in ext4_mb_release_context
3835          */
3836         return 0;
3837 }
3838
3839 static int ext4_mb_new_preallocation(struct ext4_allocation_context *ac)
3840 {
3841         int err;
3842
3843         if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
3844                 err = ext4_mb_new_group_pa(ac);
3845         else
3846                 err = ext4_mb_new_inode_pa(ac);
3847         return err;
3848 }
3849
3850 /*
3851  * finds all unused blocks in on-disk bitmap, frees them in
3852  * in-core bitmap and buddy.
3853  * @pa must be unlinked from inode and group lists, so that
3854  * nobody else can find/use it.
3855  * the caller MUST hold group/inode locks.
3856  * TODO: optimize the case when there are no in-core structures yet
3857  */
3858 static noinline_for_stack int
3859 ext4_mb_release_inode_pa(struct ext4_buddy *e4b, struct buffer_head *bitmap_bh,
3860                         struct ext4_prealloc_space *pa)
3861 {
3862         struct super_block *sb = e4b->bd_sb;
3863         struct ext4_sb_info *sbi = EXT4_SB(sb);
3864         unsigned int end;
3865         unsigned int next;
3866         ext4_group_t group;
3867         ext4_grpblk_t bit;
3868         unsigned long long grp_blk_start;
3869         int err = 0;
3870         int free = 0;
3871
3872         BUG_ON(pa->pa_deleted == 0);
3873         ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
3874         grp_blk_start = pa->pa_pstart - EXT4_C2B(sbi, bit);
3875         BUG_ON(group != e4b->bd_group && pa->pa_len != 0);
3876         end = bit + pa->pa_len;
3877
3878         while (bit < end) {
3879                 bit = mb_find_next_zero_bit(bitmap_bh->b_data, end, bit);
3880                 if (bit >= end)
3881                         break;
3882                 next = mb_find_next_bit(bitmap_bh->b_data, end, bit);
3883                 mb_debug(1, "    free preallocated %u/%u in group %u\n",
3884                          (unsigned) ext4_group_first_block_no(sb, group) + bit,
3885                          (unsigned) next - bit, (unsigned) group);
3886                 free += next - bit;
3887
3888                 trace_ext4_mballoc_discard(sb, NULL, group, bit, next - bit);
3889                 trace_ext4_mb_release_inode_pa(pa, (grp_blk_start +
3890                                                     EXT4_C2B(sbi, bit)),
3891                                                next - bit);
3892                 mb_free_blocks(pa->pa_inode, e4b, bit, next - bit);
3893                 bit = next + 1;
3894         }
3895         if (free != pa->pa_free) {
3896                 ext4_msg(e4b->bd_sb, KERN_CRIT,
3897                          "pa %p: logic %lu, phys. %lu, len %lu",
3898                          pa, (unsigned long) pa->pa_lstart,
3899                          (unsigned long) pa->pa_pstart,
3900                          (unsigned long) pa->pa_len);
3901                 ext4_grp_locked_error(sb, group, 0, 0, "free %u, pa_free %u",
3902                                         free, pa->pa_free);
3903                 /*
3904                  * pa is already deleted so we use the value obtained
3905                  * from the bitmap and continue.
3906                  */
3907         }
3908         atomic_add(free, &sbi->s_mb_discarded);
3909
3910         return err;
3911 }
3912
3913 static noinline_for_stack int
3914 ext4_mb_release_group_pa(struct ext4_buddy *e4b,
3915                                 struct ext4_prealloc_space *pa)
3916 {
3917         struct super_block *sb = e4b->bd_sb;
3918         ext4_group_t group;
3919         ext4_grpblk_t bit;
3920
3921         trace_ext4_mb_release_group_pa(sb, pa);
3922         BUG_ON(pa->pa_deleted == 0);
3923         ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
3924         BUG_ON(group != e4b->bd_group && pa->pa_len != 0);
3925         mb_free_blocks(pa->pa_inode, e4b, bit, pa->pa_len);
3926         atomic_add(pa->pa_len, &EXT4_SB(sb)->s_mb_discarded);
3927         trace_ext4_mballoc_discard(sb, NULL, group, bit, pa->pa_len);
3928
3929         return 0;
3930 }
3931
3932 /*
3933  * releases all preallocations in given group
3934  *
3935  * first, we need to decide discard policy:
3936  * - when do we discard
3937  *   1) ENOSPC
3938  * - how many do we discard
3939  *   1) how many requested
3940  */
3941 static noinline_for_stack int
3942 ext4_mb_discard_group_preallocations(struct super_block *sb,
3943                                         ext4_group_t group, int needed)
3944 {
3945         struct ext4_group_info *grp = ext4_get_group_info(sb, group);
3946         struct buffer_head *bitmap_bh = NULL;
3947         struct ext4_prealloc_space *pa, *tmp;
3948         struct list_head list;
3949         struct ext4_buddy e4b;
3950         int err;
3951         int busy = 0;
3952         int free = 0;
3953
3954         mb_debug(1, "discard preallocation for group %u\n", group);
3955
3956         if (list_empty(&grp->bb_prealloc_list))
3957                 return 0;
3958
3959         bitmap_bh = ext4_read_block_bitmap(sb, group);
3960         if (IS_ERR(bitmap_bh)) {
3961                 err = PTR_ERR(bitmap_bh);
3962                 ext4_error(sb, "Error %d reading block bitmap for %u",
3963                            err, group);
3964                 return 0;
3965         }
3966
3967         err = ext4_mb_load_buddy(sb, group, &e4b);
3968         if (err) {
3969                 ext4_warning(sb, "Error %d loading buddy information for %u",
3970                              err, group);
3971                 put_bh(bitmap_bh);
3972                 return 0;
3973         }
3974
3975         if (needed == 0)
3976                 needed = EXT4_CLUSTERS_PER_GROUP(sb) + 1;
3977
3978         INIT_LIST_HEAD(&list);
3979 repeat:
3980         ext4_lock_group(sb, group);
3981         list_for_each_entry_safe(pa, tmp,
3982                                 &grp->bb_prealloc_list, pa_group_list) {
3983                 spin_lock(&pa->pa_lock);
3984                 if (atomic_read(&pa->pa_count)) {
3985                         spin_unlock(&pa->pa_lock);
3986                         busy = 1;
3987                         continue;
3988                 }
3989                 if (pa->pa_deleted) {
3990                         spin_unlock(&pa->pa_lock);
3991                         continue;
3992                 }
3993
3994                 /* seems this one can be freed ... */
3995                 pa->pa_deleted = 1;
3996
3997                 /* we can trust pa_free ... */
3998                 free += pa->pa_free;
3999
4000                 spin_unlock(&pa->pa_lock);
4001
4002                 list_del(&pa->pa_group_list);
4003                 list_add(&pa->u.pa_tmp_list, &list);
4004         }
4005
4006         /* if we still need more blocks and some PAs were used, try again */
4007         if (free < needed && busy) {
4008                 busy = 0;
4009                 ext4_unlock_group(sb, group);
4010                 cond_resched();
4011                 goto repeat;
4012         }
4013
4014         /* found anything to free? */
4015         if (list_empty(&list)) {
4016                 BUG_ON(free != 0);
4017                 goto out;
4018         }
4019
4020         /* now free all selected PAs */
4021         list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
4022
4023                 /* remove from object (inode or locality group) */
4024                 spin_lock(pa->pa_obj_lock);
4025                 list_del_rcu(&pa->pa_inode_list);
4026                 spin_unlock(pa->pa_obj_lock);
4027
4028                 if (pa->pa_type == MB_GROUP_PA)
4029                         ext4_mb_release_group_pa(&e4b, pa);
4030                 else
4031                         ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa);
4032
4033                 list_del(&pa->u.pa_tmp_list);
4034                 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
4035         }
4036
4037 out:
4038         ext4_unlock_group(sb, group);
4039         ext4_mb_unload_buddy(&e4b);
4040         put_bh(bitmap_bh);
4041         return free;
4042 }
4043
4044 /*
4045  * releases all non-used preallocated blocks for given inode
4046  *
4047  * It's important to discard preallocations under i_data_sem
4048  * We don't want another block to be served from the prealloc
4049  * space when we are discarding the inode prealloc space.
4050  *
4051  * FIXME!! Make sure it is valid at all the call sites
4052  */
4053 void ext4_discard_preallocations(struct inode *inode)
4054 {
4055         struct ext4_inode_info *ei = EXT4_I(inode);
4056         struct super_block *sb = inode->i_sb;
4057         struct buffer_head *bitmap_bh = NULL;
4058         struct ext4_prealloc_space *pa, *tmp;
4059         ext4_group_t group = 0;
4060         struct list_head list;
4061         struct ext4_buddy e4b;
4062         int err;
4063
4064         if (!S_ISREG(inode->i_mode)) {
4065                 /*BUG_ON(!list_empty(&ei->i_prealloc_list));*/
4066                 return;
4067         }
4068
4069         mb_debug(1, "discard preallocation for inode %lu\n", inode->i_ino);
4070         trace_ext4_discard_preallocations(inode);
4071
4072         INIT_LIST_HEAD(&list);
4073
4074 repeat:
4075         /* first, collect all pa's in the inode */
4076         spin_lock(&ei->i_prealloc_lock);
4077         while (!list_empty(&ei->i_prealloc_list)) {
4078                 pa = list_entry(ei->i_prealloc_list.next,
4079                                 struct ext4_prealloc_space, pa_inode_list);
4080                 BUG_ON(pa->pa_obj_lock != &ei->i_prealloc_lock);
4081                 spin_lock(&pa->pa_lock);
4082                 if (atomic_read(&pa->pa_count)) {
4083                         /* this shouldn't happen often - nobody should
4084                          * use preallocation while we're discarding it */
4085                         spin_unlock(&pa->pa_lock);
4086                         spin_unlock(&ei->i_prealloc_lock);
4087                         ext4_msg(sb, KERN_ERR,
4088                                  "uh-oh! used pa while discarding");
4089                         WARN_ON(1);
4090                         schedule_timeout_uninterruptible(HZ);
4091                         goto repeat;
4092
4093                 }
4094                 if (pa->pa_deleted == 0) {
4095                         pa->pa_deleted = 1;
4096                         spin_unlock(&pa->pa_lock);
4097                         list_del_rcu(&pa->pa_inode_list);
4098                         list_add(&pa->u.pa_tmp_list, &list);
4099                         continue;
4100                 }
4101
4102                 /* someone is deleting pa right now */
4103                 spin_unlock(&pa->pa_lock);
4104                 spin_unlock(&ei->i_prealloc_lock);
4105
4106                 /* we have to wait here because pa_deleted
4107                  * doesn't mean pa is already unlinked from
4108                  * the list. as we might be called from
4109                  * ->clear_inode() the inode will get freed
4110                  * and concurrent thread which is unlinking
4111                  * pa from inode's list may access already
4112                  * freed memory, bad-bad-bad */
4113
4114                 /* XXX: if this happens too often, we can
4115                  * add a flag to force wait only in case
4116                  * of ->clear_inode(), but not in case of
4117                  * regular truncate */
4118                 schedule_timeout_uninterruptible(HZ);
4119                 goto repeat;
4120         }
4121         spin_unlock(&ei->i_prealloc_lock);
4122
4123         list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
4124                 BUG_ON(pa->pa_type != MB_INODE_PA);
4125                 group = ext4_get_group_number(sb, pa->pa_pstart);
4126
4127                 err = ext4_mb_load_buddy_gfp(sb, group, &e4b,
4128                                              GFP_NOFS|__GFP_NOFAIL);
4129                 if (err) {
4130                         ext4_error(sb, "Error %d loading buddy information for %u",
4131                                    err, group);
4132                         continue;
4133                 }
4134
4135                 bitmap_bh = ext4_read_block_bitmap(sb, group);
4136                 if (IS_ERR(bitmap_bh)) {
4137                         err = PTR_ERR(bitmap_bh);
4138                         ext4_error(sb, "Error %d reading block bitmap for %u",
4139                                         err, group);
4140                         ext4_mb_unload_buddy(&e4b);
4141                         continue;
4142                 }
4143
4144                 ext4_lock_group(sb, group);
4145                 list_del(&pa->pa_group_list);
4146                 ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa);
4147                 ext4_unlock_group(sb, group);
4148
4149                 ext4_mb_unload_buddy(&e4b);
4150                 put_bh(bitmap_bh);
4151
4152                 list_del(&pa->u.pa_tmp_list);
4153                 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
4154         }
4155 }
4156
4157 #ifdef CONFIG_EXT4_DEBUG
4158 static void ext4_mb_show_ac(struct ext4_allocation_context *ac)
4159 {
4160         struct super_block *sb = ac->ac_sb;
4161         ext4_group_t ngroups, i;
4162
4163         if (!ext4_mballoc_debug ||
4164             (EXT4_SB(sb)->s_mount_flags & EXT4_MF_FS_ABORTED))
4165                 return;
4166
4167         ext4_msg(ac->ac_sb, KERN_ERR, "Can't allocate:"
4168                         " Allocation context details:");
4169         ext4_msg(ac->ac_sb, KERN_ERR, "status %d flags %d",
4170                         ac->ac_status, ac->ac_flags);
4171         ext4_msg(ac->ac_sb, KERN_ERR, "orig %lu/%lu/%lu@%lu, "
4172                         "goal %lu/%lu/%lu@%lu, "
4173                         "best %lu/%lu/%lu@%lu cr %d",
4174                         (unsigned long)ac->ac_o_ex.fe_group,
4175                         (unsigned long)ac->ac_o_ex.fe_start,
4176                         (unsigned long)ac->ac_o_ex.fe_len,
4177                         (unsigned long)ac->ac_o_ex.fe_logical,
4178                         (unsigned long)ac->ac_g_ex.fe_group,
4179                         (unsigned long)ac->ac_g_ex.fe_start,
4180                         (unsigned long)ac->ac_g_ex.fe_len,
4181                         (unsigned long)ac->ac_g_ex.fe_logical,
4182                         (unsigned long)ac->ac_b_ex.fe_group,
4183                         (unsigned long)ac->ac_b_ex.fe_start,
4184                         (unsigned long)ac->ac_b_ex.fe_len,
4185                         (unsigned long)ac->ac_b_ex.fe_logical,
4186                         (int)ac->ac_criteria);
4187         ext4_msg(ac->ac_sb, KERN_ERR, "%d found", ac->ac_found);
4188         ext4_msg(ac->ac_sb, KERN_ERR, "groups: ");
4189         ngroups = ext4_get_groups_count(sb);
4190         for (i = 0; i < ngroups; i++) {
4191                 struct ext4_group_info *grp = ext4_get_group_info(sb, i);
4192                 struct ext4_prealloc_space *pa;
4193                 ext4_grpblk_t start;
4194                 struct list_head *cur;
4195                 ext4_lock_group(sb, i);
4196                 list_for_each(cur, &grp->bb_prealloc_list) {
4197                         pa = list_entry(cur, struct ext4_prealloc_space,
4198                                         pa_group_list);
4199                         spin_lock(&pa->pa_lock);
4200                         ext4_get_group_no_and_offset(sb, pa->pa_pstart,
4201                                                      NULL, &start);
4202                         spin_unlock(&pa->pa_lock);
4203                         printk(KERN_ERR "PA:%u:%d:%u \n", i,
4204                                start, pa->pa_len);
4205                 }
4206                 ext4_unlock_group(sb, i);
4207
4208                 if (grp->bb_free == 0)
4209                         continue;
4210                 printk(KERN_ERR "%u: %d/%d \n",
4211                        i, grp->bb_free, grp->bb_fragments);
4212         }
4213         printk(KERN_ERR "\n");
4214 }
4215 #else
4216 static inline void ext4_mb_show_ac(struct ext4_allocation_context *ac)
4217 {
4218         return;
4219 }
4220 #endif
4221
4222 /*
4223  * We use locality group preallocation for small size file. The size of the
4224  * file is determined by the current size or the resulting size after
4225  * allocation which ever is larger
4226  *
4227  * One can tune this size via /sys/fs/ext4/<partition>/mb_stream_req
4228  */
4229 static void ext4_mb_group_or_file(struct ext4_allocation_context *ac)
4230 {
4231         struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
4232         int bsbits = ac->ac_sb->s_blocksize_bits;
4233         loff_t size, isize;
4234
4235         if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
4236                 return;
4237
4238         if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
4239                 return;
4240
4241         size = ac->ac_o_ex.fe_logical + EXT4_C2B(sbi, ac->ac_o_ex.fe_len);
4242         isize = (i_size_read(ac->ac_inode) + ac->ac_sb->s_blocksize - 1)
4243                 >> bsbits;
4244
4245         if ((size == isize) &&
4246             !ext4_fs_is_busy(sbi) &&
4247             (atomic_read(&ac->ac_inode->i_writecount) == 0)) {
4248                 ac->ac_flags |= EXT4_MB_HINT_NOPREALLOC;
4249                 return;
4250         }
4251
4252         if (sbi->s_mb_group_prealloc <= 0) {
4253                 ac->ac_flags |= EXT4_MB_STREAM_ALLOC;
4254                 return;
4255         }
4256
4257         /* don't use group allocation for large files */
4258         size = max(size, isize);
4259         if (size > sbi->s_mb_stream_request) {
4260                 ac->ac_flags |= EXT4_MB_STREAM_ALLOC;
4261                 return;
4262         }
4263
4264         BUG_ON(ac->ac_lg != NULL);
4265         /*
4266          * locality group prealloc space are per cpu. The reason for having
4267          * per cpu locality group is to reduce the contention between block
4268          * request from multiple CPUs.
4269          */
4270         ac->ac_lg = raw_cpu_ptr(sbi->s_locality_groups);
4271
4272         /* we're going to use group allocation */
4273         ac->ac_flags |= EXT4_MB_HINT_GROUP_ALLOC;
4274
4275         /* serialize all allocations in the group */
4276         mutex_lock(&ac->ac_lg->lg_mutex);
4277 }
4278
4279 static noinline_for_stack int
4280 ext4_mb_initialize_context(struct ext4_allocation_context *ac,
4281                                 struct ext4_allocation_request *ar)
4282 {
4283         struct super_block *sb = ar->inode->i_sb;
4284         struct ext4_sb_info *sbi = EXT4_SB(sb);
4285         struct ext4_super_block *es = sbi->s_es;
4286         ext4_group_t group;
4287         unsigned int len;
4288         ext4_fsblk_t goal;
4289         ext4_grpblk_t block;
4290
4291         /* we can't allocate > group size */
4292         len = ar->len;
4293
4294         /* just a dirty hack to filter too big requests  */
4295         if (len >= EXT4_CLUSTERS_PER_GROUP(sb))
4296                 len = EXT4_CLUSTERS_PER_GROUP(sb);
4297
4298         /* start searching from the goal */
4299         goal = ar->goal;
4300         if (goal < le32_to_cpu(es->s_first_data_block) ||
4301                         goal >= ext4_blocks_count(es))
4302                 goal = le32_to_cpu(es->s_first_data_block);
4303         ext4_get_group_no_and_offset(sb, goal, &group, &block);
4304
4305         /* set up allocation goals */
4306         ac->ac_b_ex.fe_logical = EXT4_LBLK_CMASK(sbi, ar->logical);
4307         ac->ac_status = AC_STATUS_CONTINUE;
4308         ac->ac_sb = sb;
4309         ac->ac_inode = ar->inode;
4310         ac->ac_o_ex.fe_logical = ac->ac_b_ex.fe_logical;
4311         ac->ac_o_ex.fe_group = group;
4312         ac->ac_o_ex.fe_start = block;
4313         ac->ac_o_ex.fe_len = len;
4314         ac->ac_g_ex = ac->ac_o_ex;
4315         ac->ac_flags = ar->flags;
4316
4317         /* we have to define context: we'll we work with a file or
4318          * locality group. this is a policy, actually */
4319         ext4_mb_group_or_file(ac);
4320
4321         mb_debug(1, "init ac: %u blocks @ %u, goal %u, flags %x, 2^%d, "
4322                         "left: %u/%u, right %u/%u to %swritable\n",
4323                         (unsigned) ar->len, (unsigned) ar->logical,
4324                         (unsigned) ar->goal, ac->ac_flags, ac->ac_2order,
4325                         (unsigned) ar->lleft, (unsigned) ar->pleft,
4326                         (unsigned) ar->lright, (unsigned) ar->pright,
4327                         atomic_read(&ar->inode->i_writecount) ? "" : "non-");
4328         return 0;
4329
4330 }
4331
4332 static noinline_for_stack void
4333 ext4_mb_discard_lg_preallocations(struct super_block *sb,
4334                                         struct ext4_locality_group *lg,
4335                                         int order, int total_entries)
4336 {
4337         ext4_group_t group = 0;
4338         struct ext4_buddy e4b;
4339         struct list_head discard_list;
4340         struct ext4_prealloc_space *pa, *tmp;
4341
4342         mb_debug(1, "discard locality group preallocation\n");
4343
4344         INIT_LIST_HEAD(&discard_list);
4345
4346         spin_lock(&lg->lg_prealloc_lock);
4347         list_for_each_entry_rcu(pa, &lg->lg_prealloc_list[order],
4348                                                 pa_inode_list) {
4349                 spin_lock(&pa->pa_lock);
4350                 if (atomic_read(&pa->pa_count)) {
4351                         /*
4352                          * This is the pa that we just used
4353                          * for block allocation. So don't
4354                          * free that
4355                          */
4356                         spin_unlock(&pa->pa_lock);
4357                         continue;
4358                 }
4359                 if (pa->pa_deleted) {
4360                         spin_unlock(&pa->pa_lock);
4361                         continue;
4362                 }
4363                 /* only lg prealloc space */
4364                 BUG_ON(pa->pa_type != MB_GROUP_PA);
4365
4366                 /* seems this one can be freed ... */
4367                 pa->pa_deleted = 1;
4368                 spin_unlock(&pa->pa_lock);
4369
4370                 list_del_rcu(&pa->pa_inode_list);
4371                 list_add(&pa->u.pa_tmp_list, &discard_list);
4372
4373                 total_entries--;
4374                 if (total_entries <= 5) {
4375                         /*
4376                          * we want to keep only 5 entries
4377                          * allowing it to grow to 8. This
4378                          * mak sure we don't call discard
4379                          * soon for this list.
4380                          */
4381                         break;
4382                 }
4383         }
4384         spin_unlock(&lg->lg_prealloc_lock);
4385
4386         list_for_each_entry_safe(pa, tmp, &discard_list, u.pa_tmp_list) {
4387                 int err;
4388
4389                 group = ext4_get_group_number(sb, pa->pa_pstart);
4390                 err = ext4_mb_load_buddy_gfp(sb, group, &e4b,
4391                                              GFP_NOFS|__GFP_NOFAIL);
4392                 if (err) {
4393                         ext4_error(sb, "Error %d loading buddy information for %u",
4394                                    err, group);
4395                         continue;
4396                 }
4397                 ext4_lock_group(sb, group);
4398                 list_del(&pa->pa_group_list);
4399                 ext4_mb_release_group_pa(&e4b, pa);
4400                 ext4_unlock_group(sb, group);
4401
4402                 ext4_mb_unload_buddy(&e4b);
4403                 list_del(&pa->u.pa_tmp_list);
4404                 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
4405         }
4406 }
4407
4408 /*
4409  * We have incremented pa_count. So it cannot be freed at this
4410  * point. Also we hold lg_mutex. So no parallel allocation is
4411  * possible from this lg. That means pa_free cannot be updated.
4412  *
4413  * A parallel ext4_mb_discard_group_preallocations is possible.
4414  * which can cause the lg_prealloc_list to be updated.
4415  */
4416
4417 static void ext4_mb_add_n_trim(struct ext4_allocation_context *ac)
4418 {
4419         int order, added = 0, lg_prealloc_count = 1;
4420         struct super_block *sb = ac->ac_sb;
4421         struct ext4_locality_group *lg = ac->ac_lg;
4422         struct ext4_prealloc_space *tmp_pa, *pa = ac->ac_pa;
4423
4424         order = fls(pa->pa_free) - 1;
4425         if (order > PREALLOC_TB_SIZE - 1)
4426                 /* The max size of hash table is PREALLOC_TB_SIZE */
4427                 order = PREALLOC_TB_SIZE - 1;
4428         /* Add the prealloc space to lg */
4429         spin_lock(&lg->lg_prealloc_lock);
4430         list_for_each_entry_rcu(tmp_pa, &lg->lg_prealloc_list[order],
4431                                                 pa_inode_list) {
4432                 spin_lock(&tmp_pa->pa_lock);
4433                 if (tmp_pa->pa_deleted) {
4434                         spin_unlock(&tmp_pa->pa_lock);
4435                         continue;
4436                 }
4437                 if (!added && pa->pa_free < tmp_pa->pa_free) {
4438                         /* Add to the tail of the previous entry */
4439                         list_add_tail_rcu(&pa->pa_inode_list,
4440                                                 &tmp_pa->pa_inode_list);
4441                         added = 1;
4442                         /*
4443                          * we want to count the total
4444                          * number of entries in the list
4445                          */
4446                 }
4447                 spin_unlock(&tmp_pa->pa_lock);
4448                 lg_prealloc_count++;
4449         }
4450         if (!added)
4451                 list_add_tail_rcu(&pa->pa_inode_list,
4452                                         &lg->lg_prealloc_list[order]);
4453         spin_unlock(&lg->lg_prealloc_lock);
4454
4455         /* Now trim the list to be not more than 8 elements */
4456         if (lg_prealloc_count > 8) {
4457                 ext4_mb_discard_lg_preallocations(sb, lg,
4458                                                   order, lg_prealloc_count);
4459                 return;
4460         }
4461         return ;
4462 }
4463
4464 /*
4465  * release all resource we used in allocation
4466  */
4467 static int ext4_mb_release_context(struct ext4_allocation_context *ac)
4468 {
4469         struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
4470         struct ext4_prealloc_space *pa = ac->ac_pa;
4471         if (pa) {
4472                 if (pa->pa_type == MB_GROUP_PA) {
4473                         /* see comment in ext4_mb_use_group_pa() */
4474                         spin_lock(&pa->pa_lock);
4475                         pa->pa_pstart += EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
4476                         pa->pa_lstart += EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
4477                         pa->pa_free -= ac->ac_b_ex.fe_len;
4478                         pa->pa_len -= ac->ac_b_ex.fe_len;
4479                         spin_unlock(&pa->pa_lock);
4480                 }
4481         }
4482         if (pa) {
4483                 /*
4484                  * We want to add the pa to the right bucket.
4485                  * Remove it from the list and while adding
4486                  * make sure the list to which we are adding
4487                  * doesn't grow big.
4488                  */
4489                 if ((pa->pa_type == MB_GROUP_PA) && likely(pa->pa_free)) {
4490                         spin_lock(pa->pa_obj_lock);
4491                         list_del_rcu(&pa->pa_inode_list);
4492                         spin_unlock(pa->pa_obj_lock);
4493                         ext4_mb_add_n_trim(ac);
4494                 }
4495                 ext4_mb_put_pa(ac, ac->ac_sb, pa);
4496         }
4497         if (ac->ac_bitmap_page)
4498                 put_page(ac->ac_bitmap_page);
4499         if (ac->ac_buddy_page)
4500                 put_page(ac->ac_buddy_page);
4501         if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
4502                 mutex_unlock(&ac->ac_lg->lg_mutex);
4503         ext4_mb_collect_stats(ac);
4504         return 0;
4505 }
4506
4507 static int ext4_mb_discard_preallocations(struct super_block *sb, int needed)
4508 {
4509         ext4_group_t i, ngroups = ext4_get_groups_count(sb);
4510         int ret;
4511         int freed = 0;
4512
4513         trace_ext4_mb_discard_preallocations(sb, needed);
4514         for (i = 0; i < ngroups && needed > 0; i++) {
4515                 ret = ext4_mb_discard_group_preallocations(sb, i, needed);
4516                 freed += ret;
4517                 needed -= ret;
4518         }
4519
4520         return freed;
4521 }
4522
4523 /*
4524  * Main entry point into mballoc to allocate blocks
4525  * it tries to use preallocation first, then falls back
4526  * to usual allocation
4527  */
4528 ext4_fsblk_t ext4_mb_new_blocks(handle_t *handle,
4529                                 struct ext4_allocation_request *ar, int *errp)
4530 {
4531         int freed;
4532         struct ext4_allocation_context *ac = NULL;
4533         struct ext4_sb_info *sbi;
4534         struct super_block *sb;
4535         ext4_fsblk_t block = 0;
4536         unsigned int inquota = 0;
4537         unsigned int reserv_clstrs = 0;
4538
4539         might_sleep();
4540         sb = ar->inode->i_sb;
4541         sbi = EXT4_SB(sb);
4542
4543         trace_ext4_request_blocks(ar);
4544
4545         /* Allow to use superuser reservation for quota file */
4546         if (ext4_is_quota_file(ar->inode))
4547                 ar->flags |= EXT4_MB_USE_ROOT_BLOCKS;
4548
4549         if ((ar->flags & EXT4_MB_DELALLOC_RESERVED) == 0) {
4550                 /* Without delayed allocation we need to verify
4551                  * there is enough free blocks to do block allocation
4552                  * and verify allocation doesn't exceed the quota limits.
4553                  */
4554                 while (ar->len &&
4555                         ext4_claim_free_clusters(sbi, ar->len, ar->flags)) {
4556
4557                         /* let others to free the space */
4558                         cond_resched();
4559                         ar->len = ar->len >> 1;
4560                 }
4561                 if (!ar->len) {
4562                         *errp = -ENOSPC;
4563                         return 0;
4564                 }
4565                 reserv_clstrs = ar->len;
4566                 if (ar->flags & EXT4_MB_USE_ROOT_BLOCKS) {
4567                         dquot_alloc_block_nofail(ar->inode,
4568                                                  EXT4_C2B(sbi, ar->len));
4569                 } else {
4570                         while (ar->len &&
4571                                 dquot_alloc_block(ar->inode,
4572                                                   EXT4_C2B(sbi, ar->len))) {
4573
4574                                 ar->flags |= EXT4_MB_HINT_NOPREALLOC;
4575                                 ar->len--;
4576                         }
4577                 }
4578                 inquota = ar->len;
4579                 if (ar->len == 0) {
4580                         *errp = -EDQUOT;
4581                         goto out;
4582                 }
4583         }
4584
4585         ac = kmem_cache_zalloc(ext4_ac_cachep, GFP_NOFS);
4586         if (!ac) {
4587                 ar->len = 0;
4588                 *errp = -ENOMEM;
4589                 goto out;
4590         }
4591
4592         *errp = ext4_mb_initialize_context(ac, ar);
4593         if (*errp) {
4594                 ar->len = 0;
4595                 goto out;
4596         }
4597
4598         ac->ac_op = EXT4_MB_HISTORY_PREALLOC;
4599         if (!ext4_mb_use_preallocated(ac)) {
4600                 ac->ac_op = EXT4_MB_HISTORY_ALLOC;
4601                 ext4_mb_normalize_request(ac, ar);
4602 repeat:
4603                 /* allocate space in core */
4604                 *errp = ext4_mb_regular_allocator(ac);
4605                 if (*errp)
4606                         goto discard_and_exit;
4607
4608                 /* as we've just preallocated more space than
4609                  * user requested originally, we store allocated
4610                  * space in a special descriptor */
4611                 if (ac->ac_status == AC_STATUS_FOUND &&
4612                     ac->ac_o_ex.fe_len < ac->ac_b_ex.fe_len)
4613                         *errp = ext4_mb_new_preallocation(ac);
4614                 if (*errp) {
4615                 discard_and_exit:
4616                         ext4_discard_allocated_blocks(ac);
4617                         goto errout;
4618                 }
4619         }
4620         if (likely(ac->ac_status == AC_STATUS_FOUND)) {
4621                 *errp = ext4_mb_mark_diskspace_used(ac, handle, reserv_clstrs);
4622                 if (*errp) {
4623                         ext4_discard_allocated_blocks(ac);
4624                         goto errout;
4625                 } else {
4626                         block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
4627                         ar->len = ac->ac_b_ex.fe_len;
4628                 }
4629         } else {
4630                 freed  = ext4_mb_discard_preallocations(sb, ac->ac_o_ex.fe_len);
4631                 if (freed)
4632                         goto repeat;
4633                 *errp = -ENOSPC;
4634         }
4635
4636 errout:
4637         if (*errp) {
4638                 ac->ac_b_ex.fe_len = 0;
4639                 ar->len = 0;
4640                 ext4_mb_show_ac(ac);
4641         }
4642         ext4_mb_release_context(ac);
4643 out:
4644         if (ac)
4645                 kmem_cache_free(ext4_ac_cachep, ac);
4646         if (inquota && ar->len < inquota)
4647                 dquot_free_block(ar->inode, EXT4_C2B(sbi, inquota - ar->len));
4648         if (!ar->len) {
4649                 if ((ar->flags & EXT4_MB_DELALLOC_RESERVED) == 0)
4650                         /* release all the reserved blocks if non delalloc */
4651                         percpu_counter_sub(&sbi->s_dirtyclusters_counter,
4652                                                 reserv_clstrs);
4653         }
4654
4655         trace_ext4_allocate_blocks(ar, (unsigned long long)block);
4656
4657         return block;
4658 }
4659
4660 /*
4661  * We can merge two free data extents only if the physical blocks
4662  * are contiguous, AND the extents were freed by the same transaction,
4663  * AND the blocks are associated with the same group.
4664  */
4665 static void ext4_try_merge_freed_extent(struct ext4_sb_info *sbi,
4666                                         struct ext4_free_data *entry,
4667                                         struct ext4_free_data *new_entry,
4668                                         struct rb_root *entry_rb_root)
4669 {
4670         if ((entry->efd_tid != new_entry->efd_tid) ||
4671             (entry->efd_group != new_entry->efd_group))
4672                 return;
4673         if (entry->efd_start_cluster + entry->efd_count ==
4674             new_entry->efd_start_cluster) {
4675                 new_entry->efd_start_cluster = entry->efd_start_cluster;
4676                 new_entry->efd_count += entry->efd_count;
4677         } else if (new_entry->efd_start_cluster + new_entry->efd_count ==
4678                    entry->efd_start_cluster) {
4679                 new_entry->efd_count += entry->efd_count;
4680         } else
4681                 return;
4682         spin_lock(&sbi->s_md_lock);
4683         list_del(&entry->efd_list);
4684         spin_unlock(&sbi->s_md_lock);
4685         rb_erase(&entry->efd_node, entry_rb_root);
4686         kmem_cache_free(ext4_free_data_cachep, entry);
4687 }
4688
4689 static noinline_for_stack int
4690 ext4_mb_free_metadata(handle_t *handle, struct ext4_buddy *e4b,
4691                       struct ext4_free_data *new_entry)
4692 {
4693         ext4_group_t group = e4b->bd_group;
4694         ext4_grpblk_t cluster;
4695         ext4_grpblk_t clusters = new_entry->efd_count;
4696         struct ext4_free_data *entry;
4697         struct ext4_group_info *db = e4b->bd_info;
4698         struct super_block *sb = e4b->bd_sb;
4699         struct ext4_sb_info *sbi = EXT4_SB(sb);
4700         struct rb_node **n = &db->bb_free_root.rb_node, *node;
4701         struct rb_node *parent = NULL, *new_node;
4702
4703         BUG_ON(!ext4_handle_valid(handle));
4704         BUG_ON(e4b->bd_bitmap_page == NULL);
4705         BUG_ON(e4b->bd_buddy_page == NULL);
4706
4707         new_node = &new_entry->efd_node;
4708         cluster = new_entry->efd_start_cluster;
4709
4710         if (!*n) {
4711                 /* first free block exent. We need to
4712                    protect buddy cache from being freed,
4713                  * otherwise we'll refresh it from
4714                  * on-disk bitmap and lose not-yet-available
4715                  * blocks */
4716                 get_page(e4b->bd_buddy_page);
4717                 get_page(e4b->bd_bitmap_page);
4718         }
4719         while (*n) {
4720                 parent = *n;
4721                 entry = rb_entry(parent, struct ext4_free_data, efd_node);
4722                 if (cluster < entry->efd_start_cluster)
4723                         n = &(*n)->rb_left;
4724                 else if (cluster >= (entry->efd_start_cluster + entry->efd_count))
4725                         n = &(*n)->rb_right;
4726                 else {
4727                         ext4_grp_locked_error(sb, group, 0,
4728                                 ext4_group_first_block_no(sb, group) +
4729                                 EXT4_C2B(sbi, cluster),
4730                                 "Block already on to-be-freed list");
4731                         kmem_cache_free(ext4_free_data_cachep, new_entry);
4732                         return 0;
4733                 }
4734         }
4735
4736         rb_link_node(new_node, parent, n);
4737         rb_insert_color(new_node, &db->bb_free_root);
4738
4739         /* Now try to see the extent can be merged to left and right */
4740         node = rb_prev(new_node);
4741         if (node) {
4742                 entry = rb_entry(node, struct ext4_free_data, efd_node);
4743                 ext4_try_merge_freed_extent(sbi, entry, new_entry,
4744                                             &(db->bb_free_root));
4745         }
4746
4747         node = rb_next(new_node);
4748         if (node) {
4749                 entry = rb_entry(node, struct ext4_free_data, efd_node);
4750                 ext4_try_merge_freed_extent(sbi, entry, new_entry,
4751                                             &(db->bb_free_root));
4752         }
4753
4754         spin_lock(&sbi->s_md_lock);
4755         list_add_tail(&new_entry->efd_list, &sbi->s_freed_data_list);
4756         sbi->s_mb_free_pending += clusters;
4757         spin_unlock(&sbi->s_md_lock);
4758         return 0;
4759 }
4760
4761 /**
4762  * ext4_free_blocks() -- Free given blocks and update quota
4763  * @handle:             handle for this transaction
4764  * @inode:              inode
4765  * @block:              start physical block to free
4766  * @count:              number of blocks to count
4767  * @flags:              flags used by ext4_free_blocks
4768  */
4769 void ext4_free_blocks(handle_t *handle, struct inode *inode,
4770                       struct buffer_head *bh, ext4_fsblk_t block,
4771                       unsigned long count, int flags)
4772 {
4773         struct buffer_head *bitmap_bh = NULL;
4774         struct super_block *sb = inode->i_sb;
4775         struct ext4_group_desc *gdp;
4776         unsigned int overflow;
4777         ext4_grpblk_t bit;
4778         struct buffer_head *gd_bh;
4779         ext4_group_t block_group;
4780         struct ext4_sb_info *sbi;
4781         struct ext4_buddy e4b;
4782         unsigned int count_clusters;
4783         int err = 0;
4784         int ret;
4785
4786         might_sleep();
4787         if (bh) {
4788                 if (block)
4789                         BUG_ON(block != bh->b_blocknr);
4790                 else
4791                         block = bh->b_blocknr;
4792         }
4793
4794         sbi = EXT4_SB(sb);
4795         if (!(flags & EXT4_FREE_BLOCKS_VALIDATED) &&
4796             !ext4_inode_block_valid(inode, block, count)) {
4797                 ext4_error(sb, "Freeing blocks not in datazone - "
4798                            "block = %llu, count = %lu", block, count);
4799                 goto error_return;
4800         }
4801
4802         ext4_debug("freeing block %llu\n", block);
4803         trace_ext4_free_blocks(inode, block, count, flags);
4804
4805         if (bh && (flags & EXT4_FREE_BLOCKS_FORGET)) {
4806                 BUG_ON(count > 1);
4807
4808                 ext4_forget(handle, flags & EXT4_FREE_BLOCKS_METADATA,
4809                             inode, bh, block);
4810         }
4811
4812         /*
4813          * If the extent to be freed does not begin on a cluster
4814          * boundary, we need to deal with partial clusters at the
4815          * beginning and end of the extent.  Normally we will free
4816          * blocks at the beginning or the end unless we are explicitly
4817          * requested to avoid doing so.
4818          */
4819         overflow = EXT4_PBLK_COFF(sbi, block);
4820         if (overflow) {
4821                 if (flags & EXT4_FREE_BLOCKS_NOFREE_FIRST_CLUSTER) {
4822                         overflow = sbi->s_cluster_ratio - overflow;
4823                         block += overflow;
4824                         if (count > overflow)
4825                                 count -= overflow;
4826                         else
4827                                 return;
4828                 } else {
4829                         block -= overflow;
4830                         count += overflow;
4831                 }
4832         }
4833         overflow = EXT4_LBLK_COFF(sbi, count);
4834         if (overflow) {
4835                 if (flags & EXT4_FREE_BLOCKS_NOFREE_LAST_CLUSTER) {
4836                         if (count > overflow)
4837                                 count -= overflow;
4838                         else
4839                                 return;
4840                 } else
4841                         count += sbi->s_cluster_ratio - overflow;
4842         }
4843
4844         if (!bh && (flags & EXT4_FREE_BLOCKS_FORGET)) {
4845                 int i;
4846                 int is_metadata = flags & EXT4_FREE_BLOCKS_METADATA;
4847
4848                 for (i = 0; i < count; i++) {
4849                         cond_resched();
4850                         if (is_metadata)
4851                                 bh = sb_find_get_block(inode->i_sb, block + i);
4852                         ext4_forget(handle, is_metadata, inode, bh, block + i);
4853                 }
4854         }
4855
4856 do_more:
4857         overflow = 0;
4858         ext4_get_group_no_and_offset(sb, block, &block_group, &bit);
4859
4860         if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(
4861                         ext4_get_group_info(sb, block_group))))
4862                 return;
4863
4864         /*
4865          * Check to see if we are freeing blocks across a group
4866          * boundary.
4867          */
4868         if (EXT4_C2B(sbi, bit) + count > EXT4_BLOCKS_PER_GROUP(sb)) {
4869                 overflow = EXT4_C2B(sbi, bit) + count -
4870                         EXT4_BLOCKS_PER_GROUP(sb);
4871                 count -= overflow;
4872         }
4873         count_clusters = EXT4_NUM_B2C(sbi, count);
4874         bitmap_bh = ext4_read_block_bitmap(sb, block_group);
4875         if (IS_ERR(bitmap_bh)) {
4876                 err = PTR_ERR(bitmap_bh);
4877                 bitmap_bh = NULL;
4878                 goto error_return;
4879         }
4880         gdp = ext4_get_group_desc(sb, block_group, &gd_bh);
4881         if (!gdp) {
4882                 err = -EIO;
4883                 goto error_return;
4884         }
4885
4886         if (in_range(ext4_block_bitmap(sb, gdp), block, count) ||
4887             in_range(ext4_inode_bitmap(sb, gdp), block, count) ||
4888             in_range(block, ext4_inode_table(sb, gdp),
4889                      EXT4_SB(sb)->s_itb_per_group) ||
4890             in_range(block + count - 1, ext4_inode_table(sb, gdp),
4891                      EXT4_SB(sb)->s_itb_per_group)) {
4892
4893                 ext4_error(sb, "Freeing blocks in system zone - "
4894                            "Block = %llu, count = %lu", block, count);
4895                 /* err = 0. ext4_std_error should be a no op */
4896                 goto error_return;
4897         }
4898
4899         BUFFER_TRACE(bitmap_bh, "getting write access");
4900         err = ext4_journal_get_write_access(handle, bitmap_bh);
4901         if (err)
4902                 goto error_return;
4903
4904         /*
4905          * We are about to modify some metadata.  Call the journal APIs
4906          * to unshare ->b_data if a currently-committing transaction is
4907          * using it
4908          */
4909         BUFFER_TRACE(gd_bh, "get_write_access");
4910         err = ext4_journal_get_write_access(handle, gd_bh);
4911         if (err)
4912                 goto error_return;
4913 #ifdef AGGRESSIVE_CHECK
4914         {
4915                 int i;
4916                 for (i = 0; i < count_clusters; i++)
4917                         BUG_ON(!mb_test_bit(bit + i, bitmap_bh->b_data));
4918         }
4919 #endif
4920         trace_ext4_mballoc_free(sb, inode, block_group, bit, count_clusters);
4921
4922         /* __GFP_NOFAIL: retry infinitely, ignore TIF_MEMDIE and memcg limit. */
4923         err = ext4_mb_load_buddy_gfp(sb, block_group, &e4b,
4924                                      GFP_NOFS|__GFP_NOFAIL);
4925         if (err)
4926                 goto error_return;
4927
4928         /*
4929          * We need to make sure we don't reuse the freed block until after the
4930          * transaction is committed. We make an exception if the inode is to be
4931          * written in writeback mode since writeback mode has weak data
4932          * consistency guarantees.
4933          */
4934         if (ext4_handle_valid(handle) &&
4935             ((flags & EXT4_FREE_BLOCKS_METADATA) ||
4936              !ext4_should_writeback_data(inode))) {
4937                 struct ext4_free_data *new_entry;
4938                 /*
4939                  * We use __GFP_NOFAIL because ext4_free_blocks() is not allowed
4940                  * to fail.
4941                  */
4942                 new_entry = kmem_cache_alloc(ext4_free_data_cachep,
4943                                 GFP_NOFS|__GFP_NOFAIL);
4944                 new_entry->efd_start_cluster = bit;
4945                 new_entry->efd_group = block_group;
4946                 new_entry->efd_count = count_clusters;
4947                 new_entry->efd_tid = handle->h_transaction->t_tid;
4948
4949                 ext4_lock_group(sb, block_group);
4950                 mb_clear_bits(bitmap_bh->b_data, bit, count_clusters);
4951                 ext4_mb_free_metadata(handle, &e4b, new_entry);
4952         } else {
4953                 /* need to update group_info->bb_free and bitmap
4954                  * with group lock held. generate_buddy look at
4955                  * them with group lock_held
4956                  */
4957                 if (test_opt(sb, DISCARD)) {
4958                         err = ext4_issue_discard(sb, block_group, bit, count,
4959                                                  NULL);
4960                         if (err && err != -EOPNOTSUPP)
4961                                 ext4_msg(sb, KERN_WARNING, "discard request in"
4962                                          " group:%d block:%d count:%lu failed"
4963                                          " with %d", block_group, bit, count,
4964                                          err);
4965                 } else
4966                         EXT4_MB_GRP_CLEAR_TRIMMED(e4b.bd_info);
4967
4968                 ext4_lock_group(sb, block_group);
4969                 mb_clear_bits(bitmap_bh->b_data, bit, count_clusters);
4970                 mb_free_blocks(inode, &e4b, bit, count_clusters);
4971         }
4972
4973         ret = ext4_free_group_clusters(sb, gdp) + count_clusters;
4974         ext4_free_group_clusters_set(sb, gdp, ret);
4975         ext4_block_bitmap_csum_set(sb, block_group, gdp, bitmap_bh);
4976         ext4_group_desc_csum_set(sb, block_group, gdp);
4977         ext4_unlock_group(sb, block_group);
4978
4979         if (sbi->s_log_groups_per_flex) {
4980                 ext4_group_t flex_group = ext4_flex_group(sbi, block_group);
4981                 atomic64_add(count_clusters,
4982                              &sbi_array_rcu_deref(sbi, s_flex_groups,
4983                                                   flex_group)->free_clusters);
4984         }
4985
4986         if (!(flags & EXT4_FREE_BLOCKS_NO_QUOT_UPDATE))
4987                 dquot_free_block(inode, EXT4_C2B(sbi, count_clusters));
4988         percpu_counter_add(&sbi->s_freeclusters_counter, count_clusters);
4989
4990         ext4_mb_unload_buddy(&e4b);
4991
4992         /* We dirtied the bitmap block */
4993         BUFFER_TRACE(bitmap_bh, "dirtied bitmap block");
4994         err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
4995
4996         /* And the group descriptor block */
4997         BUFFER_TRACE(gd_bh, "dirtied group descriptor block");
4998         ret = ext4_handle_dirty_metadata(handle, NULL, gd_bh);
4999         if (!err)
5000                 err = ret;
5001
5002         if (overflow && !err) {
5003                 block += count;
5004                 count = overflow;
5005                 put_bh(bitmap_bh);
5006                 goto do_more;
5007         }
5008 error_return:
5009         brelse(bitmap_bh);
5010         ext4_std_error(sb, err);
5011         return;
5012 }
5013
5014 /**
5015  * ext4_group_add_blocks() -- Add given blocks to an existing group
5016  * @handle:                     handle to this transaction
5017  * @sb:                         super block
5018  * @block:                      start physical block to add to the block group
5019  * @count:                      number of blocks to free
5020  *
5021  * This marks the blocks as free in the bitmap and buddy.
5022  */
5023 int ext4_group_add_blocks(handle_t *handle, struct super_block *sb,
5024                          ext4_fsblk_t block, unsigned long count)
5025 {
5026         struct buffer_head *bitmap_bh = NULL;
5027         struct buffer_head *gd_bh;
5028         ext4_group_t block_group;
5029         ext4_grpblk_t bit;
5030         unsigned int i;
5031         struct ext4_group_desc *desc;
5032         struct ext4_sb_info *sbi = EXT4_SB(sb);
5033         struct ext4_buddy e4b;
5034         int err = 0, ret, blk_free_count;
5035         ext4_grpblk_t blocks_freed;
5036
5037         ext4_debug("Adding block(s) %llu-%llu\n", block, block + count - 1);
5038
5039         if (count == 0)
5040                 return 0;
5041
5042         ext4_get_group_no_and_offset(sb, block, &block_group, &bit);
5043         /*
5044          * Check to see if we are freeing blocks across a group
5045          * boundary.
5046          */
5047         if (bit + count > EXT4_BLOCKS_PER_GROUP(sb)) {
5048                 ext4_warning(sb, "too much blocks added to group %u",
5049                              block_group);
5050                 err = -EINVAL;
5051                 goto error_return;
5052         }
5053
5054         bitmap_bh = ext4_read_block_bitmap(sb, block_group);
5055         if (IS_ERR(bitmap_bh)) {
5056                 err = PTR_ERR(bitmap_bh);
5057                 bitmap_bh = NULL;
5058                 goto error_return;
5059         }
5060
5061         desc = ext4_get_group_desc(sb, block_group, &gd_bh);
5062         if (!desc) {
5063                 err = -EIO;
5064                 goto error_return;
5065         }
5066
5067         if (in_range(ext4_block_bitmap(sb, desc), block, count) ||
5068             in_range(ext4_inode_bitmap(sb, desc), block, count) ||
5069             in_range(block, ext4_inode_table(sb, desc), sbi->s_itb_per_group) ||
5070             in_range(block + count - 1, ext4_inode_table(sb, desc),
5071                      sbi->s_itb_per_group)) {
5072                 ext4_error(sb, "Adding blocks in system zones - "
5073                            "Block = %llu, count = %lu",
5074                            block, count);
5075                 err = -EINVAL;
5076                 goto error_return;
5077         }
5078
5079         BUFFER_TRACE(bitmap_bh, "getting write access");
5080         err = ext4_journal_get_write_access(handle, bitmap_bh);
5081         if (err)
5082                 goto error_return;
5083
5084         /*
5085          * We are about to modify some metadata.  Call the journal APIs
5086          * to unshare ->b_data if a currently-committing transaction is
5087          * using it
5088          */
5089         BUFFER_TRACE(gd_bh, "get_write_access");
5090         err = ext4_journal_get_write_access(handle, gd_bh);
5091         if (err)
5092                 goto error_return;
5093
5094         for (i = 0, blocks_freed = 0; i < count; i++) {
5095                 BUFFER_TRACE(bitmap_bh, "clear bit");
5096                 if (!mb_test_bit(bit + i, bitmap_bh->b_data)) {
5097                         ext4_error(sb, "bit already cleared for block %llu",
5098                                    (ext4_fsblk_t)(block + i));
5099                         BUFFER_TRACE(bitmap_bh, "bit already cleared");
5100                 } else {
5101                         blocks_freed++;
5102                 }
5103         }
5104
5105         err = ext4_mb_load_buddy(sb, block_group, &e4b);
5106         if (err)
5107                 goto error_return;
5108
5109         /*
5110          * need to update group_info->bb_free and bitmap
5111          * with group lock held. generate_buddy look at
5112          * them with group lock_held
5113          */
5114         ext4_lock_group(sb, block_group);
5115         mb_clear_bits(bitmap_bh->b_data, bit, count);
5116         mb_free_blocks(NULL, &e4b, bit, count);
5117         blk_free_count = blocks_freed + ext4_free_group_clusters(sb, desc);
5118         ext4_free_group_clusters_set(sb, desc, blk_free_count);
5119         ext4_block_bitmap_csum_set(sb, block_group, desc, bitmap_bh);
5120         ext4_group_desc_csum_set(sb, block_group, desc);
5121         ext4_unlock_group(sb, block_group);
5122         percpu_counter_add(&sbi->s_freeclusters_counter,
5123                            EXT4_NUM_B2C(sbi, blocks_freed));
5124
5125         if (sbi->s_log_groups_per_flex) {
5126                 ext4_group_t flex_group = ext4_flex_group(sbi, block_group);
5127                 atomic64_add(EXT4_NUM_B2C(sbi, blocks_freed),
5128                              &sbi_array_rcu_deref(sbi, s_flex_groups,
5129                                                   flex_group)->free_clusters);
5130         }
5131
5132         ext4_mb_unload_buddy(&e4b);
5133
5134         /* We dirtied the bitmap block */
5135         BUFFER_TRACE(bitmap_bh, "dirtied bitmap block");
5136         err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
5137
5138         /* And the group descriptor block */
5139         BUFFER_TRACE(gd_bh, "dirtied group descriptor block");
5140         ret = ext4_handle_dirty_metadata(handle, NULL, gd_bh);
5141         if (!err)
5142                 err = ret;
5143
5144 error_return:
5145         brelse(bitmap_bh);
5146         ext4_std_error(sb, err);
5147         return err;
5148 }
5149
5150 /**
5151  * ext4_trim_extent -- function to TRIM one single free extent in the group
5152  * @sb:         super block for the file system
5153  * @start:      starting block of the free extent in the alloc. group
5154  * @count:      number of blocks to TRIM
5155  * @group:      alloc. group we are working with
5156  * @e4b:        ext4 buddy for the group
5157  *
5158  * Trim "count" blocks starting at "start" in the "group". To assure that no
5159  * one will allocate those blocks, mark it as used in buddy bitmap. This must
5160  * be called with under the group lock.
5161  */
5162 static int ext4_trim_extent(struct super_block *sb, int start, int count,
5163                              ext4_group_t group, struct ext4_buddy *e4b)
5164 __releases(bitlock)
5165 __acquires(bitlock)
5166 {
5167         struct ext4_free_extent ex;
5168         int ret = 0;
5169
5170         trace_ext4_trim_extent(sb, group, start, count);
5171
5172         assert_spin_locked(ext4_group_lock_ptr(sb, group));
5173
5174         ex.fe_start = start;
5175         ex.fe_group = group;
5176         ex.fe_len = count;
5177
5178         /*
5179          * Mark blocks used, so no one can reuse them while
5180          * being trimmed.
5181          */
5182         mb_mark_used(e4b, &ex);
5183         ext4_unlock_group(sb, group);
5184         ret = ext4_issue_discard(sb, group, start, count, NULL);
5185         ext4_lock_group(sb, group);
5186         mb_free_blocks(NULL, e4b, start, ex.fe_len);
5187         return ret;
5188 }
5189
5190 /**
5191  * ext4_trim_all_free -- function to trim all free space in alloc. group
5192  * @sb:                 super block for file system
5193  * @group:              group to be trimmed
5194  * @start:              first group block to examine
5195  * @max:                last group block to examine
5196  * @minblocks:          minimum extent block count
5197  *
5198  * ext4_trim_all_free walks through group's buddy bitmap searching for free
5199  * extents. When the free block is found, ext4_trim_extent is called to TRIM
5200  * the extent.
5201  *
5202  *
5203  * ext4_trim_all_free walks through group's block bitmap searching for free
5204  * extents. When the free extent is found, mark it as used in group buddy
5205  * bitmap. Then issue a TRIM command on this extent and free the extent in
5206  * the group buddy bitmap. This is done until whole group is scanned.
5207  */
5208 static ext4_grpblk_t
5209 ext4_trim_all_free(struct super_block *sb, ext4_group_t group,
5210                    ext4_grpblk_t start, ext4_grpblk_t max,
5211                    ext4_grpblk_t minblocks)
5212 {
5213         void *bitmap;
5214         ext4_grpblk_t next, count = 0, free_count = 0;
5215         struct ext4_buddy e4b;
5216         int ret = 0;
5217
5218         trace_ext4_trim_all_free(sb, group, start, max);
5219
5220         ret = ext4_mb_load_buddy(sb, group, &e4b);
5221         if (ret) {
5222                 ext4_warning(sb, "Error %d loading buddy information for %u",
5223                              ret, group);
5224                 return ret;
5225         }
5226         bitmap = e4b.bd_bitmap;
5227
5228         ext4_lock_group(sb, group);
5229         if (EXT4_MB_GRP_WAS_TRIMMED(e4b.bd_info) &&
5230             minblocks >= atomic_read(&EXT4_SB(sb)->s_last_trim_minblks))
5231                 goto out;
5232
5233         start = (e4b.bd_info->bb_first_free > start) ?
5234                 e4b.bd_info->bb_first_free : start;
5235
5236         while (start <= max) {
5237                 start = mb_find_next_zero_bit(bitmap, max + 1, start);
5238                 if (start > max)
5239                         break;
5240                 next = mb_find_next_bit(bitmap, max + 1, start);
5241
5242                 if ((next - start) >= minblocks) {
5243                         ret = ext4_trim_extent(sb, start,
5244                                                next - start, group, &e4b);
5245                         if (ret && ret != -EOPNOTSUPP)
5246                                 break;
5247                         ret = 0;
5248                         count += next - start;
5249                 }
5250                 free_count += next - start;
5251                 start = next + 1;
5252
5253                 if (fatal_signal_pending(current)) {
5254                         count = -ERESTARTSYS;
5255                         break;
5256                 }
5257
5258                 if (need_resched()) {
5259                         ext4_unlock_group(sb, group);
5260                         cond_resched();
5261                         ext4_lock_group(sb, group);
5262                 }
5263
5264                 if ((e4b.bd_info->bb_free - free_count) < minblocks)
5265                         break;
5266         }
5267
5268         if (!ret) {
5269                 ret = count;
5270                 EXT4_MB_GRP_SET_TRIMMED(e4b.bd_info);
5271         }
5272 out:
5273         ext4_unlock_group(sb, group);
5274         ext4_mb_unload_buddy(&e4b);
5275
5276         ext4_debug("trimmed %d blocks in the group %d\n",
5277                 count, group);
5278
5279         return ret;
5280 }
5281
5282 /**
5283  * ext4_trim_fs() -- trim ioctl handle function
5284  * @sb:                 superblock for filesystem
5285  * @range:              fstrim_range structure
5286  *
5287  * start:       First Byte to trim
5288  * len:         number of Bytes to trim from start
5289  * minlen:      minimum extent length in Bytes
5290  * ext4_trim_fs goes through all allocation groups containing Bytes from
5291  * start to start+len. For each such a group ext4_trim_all_free function
5292  * is invoked to trim all free space.
5293  */
5294 int ext4_trim_fs(struct super_block *sb, struct fstrim_range *range)
5295 {
5296         struct request_queue *q = bdev_get_queue(sb->s_bdev);
5297         struct ext4_group_info *grp;
5298         ext4_group_t group, first_group, last_group;
5299         ext4_grpblk_t cnt = 0, first_cluster, last_cluster;
5300         uint64_t start, end, minlen, trimmed = 0;
5301         ext4_fsblk_t first_data_blk =
5302                         le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block);
5303         ext4_fsblk_t max_blks = ext4_blocks_count(EXT4_SB(sb)->s_es);
5304         int ret = 0;
5305
5306         start = range->start >> sb->s_blocksize_bits;
5307         end = start + (range->len >> sb->s_blocksize_bits) - 1;
5308         minlen = EXT4_NUM_B2C(EXT4_SB(sb),
5309                               range->minlen >> sb->s_blocksize_bits);
5310
5311         if (minlen > EXT4_CLUSTERS_PER_GROUP(sb) ||
5312             start >= max_blks ||
5313             range->len < sb->s_blocksize)
5314                 return -EINVAL;
5315         /* No point to try to trim less than discard granularity */
5316         if (range->minlen < q->limits.discard_granularity) {
5317                 minlen = EXT4_NUM_B2C(EXT4_SB(sb),
5318                         q->limits.discard_granularity >> sb->s_blocksize_bits);
5319                 if (minlen > EXT4_CLUSTERS_PER_GROUP(sb))
5320                         goto out;
5321         }
5322         if (end >= max_blks)
5323                 end = max_blks - 1;
5324         if (end <= first_data_blk)
5325                 goto out;
5326         if (start < first_data_blk)
5327                 start = first_data_blk;
5328
5329         /* Determine first and last group to examine based on start and end */
5330         ext4_get_group_no_and_offset(sb, (ext4_fsblk_t) start,
5331                                      &first_group, &first_cluster);
5332         ext4_get_group_no_and_offset(sb, (ext4_fsblk_t) end,
5333                                      &last_group, &last_cluster);
5334
5335         /* end now represents the last cluster to discard in this group */
5336         end = EXT4_CLUSTERS_PER_GROUP(sb) - 1;
5337
5338         for (group = first_group; group <= last_group; group++) {
5339                 grp = ext4_get_group_info(sb, group);
5340                 /* We only do this if the grp has never been initialized */
5341                 if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
5342                         ret = ext4_mb_init_group(sb, group, GFP_NOFS);
5343                         if (ret)
5344                                 break;
5345                 }
5346
5347                 /*
5348                  * For all the groups except the last one, last cluster will
5349                  * always be EXT4_CLUSTERS_PER_GROUP(sb)-1, so we only need to
5350                  * change it for the last group, note that last_cluster is
5351                  * already computed earlier by ext4_get_group_no_and_offset()
5352                  */
5353                 if (group == last_group)
5354                         end = last_cluster;
5355
5356                 if (grp->bb_free >= minlen) {
5357                         cnt = ext4_trim_all_free(sb, group, first_cluster,
5358                                                 end, minlen);
5359                         if (cnt < 0) {
5360                                 ret = cnt;
5361                                 break;
5362                         }
5363                         trimmed += cnt;
5364                 }
5365
5366                 /*
5367                  * For every group except the first one, we are sure
5368                  * that the first cluster to discard will be cluster #0.
5369                  */
5370                 first_cluster = 0;
5371         }
5372
5373         if (!ret)
5374                 atomic_set(&EXT4_SB(sb)->s_last_trim_minblks, minlen);
5375
5376 out:
5377         range->len = EXT4_C2B(EXT4_SB(sb), trimmed) << sb->s_blocksize_bits;
5378         return ret;
5379 }
5380
5381 /* Iterate all the free extents in the group. */
5382 int
5383 ext4_mballoc_query_range(
5384         struct super_block              *sb,
5385         ext4_group_t                    group,
5386         ext4_grpblk_t                   start,
5387         ext4_grpblk_t                   end,
5388         ext4_mballoc_query_range_fn     formatter,
5389         void                            *priv)
5390 {
5391         void                            *bitmap;
5392         ext4_grpblk_t                   next;
5393         struct ext4_buddy               e4b;
5394         int                             error;
5395
5396         error = ext4_mb_load_buddy(sb, group, &e4b);
5397         if (error)
5398                 return error;
5399         bitmap = e4b.bd_bitmap;
5400
5401         ext4_lock_group(sb, group);
5402
5403         start = (e4b.bd_info->bb_first_free > start) ?
5404                 e4b.bd_info->bb_first_free : start;
5405         if (end >= EXT4_CLUSTERS_PER_GROUP(sb))
5406                 end = EXT4_CLUSTERS_PER_GROUP(sb) - 1;
5407
5408         while (start <= end) {
5409                 start = mb_find_next_zero_bit(bitmap, end + 1, start);
5410                 if (start > end)
5411                         break;
5412                 next = mb_find_next_bit(bitmap, end + 1, start);
5413
5414                 ext4_unlock_group(sb, group);
5415                 error = formatter(sb, group, start, next - start, priv);
5416                 if (error)
5417                         goto out_unload;
5418                 ext4_lock_group(sb, group);
5419
5420                 start = next + 1;
5421         }
5422
5423         ext4_unlock_group(sb, group);
5424 out_unload:
5425         ext4_mb_unload_buddy(&e4b);
5426
5427         return error;
5428 }