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