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