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