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