]> git.proxmox.com Git - mirror_ubuntu-bionic-kernel.git/blob - fs/ext4/mballoc.c
ext4: fix spectre gadget in ext4_mb_regular_allocator()
[mirror_ubuntu-bionic-kernel.git] / fs / ext4 / mballoc.c
1 /*
2 * Copyright (c) 2003-2006, Cluster File Systems, Inc, info@clusterfs.com
3 * Written by Alex Tomas <alex@clusterfs.com>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2 as
7 * published by the Free Software Foundation.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
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
24 #include "ext4_jbd2.h"
25 #include "mballoc.h"
26 #include <linux/log2.h>
27 #include <linux/module.h>
28 #include <linux/slab.h>
29 #include <linux/nospec.h>
30 #include <linux/backing-dev.h>
31 #include <trace/events/ext4.h>
32
33 #ifdef CONFIG_EXT4_DEBUG
34 ushort ext4_mballoc_debug __read_mostly;
35
36 module_param_named(mballoc_debug, ext4_mballoc_debug, ushort, 0644);
37 MODULE_PARM_DESC(mballoc_debug, "Debugging level for ext4's mballoc");
38 #endif
39
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 *
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.
73 *
74 * The main motivation for having small file use group preallocation is to
75 * ensure that we have small files closer together on the disk.
76 *
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:
81 *
82 * pa_lstart -> the logical start block for this prealloc space
83 * pa_pstart -> the physical start block for this prealloc space
84 * pa_len -> length for this prealloc space (in clusters)
85 * pa_free -> free space available in this prealloc space (in clusters)
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
89 * space we will consume the particular prealloc space. This makes sure that
90 * we have contiguous physical blocks representing the file blocks
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
98 * prealloc space. These are per CPU prealloc list represented as
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
106 * enough free space (pa_free) within the prealloc space.
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 }
119 * [ group 0 bitmap][ group 0 buddy] [group 1][ group 1]...
120 *
121 *
122 * one block each for bitmap and buddy information. So for each group we
123 * take up 2 blocks. A page can contain blocks_per_page (PAGE_SIZE /
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
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
142 * 512 blocks. This can be tuned via
143 * /sys/fs/ext4/<partition>/mb_group_prealloc. The value is represented in
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
146 * the smallest multiple of the stripe value (sbi->s_stripe) which is
147 * greater than the default mb_group_prealloc.
148 *
149 * The regular allocator (using the buddy cache) supports a few tunables.
150 *
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
154 *
155 * The regular allocator uses buddy scan only if the request len is power of
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
158 * /sys/fs/ext4/<partition>/mb_order2_req. If the request len is equal to
159 * stripe size (sbi->s_stripe), we try to search for contiguous block in
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.
163 * min_to_scan indicate how long the mballoc __must__ look for a best
164 * extent and max_to_scan indicates how long the mballoc __can__ look for a
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
168 * can be used for allocation. ext4_mb_good_group explains how the groups are
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 */
351 static struct kmem_cache *ext4_pspace_cachep;
352 static struct kmem_cache *ext4_ac_cachep;
353 static struct kmem_cache *ext4_free_data_cachep;
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 */
358 #define NR_GRPINFO_CACHES 8
359 static struct kmem_cache *ext4_groupinfo_caches[NR_GRPINFO_CACHES];
360
361 static const char * const ext4_groupinfo_slab_names[NR_GRPINFO_CACHES] = {
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
367 static void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
368 ext4_group_t group);
369 static void ext4_mb_generate_from_freelist(struct super_block *sb, void *bitmap,
370 ext4_group_t group);
371
372 static inline void *mb_correct_addr_and_bit(int *bit, void *addr)
373 {
374 #if BITS_PER_LONG == 64
375 *bit += ((unsigned long) addr & 7UL) << 3;
376 addr = (void *) ((unsigned long) addr & ~7UL);
377 #elif BITS_PER_LONG == 32
378 *bit += ((unsigned long) addr & 3UL) << 3;
379 addr = (void *) ((unsigned long) addr & ~3UL);
380 #else
381 #error "how many bits you are?!"
382 #endif
383 return addr;
384 }
385
386 static 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 */
392 addr = mb_correct_addr_and_bit(&bit, addr);
393 return ext4_test_bit(bit, addr);
394 }
395
396 static inline void mb_set_bit(int bit, void *addr)
397 {
398 addr = mb_correct_addr_and_bit(&bit, addr);
399 ext4_set_bit(bit, addr);
400 }
401
402 static inline void mb_clear_bit(int bit, void *addr)
403 {
404 addr = mb_correct_addr_and_bit(&bit, addr);
405 ext4_clear_bit(bit, addr);
406 }
407
408 static 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
414 static inline int mb_find_next_zero_bit(void *addr, int max, int start)
415 {
416 int fix = 0, ret, tmpmax;
417 addr = mb_correct_addr_and_bit(&fix, addr);
418 tmpmax = max + fix;
419 start += fix;
420
421 ret = ext4_find_next_zero_bit(addr, tmpmax, start) - fix;
422 if (ret > max)
423 return max;
424 return ret;
425 }
426
427 static inline int mb_find_next_bit(void *addr, int max, int start)
428 {
429 int fix = 0, ret, tmpmax;
430 addr = mb_correct_addr_and_bit(&fix, addr);
431 tmpmax = max + fix;
432 start += fix;
433
434 ret = ext4_find_next_bit(addr, tmpmax, start) - fix;
435 if (ret > max)
436 return max;
437 return ret;
438 }
439
440 static void *mb_find_buddy(struct ext4_buddy *e4b, int order, int *max)
441 {
442 char *bb;
443
444 BUG_ON(e4b->bd_bitmap == e4b->bd_buddy);
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 */
453 if (order == 0) {
454 *max = 1 << (e4b->bd_blkbits + 3);
455 return e4b->bd_bitmap;
456 }
457
458 bb = e4b->bd_buddy + EXT4_SB(e4b->bd_sb)->s_mb_offsets[order];
459 *max = EXT4_SB(e4b->bd_sb)->s_mb_maxs[order];
460
461 return bb;
462 }
463
464 #ifdef DOUBLE_CHECK
465 static 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;
473 assert_spin_locked(ext4_group_lock_ptr(sb, e4b->bd_group));
474 for (i = 0; i < count; i++) {
475 if (!mb_test_bit(first + i, e4b->bd_info->bb_bitmap)) {
476 ext4_fsblk_t blocknr;
477
478 blocknr = ext4_group_first_block_no(sb, e4b->bd_group);
479 blocknr += EXT4_C2B(EXT4_SB(sb), first + i);
480 ext4_grp_locked_error(sb, e4b->bd_group,
481 inode ? inode->i_ino : 0,
482 blocknr,
483 "freeing block already freed "
484 "(bit %u)",
485 first + i);
486 }
487 mb_clear_bit(first + i, e4b->bd_info->bb_bitmap);
488 }
489 }
490
491 static 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;
497 assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
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
504 static 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]) {
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]);
518 BUG();
519 }
520 }
521 }
522 }
523
524 #else
525 static inline void mb_free_blocks_double(struct inode *inode,
526 struct ext4_buddy *e4b, int first, int count)
527 {
528 return;
529 }
530 static inline void mb_mark_used_double(struct ext4_buddy *e4b,
531 int first, int count)
532 {
533 return;
534 }
535 static 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) \
544 do { \
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
553 static 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
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
600 /* both bits in buddy2 must be 1 */
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(
607 !mb_test_bit(k, e4b->bd_bitmap));
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);
639 list_for_each(cur, &grp->bb_prealloc_list) {
640 ext4_group_t groupnr;
641 struct ext4_prealloc_space *pa;
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);
644 MB_CHECK_ASSERT(groupnr == e4b->bd_group);
645 for (i = 0; i < pa->pa_len; i++)
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, \
652 __FILE__, __func__, __LINE__)
653 #else
654 #define mb_check_buddy(e4b)
655 #endif
656
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 */
663 static void ext4_mb_mark_free_simple(struct super_block *sb,
664 void *buddy, ext4_grpblk_t first, ext4_grpblk_t len,
665 struct ext4_group_info *grp)
666 {
667 struct ext4_sb_info *sbi = EXT4_SB(sb);
668 ext4_grpblk_t min;
669 ext4_grpblk_t max;
670 ext4_grpblk_t chunk;
671 unsigned int border;
672
673 BUG_ON(len > EXT4_CLUSTERS_PER_GROUP(sb));
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
699 /*
700 * Cache the order of the largest free extent we have available in this block
701 * group.
702 */
703 static void
704 mb_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
720 static noinline_for_stack
721 void ext4_mb_generate_buddy(struct super_block *sb,
722 void *buddy, void *bitmap, ext4_group_t group)
723 {
724 struct ext4_group_info *grp = ext4_get_group_info(sb, group);
725 struct ext4_sb_info *sbi = EXT4_SB(sb);
726 ext4_grpblk_t max = EXT4_CLUSTERS_PER_GROUP(sb);
727 ext4_grpblk_t i = 0;
728 ext4_grpblk_t first;
729 ext4_grpblk_t len;
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 */
736 i = mb_find_next_zero_bit(bitmap, max, 0);
737 grp->bb_first_free = i;
738 while (i < max) {
739 fragments++;
740 first = i;
741 i = mb_find_next_bit(bitmap, max, i);
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)
749 i = mb_find_next_zero_bit(bitmap, max, i);
750 }
751 grp->bb_fragments = fragments;
752
753 if (free != grp->bb_free) {
754 ext4_grp_locked_error(sb, group, 0, 0,
755 "block bitmap and bg descriptor "
756 "inconsistent: %u vs %u free clusters",
757 free, grp->bb_free);
758 /*
759 * If we intend to continue, we consider group descriptor
760 * corrupt and update bb_free using bitmap value
761 */
762 grp->bb_free = free;
763 if (!EXT4_MB_GRP_BBITMAP_CORRUPT(grp))
764 percpu_counter_sub(&sbi->s_freeclusters_counter,
765 grp->bb_free);
766 set_bit(EXT4_GROUP_INFO_BBITMAP_CORRUPT_BIT, &grp->bb_state);
767 }
768 mb_set_largest_free_order(sb, grp);
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
779 static 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
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 }
804 * [ group 0 bitmap][ group 0 buddy] [group 1][ group 1]...
805 *
806 *
807 * one block each for bitmap and buddy information.
808 * So for each group we take up 2 blocks. A page can
809 * contain blocks_per_page (PAGE_SIZE / blocksize) blocks.
810 * So it can have information regarding groups_per_page which
811 * is blocks_per_page/2
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!
815 */
816
817 static int ext4_mb_init_cache(struct page *page, char *incore, gfp_t gfp)
818 {
819 ext4_group_t ngroups;
820 int blocksize;
821 int blocks_per_page;
822 int groups_per_page;
823 int err = 0;
824 int i;
825 ext4_group_t first_group, group;
826 int first_block;
827 struct super_block *sb;
828 struct buffer_head *bhs;
829 struct buffer_head **bh = NULL;
830 struct inode *inode;
831 char *data;
832 char *bitmap;
833 struct ext4_group_info *grinfo;
834
835 mb_debug(1, "init page %lu\n", page->index);
836
837 inode = page->mapping->host;
838 sb = inode->i_sb;
839 ngroups = ext4_get_groups_count(sb);
840 blocksize = i_blocksize(inode);
841 blocks_per_page = PAGE_SIZE / blocksize;
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) {
849 i = sizeof(struct buffer_head *) * groups_per_page;
850 bh = kzalloc(i, gfp);
851 if (bh == NULL) {
852 err = -ENOMEM;
853 goto out;
854 }
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 */
861 for (i = 0, group = first_group; i < groups_per_page; i++, group++) {
862 if (group >= ngroups)
863 break;
864
865 grinfo = ext4_get_group_info(sb, group);
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 }
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;
880 goto out;
881 }
882 mb_debug(1, "read bitmap for group %u\n", group);
883 }
884
885 /* wait for I/O completion */
886 for (i = 0, group = first_group; i < groups_per_page; i++, group++) {
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;
894 }
895
896 first_block = page->index * blocks_per_page;
897 for (i = 0; i < blocks_per_page; i++) {
898 group = (first_block + i) >> 1;
899 if (group >= ngroups)
900 break;
901
902 if (!bh[group - first_group])
903 /* skip initialized uptodate buddy */
904 continue;
905
906 if (!buffer_verified(bh[group - first_group]))
907 /* Skip faulty bitmaps */
908 continue;
909 err = 0;
910
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);
927 mb_debug(1, "put buddy for group %u in page %lu/%x\n",
928 group, page->index, i * blocksize);
929 trace_ext4_mb_buddy_bitmap_load(sb, group);
930 grinfo = ext4_get_group_info(sb, group);
931 grinfo->bb_fragments = 0;
932 memset(grinfo->bb_counters, 0,
933 sizeof(*grinfo->bb_counters) *
934 (sb->s_blocksize_bits+2));
935 /*
936 * incore got set to the group block bitmap below
937 */
938 ext4_lock_group(sb, group);
939 /* init the buddy */
940 memset(data, 0xff, blocksize);
941 ext4_mb_generate_buddy(sb, data, incore, group);
942 ext4_unlock_group(sb, group);
943 incore = NULL;
944 } else {
945 /* this is block of bitmap */
946 BUG_ON(incore != NULL);
947 mb_debug(1, "put bitmap for group %u in page %lu/%x\n",
948 group, page->index, i * blocksize);
949 trace_ext4_mb_bitmap_load(sb, group);
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);
957 ext4_mb_generate_from_freelist(sb, data, group);
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
968 out:
969 if (bh) {
970 for (i = 0; i < groups_per_page; i++)
971 brelse(bh[i]);
972 if (bh != &bhs)
973 kfree(bh);
974 }
975 return err;
976 }
977
978 /*
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.
983 */
984 static int ext4_mb_get_buddy_page_lock(struct super_block *sb,
985 ext4_group_t group, struct ext4_buddy *e4b, gfp_t gfp)
986 {
987 struct inode *inode = EXT4_SB(sb)->s_buddy_cache;
988 int block, pnum, poff;
989 int blocks_per_page;
990 struct page *page;
991
992 e4b->bd_buddy_page = NULL;
993 e4b->bd_bitmap_page = NULL;
994
995 blocks_per_page = PAGE_SIZE / sb->s_blocksize;
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;
1003 poff = block % blocks_per_page;
1004 page = find_or_create_page(inode->i_mapping, pnum, gfp);
1005 if (!page)
1006 return -ENOMEM;
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;
1014 }
1015
1016 block++;
1017 pnum = block / blocks_per_page;
1018 page = find_or_create_page(inode->i_mapping, pnum, gfp);
1019 if (!page)
1020 return -ENOMEM;
1021 BUG_ON(page->mapping != inode->i_mapping);
1022 e4b->bd_buddy_page = page;
1023 return 0;
1024 }
1025
1026 static void ext4_mb_put_buddy_page_lock(struct ext4_buddy *e4b)
1027 {
1028 if (e4b->bd_bitmap_page) {
1029 unlock_page(e4b->bd_bitmap_page);
1030 put_page(e4b->bd_bitmap_page);
1031 }
1032 if (e4b->bd_buddy_page) {
1033 unlock_page(e4b->bd_buddy_page);
1034 put_page(e4b->bd_buddy_page);
1035 }
1036 }
1037
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 */
1043 static noinline_for_stack
1044 int ext4_mb_init_group(struct super_block *sb, ext4_group_t group, gfp_t gfp)
1045 {
1046
1047 struct ext4_group_info *this_grp;
1048 struct ext4_buddy e4b;
1049 struct page *page;
1050 int ret = 0;
1051
1052 might_sleep();
1053 mb_debug(1, "init group %u\n", group);
1054 this_grp = ext4_get_group_info(sb, group);
1055 /*
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
1060 * would have pinned buddy page to page cache.
1061 * The call to ext4_mb_get_buddy_page_lock will mark the
1062 * page accessed.
1063 */
1064 ret = ext4_mb_get_buddy_page_lock(sb, group, &e4b, gfp);
1065 if (ret || !EXT4_MB_GRP_NEED_INIT(this_grp)) {
1066 /*
1067 * somebody initialized the group
1068 * return without doing anything
1069 */
1070 goto err;
1071 }
1072
1073 page = e4b.bd_bitmap_page;
1074 ret = ext4_mb_init_cache(page, NULL, gfp);
1075 if (ret)
1076 goto err;
1077 if (!PageUptodate(page)) {
1078 ret = -EIO;
1079 goto err;
1080 }
1081
1082 if (e4b.bd_buddy_page == NULL) {
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 */
1088 ret = 0;
1089 goto err;
1090 }
1091 /* init buddy cache */
1092 page = e4b.bd_buddy_page;
1093 ret = ext4_mb_init_cache(page, e4b.bd_bitmap, gfp);
1094 if (ret)
1095 goto err;
1096 if (!PageUptodate(page)) {
1097 ret = -EIO;
1098 goto err;
1099 }
1100 err:
1101 ext4_mb_put_buddy_page_lock(&e4b);
1102 return ret;
1103 }
1104
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 */
1110 static noinline_for_stack int
1111 ext4_mb_load_buddy_gfp(struct super_block *sb, ext4_group_t group,
1112 struct ext4_buddy *e4b, gfp_t gfp)
1113 {
1114 int blocks_per_page;
1115 int block;
1116 int pnum;
1117 int poff;
1118 struct page *page;
1119 int ret;
1120 struct ext4_group_info *grp;
1121 struct ext4_sb_info *sbi = EXT4_SB(sb);
1122 struct inode *inode = sbi->s_buddy_cache;
1123
1124 might_sleep();
1125 mb_debug(1, "load group %u\n", group);
1126
1127 blocks_per_page = PAGE_SIZE / sb->s_blocksize;
1128 grp = ext4_get_group_info(sb, group);
1129
1130 e4b->bd_blkbits = sb->s_blocksize_bits;
1131 e4b->bd_info = grp;
1132 e4b->bd_sb = sb;
1133 e4b->bd_group = group;
1134 e4b->bd_buddy_page = NULL;
1135 e4b->bd_bitmap_page = NULL;
1136
1137 if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
1138 /*
1139 * we need full data about the group
1140 * to make a good selection
1141 */
1142 ret = ext4_mb_init_group(sb, group, gfp);
1143 if (ret)
1144 return ret;
1145 }
1146
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 ... */
1158 page = find_get_page_flags(inode->i_mapping, pnum, FGP_ACCESSED);
1159 if (page == NULL || !PageUptodate(page)) {
1160 if (page)
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 */
1169 put_page(page);
1170 page = find_or_create_page(inode->i_mapping, pnum, gfp);
1171 if (page) {
1172 BUG_ON(page->mapping != inode->i_mapping);
1173 if (!PageUptodate(page)) {
1174 ret = ext4_mb_init_cache(page, NULL, gfp);
1175 if (ret) {
1176 unlock_page(page);
1177 goto err;
1178 }
1179 mb_cmp_bitmaps(e4b, page_address(page) +
1180 (poff * sb->s_blocksize));
1181 }
1182 unlock_page(page);
1183 }
1184 }
1185 if (page == NULL) {
1186 ret = -ENOMEM;
1187 goto err;
1188 }
1189 if (!PageUptodate(page)) {
1190 ret = -EIO;
1191 goto err;
1192 }
1193
1194 /* Pages marked accessed already */
1195 e4b->bd_bitmap_page = page;
1196 e4b->bd_bitmap = page_address(page) + (poff * sb->s_blocksize);
1197
1198 block++;
1199 pnum = block / blocks_per_page;
1200 poff = block % blocks_per_page;
1201
1202 page = find_get_page_flags(inode->i_mapping, pnum, FGP_ACCESSED);
1203 if (page == NULL || !PageUptodate(page)) {
1204 if (page)
1205 put_page(page);
1206 page = find_or_create_page(inode->i_mapping, pnum, gfp);
1207 if (page) {
1208 BUG_ON(page->mapping != inode->i_mapping);
1209 if (!PageUptodate(page)) {
1210 ret = ext4_mb_init_cache(page, e4b->bd_bitmap,
1211 gfp);
1212 if (ret) {
1213 unlock_page(page);
1214 goto err;
1215 }
1216 }
1217 unlock_page(page);
1218 }
1219 }
1220 if (page == NULL) {
1221 ret = -ENOMEM;
1222 goto err;
1223 }
1224 if (!PageUptodate(page)) {
1225 ret = -EIO;
1226 goto err;
1227 }
1228
1229 /* Pages marked accessed already */
1230 e4b->bd_buddy_page = page;
1231 e4b->bd_buddy = page_address(page) + (poff * sb->s_blocksize);
1232
1233 BUG_ON(e4b->bd_bitmap_page == NULL);
1234 BUG_ON(e4b->bd_buddy_page == NULL);
1235
1236 return 0;
1237
1238 err:
1239 if (page)
1240 put_page(page);
1241 if (e4b->bd_bitmap_page)
1242 put_page(e4b->bd_bitmap_page);
1243 if (e4b->bd_buddy_page)
1244 put_page(e4b->bd_buddy_page);
1245 e4b->bd_buddy = NULL;
1246 e4b->bd_bitmap = NULL;
1247 return ret;
1248 }
1249
1250 static 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
1256 static void ext4_mb_unload_buddy(struct ext4_buddy *e4b)
1257 {
1258 if (e4b->bd_bitmap_page)
1259 put_page(e4b->bd_bitmap_page);
1260 if (e4b->bd_buddy_page)
1261 put_page(e4b->bd_buddy_page);
1262 }
1263
1264
1265 static int mb_find_order_for_block(struct ext4_buddy *e4b, int block)
1266 {
1267 int order = 1;
1268 int bb_incr = 1 << (e4b->bd_blkbits - 1);
1269 void *bb;
1270
1271 BUG_ON(e4b->bd_bitmap == e4b->bd_buddy);
1272 BUG_ON(block >= (1 << (e4b->bd_blkbits + 3)));
1273
1274 bb = e4b->bd_buddy;
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 }
1281 bb += bb_incr;
1282 bb_incr >>= 1;
1283 order++;
1284 }
1285 return 0;
1286 }
1287
1288 static void mb_clear_bits(void *bm, int cur, int len)
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 }
1301 mb_clear_bit(cur, bm);
1302 cur++;
1303 }
1304 }
1305
1306 /* clear bits in given range
1307 * will return first found zero bit if any, -1 otherwise
1308 */
1309 static 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
1333 void ext4_set_bits(void *bm, int cur, int len)
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 }
1346 mb_set_bit(cur, bm);
1347 cur++;
1348 }
1349 }
1350
1351 /*
1352 * _________________________________________________________________ */
1353
1354 static 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
1368 static 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
1425 static void mb_free_blocks(struct inode *inode, struct ext4_buddy *e4b,
1426 int first, int count)
1427 {
1428 int left_is_free = 0;
1429 int right_is_free = 0;
1430 int block;
1431 int last = first + count - 1;
1432 struct super_block *sb = e4b->bd_sb;
1433
1434 if (WARN_ON(count == 0))
1435 return;
1436 BUG_ON(last >= (sb->s_blocksize << 3));
1437 assert_spin_locked(ext4_group_lock_ptr(sb, e4b->bd_group));
1438 /* Don't bother if the block group is corrupt. */
1439 if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(e4b->bd_info)))
1440 return;
1441
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
1449 /* access memory sequentially: check left neighbour,
1450 * clear range and then check right neighbour
1451 */
1452 if (first != 0)
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)) {
1459 struct ext4_sb_info *sbi = EXT4_SB(sb);
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 "
1468 "(bit %u); block bitmap corrupt.",
1469 block);
1470 if (!EXT4_MB_GRP_BBITMAP_CORRUPT(e4b->bd_info))
1471 percpu_counter_sub(&sbi->s_freeclusters_counter,
1472 e4b->bd_info->bb_free);
1473 /* Mark the block group as corrupt. */
1474 set_bit(EXT4_GROUP_INFO_BBITMAP_CORRUPT_BIT,
1475 &e4b->bd_info->bb_state);
1476 mb_regenerate_buddy(e4b);
1477 goto done;
1478 }
1479
1480 /* let's maintain fragments counter */
1481 if (left_is_free && right_is_free)
1482 e4b->bd_info->bb_fragments--;
1483 else if (!left_is_free && !right_is_free)
1484 e4b->bd_info->bb_fragments++;
1485
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 }
1500
1501 if (first <= last)
1502 mb_buddy_mark_free(e4b, first >> 1, last >> 1);
1503
1504 done:
1505 mb_set_largest_free_order(sb, e4b->bd_info);
1506 mb_check_buddy(e4b);
1507 }
1508
1509 static int mb_find_extent(struct ext4_buddy *e4b, int block,
1510 int needed, struct ext4_free_extent *ex)
1511 {
1512 int next = block;
1513 int max, order;
1514 void *buddy;
1515
1516 assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
1517 BUG_ON(ex == NULL);
1518
1519 buddy = mb_find_buddy(e4b, 0, &max);
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
1529 /* find actual order */
1530 order = mb_find_order_for_block(e4b, block);
1531 block = block >> order;
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 &&
1543 mb_find_buddy(e4b, order, &max)) {
1544
1545 if (block + 1 >= max)
1546 break;
1547
1548 next = (block + 1) * (1 << order);
1549 if (mb_test_bit(next, e4b->bd_bitmap))
1550 break;
1551
1552 order = mb_find_order_for_block(e4b, next);
1553
1554 block = next >> order;
1555 ex->fe_len += 1 << order;
1556 }
1557
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 }
1569 return ex->fe_len;
1570 }
1571
1572 static 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);
1586 assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
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)
1596 mlen = !mb_test_bit(start - 1, e4b->bd_bitmap);
1597 if (start + len < EXT4_SB(e4b->bd_sb)->s_mb_maxs[0])
1598 max = !mb_test_bit(start + len, e4b->bd_bitmap);
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 }
1639 mb_set_largest_free_order(e4b->bd_sb, e4b->bd_info);
1640
1641 ext4_set_bits(e4b->bd_bitmap, ex->fe_start, len0);
1642 mb_check_buddy(e4b);
1643
1644 return ret;
1645 }
1646
1647 /*
1648 * Must be called under group lock!
1649 */
1650 static 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
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 */
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);
1682 /* store last allocated for subsequent stream allocation */
1683 if (ac->ac_flags & EXT4_MB_STREAM_ALLOC) {
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
1695 static 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
1705 if (ac->ac_status == AC_STATUS_FOUND)
1706 return;
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) */
1727 max = mb_find_extent(e4b, bex->fe_start, gex->fe_len, &ex);
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 */
1745 static 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);
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));
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
1804 static noinline_for_stack
1805 int ext4_mb_try_best_found(struct ext4_allocation_context *ac,
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);
1819 max = mb_find_extent(e4b, ex.fe_start, ex.fe_len, &ex);
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);
1827 ext4_mb_unload_buddy(e4b);
1828
1829 return 0;
1830 }
1831
1832 static noinline_for_stack
1833 int ext4_mb_find_by_goal(struct ext4_allocation_context *ac,
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);
1840 struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
1841 struct ext4_free_extent ex;
1842
1843 if (!(ac->ac_flags & EXT4_MB_HINT_TRY_GOAL))
1844 return 0;
1845 if (grp->bb_free == 0)
1846 return 0;
1847
1848 err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
1849 if (err)
1850 return err;
1851
1852 if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(e4b->bd_info))) {
1853 ext4_mb_unload_buddy(e4b);
1854 return 0;
1855 }
1856
1857 ext4_lock_group(ac->ac_sb, group);
1858 max = mb_find_extent(e4b, ac->ac_g_ex.fe_start,
1859 ac->ac_g_ex.fe_len, &ex);
1860 ex.fe_logical = 0xDEADFA11; /* debug value */
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
1865 start = ext4_group_first_block_no(ac->ac_sb, e4b->bd_group) +
1866 ex.fe_start;
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);
1891 ext4_mb_unload_buddy(e4b);
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 */
1900 static noinline_for_stack
1901 void ext4_mb_simple_scan_group(struct ext4_allocation_context *ac,
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
1919 k = mb_find_next_zero_bit(buddy, max, 0);
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 */
1944 static noinline_for_stack
1945 void ext4_mb_complex_scan_group(struct ext4_allocation_context *ac,
1946 struct ext4_buddy *e4b)
1947 {
1948 struct super_block *sb = ac->ac_sb;
1949 void *bitmap = e4b->bd_bitmap;
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) {
1960 i = mb_find_next_zero_bit(bitmap,
1961 EXT4_CLUSTERS_PER_GROUP(sb), i);
1962 if (i >= EXT4_CLUSTERS_PER_GROUP(sb)) {
1963 /*
1964 * IF we have corrupt bitmap, we won't find any
1965 * free blocks even though group info says we
1966 * we have free blocks
1967 */
1968 ext4_grp_locked_error(sb, e4b->bd_group, 0, 0,
1969 "%d free clusters as per "
1970 "group info. But bitmap says 0",
1971 free);
1972 break;
1973 }
1974
1975 mb_find_extent(e4b, i, ac->ac_g_ex.fe_len, &ex);
1976 BUG_ON(ex.fe_len <= 0);
1977 if (free < ex.fe_len) {
1978 ext4_grp_locked_error(sb, e4b->bd_group, 0, 0,
1979 "%d free clusters as per "
1980 "group info. But got %d blocks",
1981 free, ex.fe_len);
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;
1988 }
1989 ex.fe_logical = 0xDEADC0DE; /* debug value */
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
2001 * we try to find stripe-aligned chunks for stripe-size-multiple requests
2002 */
2003 static noinline_for_stack
2004 void ext4_mb_scan_aligned(struct ext4_allocation_context *ac,
2005 struct ext4_buddy *e4b)
2006 {
2007 struct super_block *sb = ac->ac_sb;
2008 struct ext4_sb_info *sbi = EXT4_SB(sb);
2009 void *bitmap = e4b->bd_bitmap;
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 */
2019 first_group_block = ext4_group_first_block_no(sb, e4b->bd_group);
2020
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
2025 while (i < EXT4_CLUSTERS_PER_GROUP(sb)) {
2026 if (!mb_test_bit(i, bitmap)) {
2027 max = mb_find_extent(e4b, i, sbi->s_stripe, &ex);
2028 if (max >= sbi->s_stripe) {
2029 ac->ac_found++;
2030 ex.fe_logical = 0xDEADF00D; /* debug value */
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
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 */
2046 static int ext4_mb_good_group(struct ext4_allocation_context *ac,
2047 ext4_group_t group, int cr)
2048 {
2049 unsigned free, fragments;
2050 int flex_size = ext4_flex_bg_size(EXT4_SB(ac->ac_sb));
2051 struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
2052
2053 BUG_ON(cr < 0 || cr >= 4);
2054
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
2061 if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(grp)))
2062 return 0;
2063
2064 /* We only do this if the grp has never been initialized */
2065 if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
2066 int ret = ext4_mb_init_group(ac->ac_sb, group, GFP_NOFS);
2067 if (ret)
2068 return ret;
2069 }
2070
2071 fragments = grp->bb_fragments;
2072 if (fragments == 0)
2073 return 0;
2074
2075 switch (cr) {
2076 case 0:
2077 BUG_ON(ac->ac_2order == 0);
2078
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
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
2092 return 1;
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
2110 static noinline_for_stack int
2111 ext4_mb_regular_allocator(struct ext4_allocation_context *ac)
2112 {
2113 ext4_group_t ngroups, group, i;
2114 int cr;
2115 int err = 0, first_err = 0;
2116 struct ext4_sb_info *sbi;
2117 struct super_block *sb;
2118 struct ext4_buddy e4b;
2119
2120 sb = ac->ac_sb;
2121 sbi = EXT4_SB(sb);
2122 ngroups = ext4_get_groups_count(sb);
2123 /* non-extent files are limited to low blocks/groups */
2124 if (!(ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS)))
2125 ngroups = sbi->s_blockfile_groups;
2126
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
2147 * You can tune it via /sys/fs/ext4/<partition>/mb_order2_req
2148 * We also support searching for power-of-two requests only for
2149 * requests upto maximum buddy size we have constructed.
2150 */
2151 if (i >= sbi->s_mb_order2_reqs && i <= sb->s_blocksize_bits + 2) {
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)
2156 ac->ac_2order = array_index_nospec(i - 1,
2157 sb->s_blocksize_bits + 2);
2158 }
2159
2160 /* if stream allocation is enabled, use global goal */
2161 if (ac->ac_flags & EXT4_MB_STREAM_ALLOC) {
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 }
2168
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 */
2175 repeat:
2176 for (; cr < 4 && ac->ac_status == AC_STATUS_CONTINUE; cr++) {
2177 ac->ac_criteria = cr;
2178 /*
2179 * searching for the right group start
2180 * from the goal value specified
2181 */
2182 group = ac->ac_g_ex.fe_group;
2183
2184 for (i = 0; i < ngroups; group++, i++) {
2185 int ret = 0;
2186 cond_resched();
2187 /*
2188 * Artificially restricted ngroups for non-extent
2189 * files makes group > ngroups possible on first loop.
2190 */
2191 if (group >= ngroups)
2192 group = 0;
2193
2194 /* This now checks without needing the buddy page */
2195 ret = ext4_mb_good_group(ac, group, cr);
2196 if (ret <= 0) {
2197 if (!first_err)
2198 first_err = ret;
2199 continue;
2200 }
2201
2202 err = ext4_mb_load_buddy(sb, group, &e4b);
2203 if (err)
2204 goto out;
2205
2206 ext4_lock_group(sb, group);
2207
2208 /*
2209 * We need to check again after locking the
2210 * block group
2211 */
2212 ret = ext4_mb_good_group(ac, group, cr);
2213 if (ret <= 0) {
2214 ext4_unlock_group(sb, group);
2215 ext4_mb_unload_buddy(&e4b);
2216 if (!first_err)
2217 first_err = ret;
2218 continue;
2219 }
2220
2221 ac->ac_groups_scanned++;
2222 if (cr == 0)
2223 ext4_mb_simple_scan_group(ac, &e4b);
2224 else if (cr == 1 && sbi->s_stripe &&
2225 !(ac->ac_g_ex.fe_len % sbi->s_stripe))
2226 ext4_mb_scan_aligned(ac, &e4b);
2227 else
2228 ext4_mb_complex_scan_group(ac, &e4b);
2229
2230 ext4_unlock_group(sb, group);
2231 ext4_mb_unload_buddy(&e4b);
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 }
2263 out:
2264 if (!err && ac->ac_status != AC_STATUS_FOUND && first_err)
2265 err = first_err;
2266 return err;
2267 }
2268
2269 static void *ext4_mb_seq_groups_start(struct seq_file *seq, loff_t *pos)
2270 {
2271 struct super_block *sb = seq->private;
2272 ext4_group_t group;
2273
2274 if (*pos < 0 || *pos >= ext4_get_groups_count(sb))
2275 return NULL;
2276 group = *pos + 1;
2277 return (void *) ((unsigned long) group);
2278 }
2279
2280 static void *ext4_mb_seq_groups_next(struct seq_file *seq, void *v, loff_t *pos)
2281 {
2282 struct super_block *sb = seq->private;
2283 ext4_group_t group;
2284
2285 ++*pos;
2286 if (*pos < 0 || *pos >= ext4_get_groups_count(sb))
2287 return NULL;
2288 group = *pos + 1;
2289 return (void *) ((unsigned long) group);
2290 }
2291
2292 static int ext4_mb_seq_groups_show(struct seq_file *seq, void *v)
2293 {
2294 struct super_block *sb = seq->private;
2295 ext4_group_t group = (ext4_group_t) ((unsigned long) v);
2296 int i;
2297 int err, buddy_loaded = 0;
2298 struct ext4_buddy e4b;
2299 struct ext4_group_info *grinfo;
2300 unsigned char blocksize_bits = min_t(unsigned char,
2301 sb->s_blocksize_bits,
2302 EXT4_MAX_BLOCK_LOG_SIZE);
2303 struct sg {
2304 struct ext4_group_info info;
2305 ext4_grpblk_t counters[EXT4_MAX_BLOCK_LOG_SIZE + 2];
2306 } sg;
2307
2308 group--;
2309 if (group == 0)
2310 seq_puts(seq, "#group: free frags first ["
2311 " 2^0 2^1 2^2 2^3 2^4 2^5 2^6 "
2312 " 2^7 2^8 2^9 2^10 2^11 2^12 2^13 ]\n");
2313
2314 i = (blocksize_bits + 2) * sizeof(sg.info.bb_counters[0]) +
2315 sizeof(struct ext4_group_info);
2316
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;
2326 }
2327
2328 memcpy(&sg, ext4_get_group_info(sb, group), i);
2329
2330 if (buddy_loaded)
2331 ext4_mb_unload_buddy(&e4b);
2332
2333 seq_printf(seq, "#%-5u: %-5u %-5u %-5u [", group, sg.info.bb_free,
2334 sg.info.bb_fragments, sg.info.bb_first_free);
2335 for (i = 0; i <= 13; i++)
2336 seq_printf(seq, " %-5u", i <= blocksize_bits + 1 ?
2337 sg.info.bb_counters[i] : 0);
2338 seq_printf(seq, " ]\n");
2339
2340 return 0;
2341 }
2342
2343 static void ext4_mb_seq_groups_stop(struct seq_file *seq, void *v)
2344 {
2345 }
2346
2347 static const struct seq_operations ext4_mb_seq_groups_ops = {
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
2354 static int ext4_mb_seq_groups_open(struct inode *inode, struct file *file)
2355 {
2356 struct super_block *sb = PDE_DATA(inode);
2357 int rc;
2358
2359 rc = seq_open(file, &ext4_mb_seq_groups_ops);
2360 if (rc == 0) {
2361 struct seq_file *m = file->private_data;
2362 m->private = sb;
2363 }
2364 return rc;
2365
2366 }
2367
2368 const struct file_operations ext4_seq_mb_groups_fops = {
2369 .open = ext4_mb_seq_groups_open,
2370 .read = seq_read,
2371 .llseek = seq_lseek,
2372 .release = seq_release,
2373 };
2374
2375 static 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 }
2383
2384 /*
2385 * Allocate the top-level s_group_info array for the specified number
2386 * of groups
2387 */
2388 int 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);
2400 new_groupinfo = kvzalloc(size, GFP_KERNEL);
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));
2408 kvfree(sbi->s_group_info);
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
2417 /* Create and initialize ext4_group_info data for the given group. */
2418 int ext4_mb_add_groupinfo(struct super_block *sb, ext4_group_t group,
2419 struct ext4_group_desc *desc)
2420 {
2421 int i;
2422 int metalen = 0;
2423 struct ext4_sb_info *sbi = EXT4_SB(sb);
2424 struct ext4_group_info **meta_group_info;
2425 struct kmem_cache *cachep = get_groupinfo_cache(sb->s_blocksize_bits);
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);
2435 meta_group_info = kmalloc(metalen, GFP_NOFS);
2436 if (meta_group_info == NULL) {
2437 ext4_msg(sb, KERN_ERR, "can't allocate mem "
2438 "for a buddy group");
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
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
2449 meta_group_info[i] = kmem_cache_zalloc(cachep, GFP_NOFS);
2450 if (meta_group_info[i] == NULL) {
2451 ext4_msg(sb, KERN_ERR, "can't allocate buddy mem");
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 */
2461 if (ext4_has_group_desc_csum(sb) &&
2462 (desc->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))) {
2463 meta_group_info[i]->bb_free =
2464 ext4_free_clusters_after_init(sb, group, desc);
2465 } else {
2466 meta_group_info[i]->bb_free =
2467 ext4_free_group_clusters(sb, desc);
2468 }
2469
2470 INIT_LIST_HEAD(&meta_group_info[i]->bb_prealloc_list);
2471 init_rwsem(&meta_group_info[i]->alloc_sem);
2472 meta_group_info[i]->bb_free_root = RB_ROOT;
2473 meta_group_info[i]->bb_largest_free_order = -1; /* uninit */
2474
2475 #ifdef DOUBLE_CHECK
2476 {
2477 struct buffer_head *bh;
2478 meta_group_info[i]->bb_bitmap =
2479 kmalloc(sb->s_blocksize, GFP_NOFS);
2480 BUG_ON(meta_group_info[i]->bb_bitmap == NULL);
2481 bh = ext4_read_block_bitmap(sb, group);
2482 BUG_ON(IS_ERR_OR_NULL(bh));
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
2491 exit_group_info:
2492 /* If a meta_group_info table has been allocated, release it now */
2493 if (group % EXT4_DESC_PER_BLOCK(sb) == 0) {
2494 kfree(sbi->s_group_info[group >> EXT4_DESC_PER_BLOCK_BITS(sb)]);
2495 sbi->s_group_info[group >> EXT4_DESC_PER_BLOCK_BITS(sb)] = NULL;
2496 }
2497 exit_meta_group_info:
2498 return -ENOMEM;
2499 } /* ext4_mb_add_groupinfo */
2500
2501 static int ext4_mb_init_backend(struct super_block *sb)
2502 {
2503 ext4_group_t ngroups = ext4_get_groups_count(sb);
2504 ext4_group_t i;
2505 struct ext4_sb_info *sbi = EXT4_SB(sb);
2506 int err;
2507 struct ext4_group_desc *desc;
2508 struct kmem_cache *cachep;
2509
2510 err = ext4_mb_alloc_groupinfo(sb, ngroups);
2511 if (err)
2512 return err;
2513
2514 sbi->s_buddy_cache = new_inode(sb);
2515 if (sbi->s_buddy_cache == NULL) {
2516 ext4_msg(sb, KERN_ERR, "can't get new inode");
2517 goto err_freesgi;
2518 }
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;
2524 EXT4_I(sbi->s_buddy_cache)->i_disksize = 0;
2525 for (i = 0; i < ngroups; i++) {
2526 desc = ext4_get_group_desc(sb, i, NULL);
2527 if (desc == NULL) {
2528 ext4_msg(sb, KERN_ERR, "can't read descriptor %u", i);
2529 goto err_freebuddy;
2530 }
2531 if (ext4_mb_add_groupinfo(sb, i, desc) != 0)
2532 goto err_freebuddy;
2533 }
2534
2535 return 0;
2536
2537 err_freebuddy:
2538 cachep = get_groupinfo_cache(sb->s_blocksize_bits);
2539 while (i-- > 0)
2540 kmem_cache_free(cachep, ext4_get_group_info(sb, i));
2541 i = sbi->s_group_info_size;
2542 while (i-- > 0)
2543 kfree(sbi->s_group_info[i]);
2544 iput(sbi->s_buddy_cache);
2545 err_freesgi:
2546 kvfree(sbi->s_group_info);
2547 return -ENOMEM;
2548 }
2549
2550 static 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
2561 static 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
2588 ext4_groupinfo_caches[cache_index] = cachep;
2589
2590 mutex_unlock(&ext4_grpinfo_slab_create_mutex);
2591 if (!cachep) {
2592 printk(KERN_EMERG
2593 "EXT4-fs: no memory for groupinfo slab cache\n");
2594 return -ENOMEM;
2595 }
2596
2597 return 0;
2598 }
2599
2600 int ext4_mb_init(struct super_block *sb)
2601 {
2602 struct ext4_sb_info *sbi = EXT4_SB(sb);
2603 unsigned i, j;
2604 unsigned offset, offset_incr;
2605 unsigned max;
2606 int ret;
2607
2608 i = (sb->s_blocksize_bits + 2) * sizeof(*sbi->s_mb_offsets);
2609
2610 sbi->s_mb_offsets = kmalloc(i, GFP_KERNEL);
2611 if (sbi->s_mb_offsets == NULL) {
2612 ret = -ENOMEM;
2613 goto out;
2614 }
2615
2616 i = (sb->s_blocksize_bits + 2) * sizeof(*sbi->s_mb_maxs);
2617 sbi->s_mb_maxs = kmalloc(i, GFP_KERNEL);
2618 if (sbi->s_mb_maxs == NULL) {
2619 ret = -ENOMEM;
2620 goto out;
2621 }
2622
2623 ret = ext4_groupinfo_create_slab(sb->s_blocksize);
2624 if (ret < 0)
2625 goto out;
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;
2633 offset_incr = 1 << (sb->s_blocksize_bits - 1);
2634 max = sb->s_blocksize << 2;
2635 do {
2636 sbi->s_mb_offsets[i] = offset;
2637 sbi->s_mb_maxs[i] = max;
2638 offset += offset_incr;
2639 offset_incr = offset_incr >> 1;
2640 max = max >> 1;
2641 i++;
2642 } while (i <= sb->s_blocksize_bits + 1);
2643
2644 spin_lock_init(&sbi->s_md_lock);
2645 spin_lock_init(&sbi->s_bal_lock);
2646 sbi->s_mb_free_pending = 0;
2647 INIT_LIST_HEAD(&sbi->s_freed_data_list);
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;
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);
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 }
2680
2681 sbi->s_locality_groups = alloc_percpu(struct ext4_locality_group);
2682 if (sbi->s_locality_groups == NULL) {
2683 ret = -ENOMEM;
2684 goto out;
2685 }
2686 for_each_possible_cpu(i) {
2687 struct ext4_locality_group *lg;
2688 lg = per_cpu_ptr(sbi->s_locality_groups, i);
2689 mutex_init(&lg->lg_mutex);
2690 for (j = 0; j < PREALLOC_TB_SIZE; j++)
2691 INIT_LIST_HEAD(&lg->lg_prealloc_list[j]);
2692 spin_lock_init(&lg->lg_prealloc_lock);
2693 }
2694
2695 /* init file for buddy data */
2696 ret = ext4_mb_init_backend(sb);
2697 if (ret != 0)
2698 goto out_free_locality_groups;
2699
2700 return 0;
2701
2702 out_free_locality_groups:
2703 free_percpu(sbi->s_locality_groups);
2704 sbi->s_locality_groups = NULL;
2705 out:
2706 kfree(sbi->s_mb_offsets);
2707 sbi->s_mb_offsets = NULL;
2708 kfree(sbi->s_mb_maxs);
2709 sbi->s_mb_maxs = NULL;
2710 return ret;
2711 }
2712
2713 /* need to called with the ext4 group lock held */
2714 static 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++;
2724 kmem_cache_free(ext4_pspace_cachep, pa);
2725 }
2726 if (count)
2727 mb_debug(1, "mballoc: %u PAs left\n", count);
2728
2729 }
2730
2731 int ext4_mb_release(struct super_block *sb)
2732 {
2733 ext4_group_t ngroups = ext4_get_groups_count(sb);
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);
2738 struct kmem_cache *cachep = get_groupinfo_cache(sb->s_blocksize_bits);
2739
2740 if (sbi->s_group_info) {
2741 for (i = 0; i < ngroups; i++) {
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);
2749 kmem_cache_free(cachep, grinfo);
2750 }
2751 num_meta_group_infos = (ngroups +
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]);
2756 kvfree(sbi->s_group_info);
2757 }
2758 kfree(sbi->s_mb_offsets);
2759 kfree(sbi->s_mb_maxs);
2760 iput(sbi->s_buddy_cache);
2761 if (sbi->s_mb_stats) {
2762 ext4_msg(sb, KERN_INFO,
2763 "mballoc: %u blocks %u reqs (%u success)",
2764 atomic_read(&sbi->s_bal_allocated),
2765 atomic_read(&sbi->s_bal_reqs),
2766 atomic_read(&sbi->s_bal_success));
2767 ext4_msg(sb, KERN_INFO,
2768 "mballoc: %u extents scanned, %u goal hits, "
2769 "%u 2^N hits, %u breaks, %u lost",
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));
2775 ext4_msg(sb, KERN_INFO,
2776 "mballoc: %lu generated and it took %Lu",
2777 sbi->s_mb_buddies_generated,
2778 sbi->s_mb_generation_time);
2779 ext4_msg(sb, KERN_INFO,
2780 "mballoc: %u preallocated, %u discarded",
2781 atomic_read(&sbi->s_mb_preallocated),
2782 atomic_read(&sbi->s_mb_discarded));
2783 }
2784
2785 free_percpu(sbi->s_locality_groups);
2786
2787 return 0;
2788 }
2789
2790 static inline int ext4_issue_discard(struct super_block *sb,
2791 ext4_group_t block_group, ext4_grpblk_t cluster, int count,
2792 struct bio **biop)
2793 {
2794 ext4_fsblk_t discard_block;
2795
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);
2799 trace_ext4_discard_blocks(sb,
2800 (unsigned long long) discard_block, count);
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);
2808 }
2809
2810 static void ext4_free_data_in_buddy(struct super_block *sb,
2811 struct ext4_free_data *entry)
2812 {
2813 struct ext4_buddy e4b;
2814 struct ext4_group_info *db;
2815 int err, count = 0, count2 = 0;
2816
2817 mb_debug(1, "gonna free %u blocks in group %u (0x%p):",
2818 entry->efd_count, entry->efd_group, entry);
2819
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);
2823
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);
2827
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);
2836
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);
2845
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 */
2850 put_page(e4b.bd_buddy_page);
2851 put_page(e4b.bd_bitmap_page);
2852 }
2853 ext4_unlock_group(sb, entry->efd_group);
2854 kmem_cache_free(ext4_free_data_cachep, entry);
2855 ext4_mb_unload_buddy(&e4b);
2856
2857 mb_debug(1, "freed %u blocks in %u structures\n", count, count2);
2858 }
2859
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 */
2864 void 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
2902 if (discard_bio) {
2903 submit_bio_wait(discard_bio);
2904 bio_put(discard_bio);
2905 }
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
2912 int __init ext4_init_mballoc(void)
2913 {
2914 ext4_pspace_cachep = KMEM_CACHE(ext4_prealloc_space,
2915 SLAB_RECLAIM_ACCOUNT);
2916 if (ext4_pspace_cachep == NULL)
2917 return -ENOMEM;
2918
2919 ext4_ac_cachep = KMEM_CACHE(ext4_allocation_context,
2920 SLAB_RECLAIM_ACCOUNT);
2921 if (ext4_ac_cachep == NULL) {
2922 kmem_cache_destroy(ext4_pspace_cachep);
2923 return -ENOMEM;
2924 }
2925
2926 ext4_free_data_cachep = KMEM_CACHE(ext4_free_data,
2927 SLAB_RECLAIM_ACCOUNT);
2928 if (ext4_free_data_cachep == NULL) {
2929 kmem_cache_destroy(ext4_pspace_cachep);
2930 kmem_cache_destroy(ext4_ac_cachep);
2931 return -ENOMEM;
2932 }
2933 return 0;
2934 }
2935
2936 void ext4_exit_mballoc(void)
2937 {
2938 /*
2939 * Wait for completion of call_rcu()'s on ext4_pspace_cachep
2940 * before destroying the slab cache.
2941 */
2942 rcu_barrier();
2943 kmem_cache_destroy(ext4_pspace_cachep);
2944 kmem_cache_destroy(ext4_ac_cachep);
2945 kmem_cache_destroy(ext4_free_data_cachep);
2946 ext4_groupinfo_destroy_slabs();
2947 }
2948
2949
2950 /*
2951 * Check quota and mark chosen space (ac->ac_b_ex) non-free in bitmaps
2952 * Returns 0 if success or error code
2953 */
2954 static noinline_for_stack int
2955 ext4_mb_mark_diskspace_used(struct ext4_allocation_context *ac,
2956 handle_t *handle, unsigned int reserv_clstrs)
2957 {
2958 struct buffer_head *bitmap_bh = NULL;
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;
2964 int err, len;
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);
2971
2972 bitmap_bh = ext4_read_block_bitmap(sb, ac->ac_b_ex.fe_group);
2973 if (IS_ERR(bitmap_bh)) {
2974 err = PTR_ERR(bitmap_bh);
2975 bitmap_bh = NULL;
2976 goto out_err;
2977 }
2978
2979 BUFFER_TRACE(bitmap_bh, "getting write access");
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
2989 ext4_debug("using block group %u(%d)\n", ac->ac_b_ex.fe_group,
2990 ext4_free_group_clusters(sb, gdp));
2991
2992 BUFFER_TRACE(gdp_bh, "get_write_access");
2993 err = ext4_journal_get_write_access(handle, gdp_bh);
2994 if (err)
2995 goto out_err;
2996
2997 block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
2998
2999 len = EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
3000 if (!ext4_data_block_valid(sbi, block, len)) {
3001 ext4_error(sb, "Allocating blocks %llu-%llu which overlap "
3002 "fs metadata", block, block+len);
3003 /* File system mounted not to panic on error
3004 * Fix the bitmap and return EFSCORRUPTED
3005 * We leak some of the blocks here.
3006 */
3007 ext4_lock_group(sb, ac->ac_b_ex.fe_group);
3008 ext4_set_bits(bitmap_bh->b_data, ac->ac_b_ex.fe_start,
3009 ac->ac_b_ex.fe_len);
3010 ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3011 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
3012 if (!err)
3013 err = -EFSCORRUPTED;
3014 goto out_err;
3015 }
3016
3017 ext4_lock_group(sb, ac->ac_b_ex.fe_group);
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
3027 ext4_set_bits(bitmap_bh->b_data, ac->ac_b_ex.fe_start,
3028 ac->ac_b_ex.fe_len);
3029 if (ext4_has_group_desc_csum(sb) &&
3030 (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))) {
3031 gdp->bg_flags &= cpu_to_le16(~EXT4_BG_BLOCK_UNINIT);
3032 ext4_free_group_clusters_set(sb, gdp,
3033 ext4_free_clusters_after_init(sb,
3034 ac->ac_b_ex.fe_group, gdp));
3035 }
3036 len = ext4_free_group_clusters(sb, gdp) - ac->ac_b_ex.fe_len;
3037 ext4_free_group_clusters_set(sb, gdp, len);
3038 ext4_block_bitmap_csum_set(sb, ac->ac_b_ex.fe_group, gdp, bitmap_bh);
3039 ext4_group_desc_csum_set(sb, ac->ac_b_ex.fe_group, gdp);
3040
3041 ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3042 percpu_counter_sub(&sbi->s_freeclusters_counter, ac->ac_b_ex.fe_len);
3043 /*
3044 * Now reduce the dirty block count also. Should not go negative
3045 */
3046 if (!(ac->ac_flags & EXT4_MB_DELALLOC_RESERVED))
3047 /* release all the reserved blocks if non delalloc */
3048 percpu_counter_sub(&sbi->s_dirtyclusters_counter,
3049 reserv_clstrs);
3050
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);
3054 atomic64_sub(ac->ac_b_ex.fe_len,
3055 &sbi->s_flex_groups[flex_group].free_clusters);
3056 }
3057
3058 err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
3059 if (err)
3060 goto out_err;
3061 err = ext4_handle_dirty_metadata(handle, NULL, gdp_bh);
3062
3063 out_err:
3064 brelse(bitmap_bh);
3065 return err;
3066 }
3067
3068 /*
3069 * here we normalize request for locality group
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
3073 * /sys/fs/ext4/<partition>/mb_group_prealloc
3074 *
3075 * XXX: should we try to preallocate more than the group has now?
3076 */
3077 static 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);
3083 ac->ac_g_ex.fe_len = EXT4_SB(sb)->s_mb_group_prealloc;
3084 mb_debug(1, "#%u: goal %u blocks for locality group\n",
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 */
3092 static noinline_for_stack void
3093 ext4_mb_normalize_request(struct ext4_allocation_context *ac,
3094 struct ext4_allocation_request *ar)
3095 {
3096 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3097 int bsbits, max;
3098 ext4_lblk_t end;
3099 loff_t size, start_off;
3100 loff_t orig_size __maybe_unused;
3101 ext4_lblk_t start;
3102 struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
3103 struct ext4_prealloc_space *pa;
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 */
3128 size = ac->ac_o_ex.fe_logical + EXT4_C2B(sbi, ac->ac_o_ex.fe_len);
3129 size = size << bsbits;
3130 if (size < i_size_read(ac->ac_inode))
3131 size = i_size_read(ac->ac_inode);
3132 orig_size = size;
3133
3134 /* max size of free chunks */
3135 max = 2 << bsbits;
3136
3137 #define NRL_CHECK_SIZE(req, size, max, chunk_size) \
3138 (req <= (size) || max <= (chunk_size))
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;
3157 } else if (NRL_CHECK_SIZE(size, 4 * 1024 * 1024, max, 2 * 1024)) {
3158 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
3159 (21 - bsbits)) << 21;
3160 size = 2 * 1024 * 1024;
3161 } else if (NRL_CHECK_SIZE(size, 8 * 1024 * 1024, max, 4 * 1024)) {
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,
3166 (8<<20)>>bsbits, max, 8 * 1024)) {
3167 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
3168 (23 - bsbits)) << 23;
3169 size = 8 * 1024 * 1024;
3170 } else {
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;
3174 }
3175 size = size >> bsbits;
3176 start = start_off >> bsbits;
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
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
3193 end = start + size;
3194
3195 /* check we don't cross already preallocated blocks */
3196 rcu_read_lock();
3197 list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3198 ext4_lblk_t pa_end;
3199
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
3208 pa_end = pa->pa_lstart + EXT4_C2B(EXT4_SB(ac->ac_sb),
3209 pa->pa_len);
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
3215 /* skip PAs this normalized request doesn't overlap with */
3216 if (pa->pa_lstart >= end || pa_end <= start) {
3217 spin_unlock(&pa->pa_lock);
3218 continue;
3219 }
3220 BUG_ON(pa->pa_lstart <= start && pa_end >= end);
3221
3222 /* adjust start or end to be adjacent to this pa */
3223 if (pa_end <= ac->ac_o_ex.fe_logical) {
3224 BUG_ON(pa_end < start);
3225 start = pa_end;
3226 } else if (pa->pa_lstart > ac->ac_o_ex.fe_logical) {
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();
3237 list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3238 ext4_lblk_t pa_end;
3239
3240 spin_lock(&pa->pa_lock);
3241 if (pa->pa_deleted == 0) {
3242 pa_end = pa->pa_lstart + EXT4_C2B(EXT4_SB(ac->ac_sb),
3243 pa->pa_len);
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) {
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);
3256 BUG();
3257 }
3258 BUG_ON(size <= 0 || size > EXT4_BLOCKS_PER_GROUP(ac->ac_sb));
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;
3265 ac->ac_g_ex.fe_len = EXT4_NUM_B2C(sbi, size);
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
3283 mb_debug(1, "goal: %u(was %u) blocks at %u\n", (unsigned) size,
3284 (unsigned) orig_size, (unsigned) start);
3285 }
3286
3287 static 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);
3294 if (ac->ac_b_ex.fe_len >= ac->ac_o_ex.fe_len)
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
3304 if (ac->ac_op == EXT4_MB_HISTORY_ALLOC)
3305 trace_ext4_mballoc_alloc(ac);
3306 else
3307 trace_ext4_mballoc_prealloc(ac);
3308 }
3309
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 */
3316 static void ext4_discard_allocated_blocks(struct ext4_allocation_context *ac)
3317 {
3318 struct ext4_prealloc_space *pa = ac->ac_pa;
3319 struct ext4_buddy e4b;
3320 int err;
3321
3322 if (pa == NULL) {
3323 if (ac->ac_f_ex.fe_len == 0)
3324 return;
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);
3339 ext4_mb_unload_buddy(&e4b);
3340 return;
3341 }
3342 if (pa->pa_type == MB_INODE_PA)
3343 pa->pa_free += ac->ac_b_ex.fe_len;
3344 }
3345
3346 /*
3347 * use blocks preallocated to inode
3348 */
3349 static void ext4_mb_use_inode_pa(struct ext4_allocation_context *ac,
3350 struct ext4_prealloc_space *pa)
3351 {
3352 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
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);
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);
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);
3369 BUG_ON(end > pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len));
3370 BUG_ON(pa->pa_free < len);
3371 pa->pa_free -= len;
3372
3373 mb_debug(1, "use %llu/%u from inode pa %p\n", start, len, pa);
3374 }
3375
3376 /*
3377 * use blocks preallocated to locality group
3378 */
3379 static void ext4_mb_use_group_pa(struct ext4_allocation_context *ac,
3380 struct ext4_prealloc_space *pa)
3381 {
3382 unsigned int len = ac->ac_o_ex.fe_len;
3383
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
3392 * possible race when the group is being loaded concurrently
3393 * instead we correct pa later, after blocks are marked
3394 * in on-disk bitmap -- see ext4_mb_release_context()
3395 * Other CPUs are prevented from allocating from this pa by lg_mutex
3396 */
3397 mb_debug(1, "use %u/%u from group pa %p\n", pa->pa_lstart-len, len, pa);
3398 }
3399
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 */
3406 static struct ext4_prealloc_space *
3407 ext4_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 }
3417 cur_distance = abs(goal_block - cpa->pa_pstart);
3418 new_distance = abs(goal_block - pa->pa_pstart);
3419
3420 if (cur_distance <= new_distance)
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
3429 /*
3430 * search goal blocks in preallocated space
3431 */
3432 static noinline_for_stack int
3433 ext4_mb_use_preallocated(struct ext4_allocation_context *ac)
3434 {
3435 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3436 int order, i;
3437 struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
3438 struct ext4_locality_group *lg;
3439 struct ext4_prealloc_space *pa, *cpa = NULL;
3440 ext4_fsblk_t goal_block;
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();
3448 list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
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 ||
3453 ac->ac_o_ex.fe_logical >= (pa->pa_lstart +
3454 EXT4_C2B(sbi, pa->pa_len)))
3455 continue;
3456
3457 /* non-extent files can't have physical blocks past 2^32 */
3458 if (!(ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS)) &&
3459 (pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len) >
3460 EXT4_MAX_BLOCK_FILE_PHYS))
3461 continue;
3462
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;
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
3490 goal_block = ext4_grp_offs_to_block(ac->ac_sb, &ac->ac_g_ex);
3491 /*
3492 * search for the prealloc space that is having
3493 * minimal distance from the goal block.
3494 */
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) {
3502
3503 cpa = ext4_mb_check_group_pa(goal_block,
3504 pa, cpa);
3505 }
3506 spin_unlock(&pa->pa_lock);
3507 }
3508 rcu_read_unlock();
3509 }
3510 if (cpa) {
3511 ext4_mb_use_group_pa(ac, cpa);
3512 ac->ac_criteria = 20;
3513 return 1;
3514 }
3515 return 0;
3516 }
3517
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
3522 * Need to be called with the ext4 group lock held
3523 */
3524 static 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) {
3535 entry = rb_entry(n, struct ext4_free_data, efd_node);
3536 ext4_set_bits(bitmap, entry->efd_start_cluster, entry->efd_count);
3537 n = rb_next(n);
3538 }
3539 return;
3540 }
3541
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
3545 * Need to be called with ext4 group lock held
3546 */
3547 static noinline_for_stack
3548 void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
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;
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);
3577 ext4_set_bits(bitmap, start, len);
3578 preallocated += len;
3579 }
3580 mb_debug(1, "preallocated %u for group %u\n", preallocated, group);
3581 }
3582
3583 static 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);
3587
3588 BUG_ON(atomic_read(&pa->pa_count));
3589 BUG_ON(pa->pa_deleted == 0);
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 */
3597 static void ext4_mb_put_pa(struct ext4_allocation_context *ac,
3598 struct super_block *sb, struct ext4_prealloc_space *pa)
3599 {
3600 ext4_group_t grp;
3601 ext4_fsblk_t grp_blk;
3602
3603 /* in this short window concurrent discard can set pa_deleted */
3604 spin_lock(&pa->pa_lock);
3605 if (!atomic_dec_and_test(&pa->pa_count) || pa->pa_free != 0) {
3606 spin_unlock(&pa->pa_lock);
3607 return;
3608 }
3609
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
3618 grp_blk = pa->pa_pstart;
3619 /*
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)
3624 grp_blk--;
3625
3626 grp = ext4_get_group_number(sb, grp_blk);
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 */
3656 static noinline_for_stack int
3657 ext4_mb_new_inode_pa(struct ext4_allocation_context *ac)
3658 {
3659 struct super_block *sb = ac->ac_sb;
3660 struct ext4_sb_info *sbi = EXT4_SB(sb);
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 */
3692 wins = EXT4_C2B(sbi, ac->ac_b_ex.fe_len - ac->ac_o_ex.fe_len);
3693
3694 /* the smallest one defines real window */
3695 win = min(winl, wins);
3696
3697 offs = ac->ac_o_ex.fe_logical %
3698 EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
3699 if (offs && offs < win)
3700 win = offs;
3701
3702 ac->ac_b_ex.fe_logical = ac->ac_o_ex.fe_logical -
3703 EXT4_NUM_B2C(sbi, win);
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);
3718 INIT_LIST_HEAD(&pa->pa_inode_list);
3719 INIT_LIST_HEAD(&pa->pa_group_list);
3720 pa->pa_deleted = 0;
3721 pa->pa_type = MB_INODE_PA;
3722
3723 mb_debug(1, "new inode pa %p: %llu/%u for %u\n", pa,
3724 pa->pa_pstart, pa->pa_len, pa->pa_lstart);
3725 trace_ext4_mb_new_inode_pa(ac, pa);
3726
3727 ext4_mb_use_inode_pa(ac, pa);
3728 atomic_add(pa->pa_free, &sbi->s_mb_preallocated);
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 */
3750 static noinline_for_stack int
3751 ext4_mb_new_group_pa(struct ext4_allocation_context *ac)
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);
3778 INIT_LIST_HEAD(&pa->pa_inode_list);
3779 INIT_LIST_HEAD(&pa->pa_group_list);
3780 pa->pa_deleted = 0;
3781 pa->pa_type = MB_GROUP_PA;
3782
3783 mb_debug(1, "new group pa %p: %llu/%u for %u\n", pa,
3784 pa->pa_pstart, pa->pa_len, pa->pa_lstart);
3785 trace_ext4_mb_new_group_pa(ac, pa);
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
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 */
3805 return 0;
3806 }
3807
3808 static 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 */
3827 static noinline_for_stack int
3828 ext4_mb_release_inode_pa(struct ext4_buddy *e4b, struct buffer_head *bitmap_bh,
3829 struct ext4_prealloc_space *pa)
3830 {
3831 struct super_block *sb = e4b->bd_sb;
3832 struct ext4_sb_info *sbi = EXT4_SB(sb);
3833 unsigned int end;
3834 unsigned int next;
3835 ext4_group_t group;
3836 ext4_grpblk_t bit;
3837 unsigned long long grp_blk_start;
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);
3843 grp_blk_start = pa->pa_pstart - EXT4_C2B(sbi, bit);
3844 BUG_ON(group != e4b->bd_group && pa->pa_len != 0);
3845 end = bit + pa->pa_len;
3846
3847 while (bit < end) {
3848 bit = mb_find_next_zero_bit(bitmap_bh->b_data, end, bit);
3849 if (bit >= end)
3850 break;
3851 next = mb_find_next_bit(bitmap_bh->b_data, end, bit);
3852 mb_debug(1, " free preallocated %u/%u in group %u\n",
3853 (unsigned) ext4_group_first_block_no(sb, group) + bit,
3854 (unsigned) next - bit, (unsigned) group);
3855 free += next - bit;
3856
3857 trace_ext4_mballoc_discard(sb, NULL, group, bit, next - bit);
3858 trace_ext4_mb_release_inode_pa(pa, (grp_blk_start +
3859 EXT4_C2B(sbi, bit)),
3860 next - bit);
3861 mb_free_blocks(pa->pa_inode, e4b, bit, next - bit);
3862 bit = next + 1;
3863 }
3864 if (free != pa->pa_free) {
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);
3870 ext4_grp_locked_error(sb, group, 0, 0, "free %u, pa_free %u",
3871 free, pa->pa_free);
3872 /*
3873 * pa is already deleted so we use the value obtained
3874 * from the bitmap and continue.
3875 */
3876 }
3877 atomic_add(free, &sbi->s_mb_discarded);
3878
3879 return err;
3880 }
3881
3882 static noinline_for_stack int
3883 ext4_mb_release_group_pa(struct ext4_buddy *e4b,
3884 struct ext4_prealloc_space *pa)
3885 {
3886 struct super_block *sb = e4b->bd_sb;
3887 ext4_group_t group;
3888 ext4_grpblk_t bit;
3889
3890 trace_ext4_mb_release_group_pa(sb, pa);
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);
3896 trace_ext4_mballoc_discard(sb, NULL, group, bit, pa->pa_len);
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 */
3910 static noinline_for_stack int
3911 ext4_mb_discard_group_preallocations(struct super_block *sb,
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
3923 mb_debug(1, "discard preallocation for group %u\n", group);
3924
3925 if (list_empty(&grp->bb_prealloc_list))
3926 return 0;
3927
3928 bitmap_bh = ext4_read_block_bitmap(sb, group);
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);
3933 return 0;
3934 }
3935
3936 err = ext4_mb_load_buddy(sb, group, &e4b);
3937 if (err) {
3938 ext4_warning(sb, "Error %d loading buddy information for %u",
3939 err, group);
3940 put_bh(bitmap_bh);
3941 return 0;
3942 }
3943
3944 if (needed == 0)
3945 needed = EXT4_CLUSTERS_PER_GROUP(sb) + 1;
3946
3947 INIT_LIST_HEAD(&list);
3948 repeat:
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);
3979 cond_resched();
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
3997 if (pa->pa_type == MB_GROUP_PA)
3998 ext4_mb_release_group_pa(&e4b, pa);
3999 else
4000 ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa);
4001
4002 list_del(&pa->u.pa_tmp_list);
4003 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
4004 }
4005
4006 out:
4007 ext4_unlock_group(sb, group);
4008 ext4_mb_unload_buddy(&e4b);
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 */
4022 void ext4_discard_preallocations(struct inode *inode)
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
4033 if (!S_ISREG(inode->i_mode)) {
4034 /*BUG_ON(!list_empty(&ei->i_prealloc_list));*/
4035 return;
4036 }
4037
4038 mb_debug(1, "discard preallocation for inode %lu\n", inode->i_ino);
4039 trace_ext4_discard_preallocations(inode);
4040
4041 INIT_LIST_HEAD(&list);
4042
4043 repeat:
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);
4056 ext4_msg(sb, KERN_ERR,
4057 "uh-oh! used pa while discarding");
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) {
4093 BUG_ON(pa->pa_type != MB_INODE_PA);
4094 group = ext4_get_group_number(sb, pa->pa_pstart);
4095
4096 err = ext4_mb_load_buddy_gfp(sb, group, &e4b,
4097 GFP_NOFS|__GFP_NOFAIL);
4098 if (err) {
4099 ext4_error(sb, "Error %d loading buddy information for %u",
4100 err, group);
4101 continue;
4102 }
4103
4104 bitmap_bh = ext4_read_block_bitmap(sb, group);
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);
4109 ext4_mb_unload_buddy(&e4b);
4110 continue;
4111 }
4112
4113 ext4_lock_group(sb, group);
4114 list_del(&pa->pa_group_list);
4115 ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa);
4116 ext4_unlock_group(sb, group);
4117
4118 ext4_mb_unload_buddy(&e4b);
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
4126 #ifdef CONFIG_EXT4_DEBUG
4127 static void ext4_mb_show_ac(struct ext4_allocation_context *ac)
4128 {
4129 struct super_block *sb = ac->ac_sb;
4130 ext4_group_t ngroups, i;
4131
4132 if (!ext4_mballoc_debug ||
4133 (EXT4_SB(sb)->s_mount_flags & EXT4_MF_FS_ABORTED))
4134 return;
4135
4136 ext4_msg(ac->ac_sb, KERN_ERR, "Can't allocate:"
4137 " Allocation context details:");
4138 ext4_msg(ac->ac_sb, KERN_ERR, "status %d flags %d",
4139 ac->ac_status, ac->ac_flags);
4140 ext4_msg(ac->ac_sb, KERN_ERR, "orig %lu/%lu/%lu@%lu, "
4141 "goal %lu/%lu/%lu@%lu, "
4142 "best %lu/%lu/%lu@%lu cr %d",
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);
4156 ext4_msg(ac->ac_sb, KERN_ERR, "%d found", ac->ac_found);
4157 ext4_msg(ac->ac_sb, KERN_ERR, "groups: ");
4158 ngroups = ext4_get_groups_count(sb);
4159 for (i = 0; i < ngroups; i++) {
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);
4172 printk(KERN_ERR "PA:%u:%d:%u \n", i,
4173 start, pa->pa_len);
4174 }
4175 ext4_unlock_group(sb, i);
4176
4177 if (grp->bb_free == 0)
4178 continue;
4179 printk(KERN_ERR "%u: %d/%d \n",
4180 i, grp->bb_free, grp->bb_fragments);
4181 }
4182 printk(KERN_ERR "\n");
4183 }
4184 #else
4185 static 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 *
4196 * One can tune this size via /sys/fs/ext4/<partition>/mb_stream_req
4197 */
4198 static 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
4207 if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
4208 return;
4209
4210 size = ac->ac_o_ex.fe_logical + EXT4_C2B(sbi, ac->ac_o_ex.fe_len);
4211 isize = (i_size_read(ac->ac_inode) + ac->ac_sb->s_blocksize - 1)
4212 >> bsbits;
4213
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
4221 if (sbi->s_mb_group_prealloc <= 0) {
4222 ac->ac_flags |= EXT4_MB_STREAM_ALLOC;
4223 return;
4224 }
4225
4226 /* don't use group allocation for large files */
4227 size = max(size, isize);
4228 if (size > sbi->s_mb_stream_request) {
4229 ac->ac_flags |= EXT4_MB_STREAM_ALLOC;
4230 return;
4231 }
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 */
4239 ac->ac_lg = raw_cpu_ptr(sbi->s_locality_groups);
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
4248 static noinline_for_stack int
4249 ext4_mb_initialize_context(struct ext4_allocation_context *ac,
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;
4256 unsigned int len;
4257 ext4_fsblk_t goal;
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 */
4264 if (len >= EXT4_CLUSTERS_PER_GROUP(sb))
4265 len = EXT4_CLUSTERS_PER_GROUP(sb);
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 */
4275 ac->ac_b_ex.fe_logical = EXT4_LBLK_CMASK(sbi, ar->logical);
4276 ac->ac_status = AC_STATUS_CONTINUE;
4277 ac->ac_sb = sb;
4278 ac->ac_inode = ar->inode;
4279 ac->ac_o_ex.fe_logical = ac->ac_b_ex.fe_logical;
4280 ac->ac_o_ex.fe_group = group;
4281 ac->ac_o_ex.fe_start = block;
4282 ac->ac_o_ex.fe_len = len;
4283 ac->ac_g_ex = ac->ac_o_ex;
4284 ac->ac_flags = ar->flags;
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
4290 mb_debug(1, "init ac: %u blocks @ %u, goal %u, flags %x, 2^%d, "
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
4301 static noinline_for_stack void
4302 ext4_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;
4310
4311 mb_debug(1, "discard locality group preallocation\n");
4312
4313 INIT_LIST_HEAD(&discard_list);
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 */
4333 BUG_ON(pa->pa_type != MB_GROUP_PA);
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) {
4356 int err;
4357
4358 group = ext4_get_group_number(sb, pa->pa_pstart);
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);
4364 continue;
4365 }
4366 ext4_lock_group(sb, group);
4367 list_del(&pa->pa_group_list);
4368 ext4_mb_release_group_pa(&e4b, pa);
4369 ext4_unlock_group(sb, group);
4370
4371 ext4_mb_unload_buddy(&e4b);
4372 list_del(&pa->u.pa_tmp_list);
4373 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
4374 }
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
4386 static 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 */
4398 spin_lock(&lg->lg_prealloc_lock);
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) {
4403 spin_unlock(&tmp_pa->pa_lock);
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]);
4422 spin_unlock(&lg->lg_prealloc_lock);
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,
4427 order, lg_prealloc_count);
4428 return;
4429 }
4430 return ;
4431 }
4432
4433 /*
4434 * release all resource we used in allocation
4435 */
4436 static int ext4_mb_release_context(struct ext4_allocation_context *ac)
4437 {
4438 struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
4439 struct ext4_prealloc_space *pa = ac->ac_pa;
4440 if (pa) {
4441 if (pa->pa_type == MB_GROUP_PA) {
4442 /* see comment in ext4_mb_use_group_pa() */
4443 spin_lock(&pa->pa_lock);
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);
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);
4449 }
4450 }
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
4456 * doesn't grow big.
4457 */
4458 if ((pa->pa_type == MB_GROUP_PA) && likely(pa->pa_free)) {
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 }
4466 if (ac->ac_bitmap_page)
4467 put_page(ac->ac_bitmap_page);
4468 if (ac->ac_buddy_page)
4469 put_page(ac->ac_buddy_page);
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
4476 static int ext4_mb_discard_preallocations(struct super_block *sb, int needed)
4477 {
4478 ext4_group_t i, ngroups = ext4_get_groups_count(sb);
4479 int ret;
4480 int freed = 0;
4481
4482 trace_ext4_mb_discard_preallocations(sb, needed);
4483 for (i = 0; i < ngroups && needed > 0; i++) {
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 */
4497 ext4_fsblk_t ext4_mb_new_blocks(handle_t *handle,
4498 struct ext4_allocation_request *ar, int *errp)
4499 {
4500 int freed;
4501 struct ext4_allocation_context *ac = NULL;
4502 struct ext4_sb_info *sbi;
4503 struct super_block *sb;
4504 ext4_fsblk_t block = 0;
4505 unsigned int inquota = 0;
4506 unsigned int reserv_clstrs = 0;
4507
4508 might_sleep();
4509 sb = ar->inode->i_sb;
4510 sbi = EXT4_SB(sb);
4511
4512 trace_ext4_request_blocks(ar);
4513
4514 /* Allow to use superuser reservation for quota file */
4515 if (ext4_is_quota_file(ar->inode))
4516 ar->flags |= EXT4_MB_USE_ROOT_BLOCKS;
4517
4518 if ((ar->flags & EXT4_MB_DELALLOC_RESERVED) == 0) {
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.
4522 */
4523 while (ar->len &&
4524 ext4_claim_free_clusters(sbi, ar->len, ar->flags)) {
4525
4526 /* let others to free the space */
4527 cond_resched();
4528 ar->len = ar->len >> 1;
4529 }
4530 if (!ar->len) {
4531 *errp = -ENOSPC;
4532 return 0;
4533 }
4534 reserv_clstrs = ar->len;
4535 if (ar->flags & EXT4_MB_USE_ROOT_BLOCKS) {
4536 dquot_alloc_block_nofail(ar->inode,
4537 EXT4_C2B(sbi, ar->len));
4538 } else {
4539 while (ar->len &&
4540 dquot_alloc_block(ar->inode,
4541 EXT4_C2B(sbi, ar->len))) {
4542
4543 ar->flags |= EXT4_MB_HINT_NOPREALLOC;
4544 ar->len--;
4545 }
4546 }
4547 inquota = ar->len;
4548 if (ar->len == 0) {
4549 *errp = -EDQUOT;
4550 goto out;
4551 }
4552 }
4553
4554 ac = kmem_cache_zalloc(ext4_ac_cachep, GFP_NOFS);
4555 if (!ac) {
4556 ar->len = 0;
4557 *errp = -ENOMEM;
4558 goto out;
4559 }
4560
4561 *errp = ext4_mb_initialize_context(ac, ar);
4562 if (*errp) {
4563 ar->len = 0;
4564 goto out;
4565 }
4566
4567 ac->ac_op = EXT4_MB_HISTORY_PREALLOC;
4568 if (!ext4_mb_use_preallocated(ac)) {
4569 ac->ac_op = EXT4_MB_HISTORY_ALLOC;
4570 ext4_mb_normalize_request(ac, ar);
4571 repeat:
4572 /* allocate space in core */
4573 *errp = ext4_mb_regular_allocator(ac);
4574 if (*errp)
4575 goto discard_and_exit;
4576
4577 /* as we've just preallocated more space than
4578 * user requested originally, we store allocated
4579 * space in a special descriptor */
4580 if (ac->ac_status == AC_STATUS_FOUND &&
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 }
4588 }
4589 if (likely(ac->ac_status == AC_STATUS_FOUND)) {
4590 *errp = ext4_mb_mark_diskspace_used(ac, handle, reserv_clstrs);
4591 if (*errp) {
4592 ext4_discard_allocated_blocks(ac);
4593 goto errout;
4594 } else {
4595 block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
4596 ar->len = ac->ac_b_ex.fe_len;
4597 }
4598 } else {
4599 freed = ext4_mb_discard_preallocations(sb, ac->ac_o_ex.fe_len);
4600 if (freed)
4601 goto repeat;
4602 *errp = -ENOSPC;
4603 }
4604
4605 errout:
4606 if (*errp) {
4607 ac->ac_b_ex.fe_len = 0;
4608 ar->len = 0;
4609 ext4_mb_show_ac(ac);
4610 }
4611 ext4_mb_release_context(ac);
4612 out:
4613 if (ac)
4614 kmem_cache_free(ext4_ac_cachep, ac);
4615 if (inquota && ar->len < inquota)
4616 dquot_free_block(ar->inode, EXT4_C2B(sbi, inquota - ar->len));
4617 if (!ar->len) {
4618 if ((ar->flags & EXT4_MB_DELALLOC_RESERVED) == 0)
4619 /* release all the reserved blocks if non delalloc */
4620 percpu_counter_sub(&sbi->s_dirtyclusters_counter,
4621 reserv_clstrs);
4622 }
4623
4624 trace_ext4_allocate_blocks(ar, (unsigned long long)block);
4625
4626 return block;
4627 }
4628
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 */
4634 static 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)
4638 {
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);
4656 }
4657
4658 static noinline_for_stack int
4659 ext4_mb_free_metadata(handle_t *handle, struct ext4_buddy *e4b,
4660 struct ext4_free_data *new_entry)
4661 {
4662 ext4_group_t group = e4b->bd_group;
4663 ext4_grpblk_t cluster;
4664 ext4_grpblk_t clusters = new_entry->efd_count;
4665 struct ext4_free_data *entry;
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);
4669 struct rb_node **n = &db->bb_free_root.rb_node, *node;
4670 struct rb_node *parent = NULL, *new_node;
4671
4672 BUG_ON(!ext4_handle_valid(handle));
4673 BUG_ON(e4b->bd_bitmap_page == NULL);
4674 BUG_ON(e4b->bd_buddy_page == NULL);
4675
4676 new_node = &new_entry->efd_node;
4677 cluster = new_entry->efd_start_cluster;
4678
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 */
4685 get_page(e4b->bd_buddy_page);
4686 get_page(e4b->bd_bitmap_page);
4687 }
4688 while (*n) {
4689 parent = *n;
4690 entry = rb_entry(parent, struct ext4_free_data, efd_node);
4691 if (cluster < entry->efd_start_cluster)
4692 n = &(*n)->rb_left;
4693 else if (cluster >= (entry->efd_start_cluster + entry->efd_count))
4694 n = &(*n)->rb_right;
4695 else {
4696 ext4_grp_locked_error(sb, group, 0,
4697 ext4_group_first_block_no(sb, group) +
4698 EXT4_C2B(sbi, cluster),
4699 "Block already on to-be-freed list");
4700 return 0;
4701 }
4702 }
4703
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) {
4710 entry = rb_entry(node, struct ext4_free_data, efd_node);
4711 ext4_try_merge_freed_extent(sbi, entry, new_entry,
4712 &(db->bb_free_root));
4713 }
4714
4715 node = rb_next(new_node);
4716 if (node) {
4717 entry = rb_entry(node, struct ext4_free_data, efd_node);
4718 ext4_try_merge_freed_extent(sbi, entry, new_entry,
4719 &(db->bb_free_root));
4720 }
4721
4722 spin_lock(&sbi->s_md_lock);
4723 list_add_tail(&new_entry->efd_list, &sbi->s_freed_data_list);
4724 sbi->s_mb_free_pending += clusters;
4725 spin_unlock(&sbi->s_md_lock);
4726 return 0;
4727 }
4728
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
4735 * @flags: flags used by ext4_free_blocks
4736 */
4737 void ext4_free_blocks(handle_t *handle, struct inode *inode,
4738 struct buffer_head *bh, ext4_fsblk_t block,
4739 unsigned long count, int flags)
4740 {
4741 struct buffer_head *bitmap_bh = NULL;
4742 struct super_block *sb = inode->i_sb;
4743 struct ext4_group_desc *gdp;
4744 unsigned int overflow;
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;
4750 unsigned int count_clusters;
4751 int err = 0;
4752 int ret;
4753
4754 might_sleep();
4755 if (bh) {
4756 if (block)
4757 BUG_ON(block != bh->b_blocknr);
4758 else
4759 block = bh->b_blocknr;
4760 }
4761
4762 sbi = EXT4_SB(sb);
4763 if (!(flags & EXT4_FREE_BLOCKS_VALIDATED) &&
4764 !ext4_data_block_valid(sbi, block, count)) {
4765 ext4_error(sb, "Freeing blocks not in datazone - "
4766 "block = %llu, count = %lu", block, count);
4767 goto error_return;
4768 }
4769
4770 ext4_debug("freeing block %llu\n", block);
4771 trace_ext4_free_blocks(inode, block, count, flags);
4772
4773 if (bh && (flags & EXT4_FREE_BLOCKS_FORGET)) {
4774 BUG_ON(count > 1);
4775
4776 ext4_forget(handle, flags & EXT4_FREE_BLOCKS_METADATA,
4777 inode, bh, block);
4778 }
4779
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 */
4787 overflow = EXT4_PBLK_COFF(sbi, block);
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 }
4801 overflow = EXT4_LBLK_COFF(sbi, count);
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
4812 if (!bh && (flags & EXT4_FREE_BLOCKS_FORGET)) {
4813 int i;
4814 int is_metadata = flags & EXT4_FREE_BLOCKS_METADATA;
4815
4816 for (i = 0; i < count; i++) {
4817 cond_resched();
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);
4821 }
4822 }
4823
4824 do_more:
4825 overflow = 0;
4826 ext4_get_group_no_and_offset(sb, block, &block_group, &bit);
4827
4828 if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(
4829 ext4_get_group_info(sb, block_group))))
4830 return;
4831
4832 /*
4833 * Check to see if we are freeing blocks across a group
4834 * boundary.
4835 */
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);
4839 count -= overflow;
4840 }
4841 count_clusters = EXT4_NUM_B2C(sbi, count);
4842 bitmap_bh = ext4_read_block_bitmap(sb, block_group);
4843 if (IS_ERR(bitmap_bh)) {
4844 err = PTR_ERR(bitmap_bh);
4845 bitmap_bh = NULL;
4846 goto error_return;
4847 }
4848 gdp = ext4_get_group_desc(sb, block_group, &gd_bh);
4849 if (!gdp) {
4850 err = -EIO;
4851 goto error_return;
4852 }
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),
4857 EXT4_SB(sb)->s_itb_per_group) ||
4858 in_range(block + count - 1, ext4_inode_table(sb, gdp),
4859 EXT4_SB(sb)->s_itb_per_group)) {
4860
4861 ext4_error(sb, "Freeing blocks in system zone - "
4862 "Block = %llu, count = %lu", block, count);
4863 /* err = 0. ext4_std_error should be a no op */
4864 goto error_return;
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;
4881 #ifdef AGGRESSIVE_CHECK
4882 {
4883 int i;
4884 for (i = 0; i < count_clusters; i++)
4885 BUG_ON(!mb_test_bit(bit + i, bitmap_bh->b_data));
4886 }
4887 #endif
4888 trace_ext4_mballoc_free(sb, inode, block_group, bit, count_clusters);
4889
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);
4893 if (err)
4894 goto error_return;
4895
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))) {
4905 struct ext4_free_data *new_entry;
4906 /*
4907 * We use __GFP_NOFAIL because ext4_free_blocks() is not allowed
4908 * to fail.
4909 */
4910 new_entry = kmem_cache_alloc(ext4_free_data_cachep,
4911 GFP_NOFS|__GFP_NOFAIL);
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;
4916
4917 ext4_lock_group(sb, block_group);
4918 mb_clear_bits(bitmap_bh->b_data, bit, count_clusters);
4919 ext4_mb_free_metadata(handle, &e4b, new_entry);
4920 } else {
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 */
4925 if (test_opt(sb, DISCARD)) {
4926 err = ext4_issue_discard(sb, block_group, bit, count,
4927 NULL);
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);
4933 } else
4934 EXT4_MB_GRP_CLEAR_TRIMMED(e4b.bd_info);
4935
4936 ext4_lock_group(sb, block_group);
4937 mb_clear_bits(bitmap_bh->b_data, bit, count_clusters);
4938 mb_free_blocks(inode, &e4b, bit, count_clusters);
4939 }
4940
4941 ret = ext4_free_group_clusters(sb, gdp) + count_clusters;
4942 ext4_free_group_clusters_set(sb, gdp, ret);
4943 ext4_block_bitmap_csum_set(sb, block_group, gdp, bitmap_bh);
4944 ext4_group_desc_csum_set(sb, block_group, gdp);
4945 ext4_unlock_group(sb, block_group);
4946
4947 if (sbi->s_log_groups_per_flex) {
4948 ext4_group_t flex_group = ext4_flex_group(sbi, block_group);
4949 atomic64_add(count_clusters,
4950 &sbi->s_flex_groups[flex_group].free_clusters);
4951 }
4952
4953 if (!(flags & EXT4_FREE_BLOCKS_NO_QUOT_UPDATE))
4954 dquot_free_block(inode, EXT4_C2B(sbi, count_clusters));
4955 percpu_counter_add(&sbi->s_freeclusters_counter, count_clusters);
4956
4957 ext4_mb_unload_buddy(&e4b);
4958
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
4963 /* And the group descriptor block */
4964 BUFFER_TRACE(gd_bh, "dirtied group descriptor block");
4965 ret = ext4_handle_dirty_metadata(handle, NULL, gd_bh);
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 }
4975 error_return:
4976 brelse(bitmap_bh);
4977 ext4_std_error(sb, err);
4978 return;
4979 }
4980
4981 /**
4982 * ext4_group_add_blocks() -- Add given blocks to an existing group
4983 * @handle: handle to this transaction
4984 * @sb: super block
4985 * @block: start physical block to add to the block group
4986 * @count: number of blocks to free
4987 *
4988 * This marks the blocks as free in the bitmap and buddy.
4989 */
4990 int ext4_group_add_blocks(handle_t *handle, struct super_block *sb,
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);
5000 struct ext4_buddy e4b;
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;
5006
5007 ext4_debug("Adding block(s) %llu-%llu\n", block, block + count - 1);
5008
5009 if (count == 0)
5010 return 0;
5011
5012 ext4_get_group_no_and_offset(sb, block, &block_group, &bit);
5013 /*
5014 * Check to see if we are freeing blocks across a group
5015 * boundary.
5016 */
5017 if (bit + cluster_count > EXT4_CLUSTERS_PER_GROUP(sb)) {
5018 ext4_warning(sb, "too many blocks added to group %u",
5019 block_group);
5020 err = -EINVAL;
5021 goto error_return;
5022 }
5023
5024 bitmap_bh = ext4_read_block_bitmap(sb, block_group);
5025 if (IS_ERR(bitmap_bh)) {
5026 err = PTR_ERR(bitmap_bh);
5027 bitmap_bh = NULL;
5028 goto error_return;
5029 }
5030
5031 desc = ext4_get_group_desc(sb, block_group, &gd_bh);
5032 if (!desc) {
5033 err = -EIO;
5034 goto error_return;
5035 }
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);
5045 err = -EINVAL;
5046 goto error_return;
5047 }
5048
5049 BUFFER_TRACE(bitmap_bh, "getting write access");
5050 err = ext4_journal_get_write_access(handle, bitmap_bh);
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;
5063
5064 for (i = 0, clusters_freed = 0; i < cluster_count; i++) {
5065 BUFFER_TRACE(bitmap_bh, "clear bit");
5066 if (!mb_test_bit(bit + i, bitmap_bh->b_data)) {
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 {
5071 clusters_freed++;
5072 }
5073 }
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 */
5084 ext4_lock_group(sb, block_group);
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);
5090 ext4_block_bitmap_csum_set(sb, block_group, desc, bitmap_bh);
5091 ext4_group_desc_csum_set(sb, block_group, desc);
5092 ext4_unlock_group(sb, block_group);
5093 percpu_counter_add(&sbi->s_freeclusters_counter,
5094 clusters_freed);
5095
5096 if (sbi->s_log_groups_per_flex) {
5097 ext4_group_t flex_group = ext4_flex_group(sbi, block_group);
5098 atomic64_add(clusters_freed,
5099 &sbi->s_flex_groups[flex_group].free_clusters);
5100 }
5101
5102 ext4_mb_unload_buddy(&e4b);
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
5114 error_return:
5115 brelse(bitmap_bh);
5116 ext4_std_error(sb, err);
5117 return err;
5118 }
5119
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 */
5132 static int ext4_trim_extent(struct super_block *sb, int start, int count,
5133 ext4_group_t group, struct ext4_buddy *e4b)
5134 __releases(bitlock)
5135 __acquires(bitlock)
5136 {
5137 struct ext4_free_extent ex;
5138 int ret = 0;
5139
5140 trace_ext4_trim_extent(sb, group, start, count);
5141
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);
5154 ret = ext4_issue_discard(sb, group, start, count, NULL);
5155 ext4_lock_group(sb, group);
5156 mb_free_blocks(NULL, e4b, start, ex.fe_len);
5157 return ret;
5158 }
5159
5160 /**
5161 * ext4_trim_all_free -- function to trim all free space in alloc. group
5162 * @sb: super block for file system
5163 * @group: group to be trimmed
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 */
5178 static ext4_grpblk_t
5179 ext4_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)
5182 {
5183 void *bitmap;
5184 ext4_grpblk_t next, count = 0, free_count = 0;
5185 struct ext4_buddy e4b;
5186 int ret = 0;
5187
5188 trace_ext4_trim_all_free(sb, group, start, max);
5189
5190 ret = ext4_mb_load_buddy(sb, group, &e4b);
5191 if (ret) {
5192 ext4_warning(sb, "Error %d loading buddy information for %u",
5193 ret, group);
5194 return ret;
5195 }
5196 bitmap = e4b.bd_bitmap;
5197
5198 ext4_lock_group(sb, group);
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
5203 start = (e4b.bd_info->bb_first_free > start) ?
5204 e4b.bd_info->bb_first_free : start;
5205
5206 while (start <= max) {
5207 start = mb_find_next_zero_bit(bitmap, max + 1, start);
5208 if (start > max)
5209 break;
5210 next = mb_find_next_bit(bitmap, max + 1, start);
5211
5212 if ((next - start) >= minblocks) {
5213 ret = ext4_trim_extent(sb, start,
5214 next - start, group, &e4b);
5215 if (ret && ret != -EOPNOTSUPP)
5216 break;
5217 ret = 0;
5218 count += next - start;
5219 }
5220 free_count += next - start;
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
5234 if ((e4b.bd_info->bb_free - free_count) < minblocks)
5235 break;
5236 }
5237
5238 if (!ret) {
5239 ret = count;
5240 EXT4_MB_GRP_SET_TRIMMED(e4b.bd_info);
5241 }
5242 out:
5243 ext4_unlock_group(sb, group);
5244 ext4_mb_unload_buddy(&e4b);
5245
5246 ext4_debug("trimmed %d blocks in the group %d\n",
5247 count, group);
5248
5249 return ret;
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 */
5264 int ext4_trim_fs(struct super_block *sb, struct fstrim_range *range)
5265 {
5266 struct ext4_group_info *grp;
5267 ext4_group_t group, first_group, last_group;
5268 ext4_grpblk_t cnt = 0, first_cluster, last_cluster;
5269 uint64_t start, end, minlen, trimmed = 0;
5270 ext4_fsblk_t first_data_blk =
5271 le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block);
5272 ext4_fsblk_t max_blks = ext4_blocks_count(EXT4_SB(sb)->s_es);
5273 int ret = 0;
5274
5275 start = range->start >> sb->s_blocksize_bits;
5276 end = start + (range->len >> sb->s_blocksize_bits) - 1;
5277 minlen = EXT4_NUM_B2C(EXT4_SB(sb),
5278 range->minlen >> sb->s_blocksize_bits);
5279
5280 if (minlen > EXT4_CLUSTERS_PER_GROUP(sb) ||
5281 start >= max_blks ||
5282 range->len < sb->s_blocksize)
5283 return -EINVAL;
5284 if (end >= max_blks)
5285 end = max_blks - 1;
5286 if (end <= first_data_blk)
5287 goto out;
5288 if (start < first_data_blk)
5289 start = first_data_blk;
5290
5291 /* Determine first and last group to examine based on start and end */
5292 ext4_get_group_no_and_offset(sb, (ext4_fsblk_t) start,
5293 &first_group, &first_cluster);
5294 ext4_get_group_no_and_offset(sb, (ext4_fsblk_t) end,
5295 &last_group, &last_cluster);
5296
5297 /* end now represents the last cluster to discard in this group */
5298 end = EXT4_CLUSTERS_PER_GROUP(sb) - 1;
5299
5300 for (group = first_group; group <= last_group; group++) {
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))) {
5304 ret = ext4_mb_init_group(sb, group, GFP_NOFS);
5305 if (ret)
5306 break;
5307 }
5308
5309 /*
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()
5314 */
5315 if (group == last_group)
5316 end = last_cluster;
5317
5318 if (grp->bb_free >= minlen) {
5319 cnt = ext4_trim_all_free(sb, group, first_cluster,
5320 end, minlen);
5321 if (cnt < 0) {
5322 ret = cnt;
5323 break;
5324 }
5325 trimmed += cnt;
5326 }
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 */
5332 first_cluster = 0;
5333 }
5334
5335 if (!ret)
5336 atomic_set(&EXT4_SB(sb)->s_last_trim_minblks, minlen);
5337
5338 out:
5339 range->len = EXT4_C2B(EXT4_SB(sb), trimmed) << sb->s_blocksize_bits;
5340 return ret;
5341 }
5342
5343 /* Iterate all the free extents in the group. */
5344 int
5345 ext4_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);
5386 out_unload:
5387 ext4_mb_unload_buddy(&e4b);
5388
5389 return error;
5390 }