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