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