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