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