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