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