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