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