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