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