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