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