]> err.no Git - linux-2.6/blob - fs/ext4/mballoc.c
ext4: remove extra define of ext4_new_blocks_old from mballoc.c
[linux-2.6] / fs / ext4 / mballoc.c
1 /*
2  * Copyright (c) 2003-2006, Cluster File Systems, Inc, info@clusterfs.com
3  * Written by Alex Tomas <alex@clusterfs.com>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License version 2 as
7  * published by the Free Software Foundation.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public 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 <linux/time.h>
25 #include <linux/fs.h>
26 #include <linux/namei.h>
27 #include <linux/ext4_jbd2.h>
28 #include <linux/ext4_fs.h>
29 #include <linux/quotaops.h>
30 #include <linux/buffer_head.h>
31 #include <linux/module.h>
32 #include <linux/swap.h>
33 #include <linux/proc_fs.h>
34 #include <linux/pagemap.h>
35 #include <linux/seq_file.h>
36 #include <linux/version.h>
37 #include "group.h"
38
39 /*
40  * MUSTDO:
41  *   - test ext4_ext_search_left() and ext4_ext_search_right()
42  *   - search for metadata in few groups
43  *
44  * TODO v4:
45  *   - normalization should take into account whether file is still open
46  *   - discard preallocations if no free space left (policy?)
47  *   - don't normalize tails
48  *   - quota
49  *   - reservation for superuser
50  *
51  * TODO v3:
52  *   - bitmap read-ahead (proposed by Oleg Drokin aka green)
53  *   - track min/max extents in each group for better group selection
54  *   - mb_mark_used() may allocate chunk right after splitting buddy
55  *   - tree of groups sorted by number of free blocks
56  *   - error handling
57  */
58
59 /*
60  * The allocation request involve request for multiple number of blocks
61  * near to the goal(block) value specified.
62  *
63  * During initialization phase of the allocator we decide to use the group
64  * preallocation or inode preallocation depending on the size file. The
65  * size of the file could be the resulting file size we would have after
66  * allocation or the current file size which ever is larger. If the size is
67  * less that sbi->s_mb_stream_request we select the group
68  * preallocation. The default value of s_mb_stream_request is 16
69  * blocks. This can also be tuned via
70  * /proc/fs/ext4/<partition>/stream_req. The value is represented in terms
71  * of number of blocks.
72  *
73  * The main motivation for having small file use group preallocation is to
74  * ensure that we have small file closer in the disk.
75  *
76  * First stage the allocator looks at the inode prealloc list
77  * ext4_inode_info->i_prealloc_list contain list of prealloc spaces for
78  * this particular inode. The inode prealloc space is 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    -> lenght for this prealloc space
83  * pa_free   ->  free space available in this prealloc space
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 make sure that
88  * that the 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 repreasented 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) withing 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 buddy][ group 0 bitmap] [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. Default value of s_mb_group_prealloc is set to
139  * 512 blocks. This can be tuned via
140  * /proc/fs/ext4/<partition/group_prealloc. The value is represented in
141  * terms of number of blocks. If we have mounted the file system with -O
142  * stripe=<value> option the group prealloc request is normalized to the
143  * stripe value (sbi->s_stripe)
144  *
145  * The regular allocator(using the buddy cache) support few tunables.
146  *
147  * /proc/fs/ext4/<partition>/min_to_scan
148  * /proc/fs/ext4/<partition>/max_to_scan
149  * /proc/fs/ext4/<partition>/order2_req
150  *
151  * The regular allocator use buddy scan only if the request len is power of
152  * 2 blocks and the order of allocation is >= sbi->s_mb_order2_reqs. The
153  * value of s_mb_order2_reqs can be tuned via
154  * /proc/fs/ext4/<partition>/order2_req.  If the request len is equal to
155  * stripe size (sbi->s_stripe), we try to search for contigous block in
156  * stripe size. This should result in better allocation on RAID setup. If
157  * not we search in the specific group using bitmap for best extents. The
158  * tunable min_to_scan and max_to_scan controll the behaviour here.
159  * min_to_scan indicate how long the mballoc __must__ look for a best
160  * extent and max_to_scanindicate how long the mballoc __can__ look for a
161  * best extent in the found extents. Searching for the blocks starts with
162  * the group specified as the goal value in allocation context via
163  * ac_g_ex. Each group is first checked based on the criteria whether it
164  * can used for allocation. ext4_mb_good_group explains how the groups are
165  * checked.
166  *
167  * Both the prealloc space are getting populated as above. So for the first
168  * request we will hit the buddy cache which will result in this prealloc
169  * space getting filled. The prealloc space is then later used for the
170  * subsequent request.
171  */
172
173 /*
174  * mballoc operates on the following data:
175  *  - on-disk bitmap
176  *  - in-core buddy (actually includes buddy and bitmap)
177  *  - preallocation descriptors (PAs)
178  *
179  * there are two types of preallocations:
180  *  - inode
181  *    assiged to specific inode and can be used for this inode only.
182  *    it describes part of inode's space preallocated to specific
183  *    physical blocks. any block from that preallocated can be used
184  *    independent. the descriptor just tracks number of blocks left
185  *    unused. so, before taking some block from descriptor, one must
186  *    make sure corresponded logical block isn't allocated yet. this
187  *    also means that freeing any block within descriptor's range
188  *    must discard all preallocated blocks.
189  *  - locality group
190  *    assigned to specific locality group which does not translate to
191  *    permanent set of inodes: inode can join and leave group. space
192  *    from this type of preallocation can be used for any inode. thus
193  *    it's consumed from the beginning to the end.
194  *
195  * relation between them can be expressed as:
196  *    in-core buddy = on-disk bitmap + preallocation descriptors
197  *
198  * this mean blocks mballoc considers used are:
199  *  - allocated blocks (persistent)
200  *  - preallocated blocks (non-persistent)
201  *
202  * consistency in mballoc world means that at any time a block is either
203  * free or used in ALL structures. notice: "any time" should not be read
204  * literally -- time is discrete and delimited by locks.
205  *
206  *  to keep it simple, we don't use block numbers, instead we count number of
207  *  blocks: how many blocks marked used/free in on-disk bitmap, buddy and PA.
208  *
209  * all operations can be expressed as:
210  *  - init buddy:                       buddy = on-disk + PAs
211  *  - new PA:                           buddy += N; PA = N
212  *  - use inode PA:                     on-disk += N; PA -= N
213  *  - discard inode PA                  buddy -= on-disk - PA; PA = 0
214  *  - use locality group PA             on-disk += N; PA -= N
215  *  - discard locality group PA         buddy -= PA; PA = 0
216  *  note: 'buddy -= on-disk - PA' is used to show that on-disk bitmap
217  *        is used in real operation because we can't know actual used
218  *        bits from PA, only from on-disk bitmap
219  *
220  * if we follow this strict logic, then all operations above should be atomic.
221  * given some of them can block, we'd have to use something like semaphores
222  * killing performance on high-end SMP hardware. let's try to relax it using
223  * the following knowledge:
224  *  1) if buddy is referenced, it's already initialized
225  *  2) while block is used in buddy and the buddy is referenced,
226  *     nobody can re-allocate that block
227  *  3) we work on bitmaps and '+' actually means 'set bits'. if on-disk has
228  *     bit set and PA claims same block, it's OK. IOW, one can set bit in
229  *     on-disk bitmap if buddy has same bit set or/and PA covers corresponded
230  *     block
231  *
232  * so, now we're building a concurrency table:
233  *  - init buddy vs.
234  *    - new PA
235  *      blocks for PA are allocated in the buddy, buddy must be referenced
236  *      until PA is linked to allocation group to avoid concurrent buddy init
237  *    - use inode PA
238  *      we need to make sure that either on-disk bitmap or PA has uptodate data
239  *      given (3) we care that PA-=N operation doesn't interfere with init
240  *    - discard inode PA
241  *      the simplest way would be to have buddy initialized by the discard
242  *    - use locality group PA
243  *      again PA-=N must be serialized with init
244  *    - discard locality group PA
245  *      the simplest way would be to have buddy initialized by the discard
246  *  - new PA vs.
247  *    - use inode PA
248  *      i_data_sem serializes them
249  *    - discard inode PA
250  *      discard process must wait until PA isn't used by another process
251  *    - use locality group PA
252  *      some mutex should serialize them
253  *    - discard locality group PA
254  *      discard process must wait until PA isn't used by another process
255  *  - use inode PA
256  *    - use inode PA
257  *      i_data_sem or another mutex should serializes them
258  *    - discard inode PA
259  *      discard process must wait until PA isn't used by another process
260  *    - use locality group PA
261  *      nothing wrong here -- they're different PAs covering different blocks
262  *    - discard locality group PA
263  *      discard process must wait until PA isn't used by another process
264  *
265  * now we're ready to make few consequences:
266  *  - PA is referenced and while it is no discard is possible
267  *  - PA is referenced until block isn't marked in on-disk bitmap
268  *  - PA changes only after on-disk bitmap
269  *  - discard must not compete with init. either init is done before
270  *    any discard or they're serialized somehow
271  *  - buddy init as sum of on-disk bitmap and PAs is done atomically
272  *
273  * a special case when we've used PA to emptiness. no need to modify buddy
274  * in this case, but we should care about concurrent init
275  *
276  */
277
278  /*
279  * Logic in few words:
280  *
281  *  - allocation:
282  *    load group
283  *    find blocks
284  *    mark bits in on-disk bitmap
285  *    release group
286  *
287  *  - use preallocation:
288  *    find proper PA (per-inode or group)
289  *    load group
290  *    mark bits in on-disk bitmap
291  *    release group
292  *    release PA
293  *
294  *  - free:
295  *    load group
296  *    mark bits in on-disk bitmap
297  *    release group
298  *
299  *  - discard preallocations in group:
300  *    mark PAs deleted
301  *    move them onto local list
302  *    load on-disk bitmap
303  *    load group
304  *    remove PA from object (inode or locality group)
305  *    mark free blocks in-core
306  *
307  *  - discard inode's preallocations:
308  */
309
310 /*
311  * Locking rules
312  *
313  * Locks:
314  *  - bitlock on a group        (group)
315  *  - object (inode/locality)   (object)
316  *  - per-pa lock               (pa)
317  *
318  * Paths:
319  *  - new pa
320  *    object
321  *    group
322  *
323  *  - find and use pa:
324  *    pa
325  *
326  *  - release consumed pa:
327  *    pa
328  *    group
329  *    object
330  *
331  *  - generate in-core bitmap:
332  *    group
333  *        pa
334  *
335  *  - discard all for given object (inode, locality group):
336  *    object
337  *        pa
338  *    group
339  *
340  *  - discard all for given group:
341  *    group
342  *        pa
343  *    group
344  *        object
345  *
346  */
347
348 /*
349  * with AGGRESSIVE_CHECK allocator runs consistency checks over
350  * structures. these checks slow things down a lot
351  */
352 #define AGGRESSIVE_CHECK__
353
354 /*
355  * with DOUBLE_CHECK defined mballoc creates persistent in-core
356  * bitmaps, maintains and uses them to check for double allocations
357  */
358 #define DOUBLE_CHECK__
359
360 /*
361  */
362 #define MB_DEBUG__
363 #ifdef MB_DEBUG
364 #define mb_debug(fmt, a...)     printk(fmt, ##a)
365 #else
366 #define mb_debug(fmt, a...)
367 #endif
368
369 /*
370  * with EXT4_MB_HISTORY mballoc stores last N allocations in memory
371  * and you can monitor it in /proc/fs/ext4/<dev>/mb_history
372  */
373 #define EXT4_MB_HISTORY
374 #define EXT4_MB_HISTORY_ALLOC           1       /* allocation */
375 #define EXT4_MB_HISTORY_PREALLOC        2       /* preallocated blocks used */
376 #define EXT4_MB_HISTORY_DISCARD         4       /* preallocation discarded */
377 #define EXT4_MB_HISTORY_FREE            8       /* free */
378
379 #define EXT4_MB_HISTORY_DEFAULT         (EXT4_MB_HISTORY_ALLOC | \
380                                          EXT4_MB_HISTORY_PREALLOC)
381
382 /*
383  * How long mballoc can look for a best extent (in found extents)
384  */
385 #define MB_DEFAULT_MAX_TO_SCAN          200
386
387 /*
388  * How long mballoc must look for a best extent
389  */
390 #define MB_DEFAULT_MIN_TO_SCAN          10
391
392 /*
393  * How many groups mballoc will scan looking for the best chunk
394  */
395 #define MB_DEFAULT_MAX_GROUPS_TO_SCAN   5
396
397 /*
398  * with 'ext4_mb_stats' allocator will collect stats that will be
399  * shown at umount. The collecting costs though!
400  */
401 #define MB_DEFAULT_STATS                1
402
403 /*
404  * files smaller than MB_DEFAULT_STREAM_THRESHOLD are served
405  * by the stream allocator, which purpose is to pack requests
406  * as close each to other as possible to produce smooth I/O traffic
407  * We use locality group prealloc space for stream request.
408  * We can tune the same via /proc/fs/ext4/<parition>/stream_req
409  */
410 #define MB_DEFAULT_STREAM_THRESHOLD     16      /* 64K */
411
412 /*
413  * for which requests use 2^N search using buddies
414  */
415 #define MB_DEFAULT_ORDER2_REQS          2
416
417 /*
418  * default group prealloc size 512 blocks
419  */
420 #define MB_DEFAULT_GROUP_PREALLOC       512
421
422 static struct kmem_cache *ext4_pspace_cachep;
423 static struct kmem_cache *ext4_ac_cachep;
424
425 #ifdef EXT4_BB_MAX_BLOCKS
426 #undef EXT4_BB_MAX_BLOCKS
427 #endif
428 #define EXT4_BB_MAX_BLOCKS      30
429
430 struct ext4_free_metadata {
431         ext4_group_t group;
432         unsigned short num;
433         ext4_grpblk_t  blocks[EXT4_BB_MAX_BLOCKS];
434         struct list_head list;
435 };
436
437 struct ext4_group_info {
438         unsigned long   bb_state;
439         unsigned long   bb_tid;
440         struct ext4_free_metadata *bb_md_cur;
441         unsigned short  bb_first_free;
442         unsigned short  bb_free;
443         unsigned short  bb_fragments;
444         struct          list_head bb_prealloc_list;
445 #ifdef DOUBLE_CHECK
446         void            *bb_bitmap;
447 #endif
448         unsigned short  bb_counters[];
449 };
450
451 #define EXT4_GROUP_INFO_NEED_INIT_BIT   0
452 #define EXT4_GROUP_INFO_LOCKED_BIT      1
453
454 #define EXT4_MB_GRP_NEED_INIT(grp)      \
455         (test_bit(EXT4_GROUP_INFO_NEED_INIT_BIT, &((grp)->bb_state)))
456
457
458 struct ext4_prealloc_space {
459         struct list_head        pa_inode_list;
460         struct list_head        pa_group_list;
461         union {
462                 struct list_head pa_tmp_list;
463                 struct rcu_head pa_rcu;
464         } u;
465         spinlock_t              pa_lock;
466         atomic_t                pa_count;
467         unsigned                pa_deleted;
468         ext4_fsblk_t            pa_pstart;      /* phys. block */
469         ext4_lblk_t             pa_lstart;      /* log. block */
470         unsigned short          pa_len;         /* len of preallocated chunk */
471         unsigned short          pa_free;        /* how many blocks are free */
472         unsigned short          pa_linear;      /* consumed in one direction
473                                                  * strictly, for grp prealloc */
474         spinlock_t              *pa_obj_lock;
475         struct inode            *pa_inode;      /* hack, for history only */
476 };
477
478
479 struct ext4_free_extent {
480         ext4_lblk_t fe_logical;
481         ext4_grpblk_t fe_start;
482         ext4_group_t fe_group;
483         int fe_len;
484 };
485
486 /*
487  * Locality group:
488  *   we try to group all related changes together
489  *   so that writeback can flush/allocate them together as well
490  */
491 struct ext4_locality_group {
492         /* for allocator */
493         struct mutex            lg_mutex;       /* to serialize allocates */
494         struct list_head        lg_prealloc_list;/* list of preallocations */
495         spinlock_t              lg_prealloc_lock;
496 };
497
498 struct ext4_allocation_context {
499         struct inode *ac_inode;
500         struct super_block *ac_sb;
501
502         /* original request */
503         struct ext4_free_extent ac_o_ex;
504
505         /* goal request (after normalization) */
506         struct ext4_free_extent ac_g_ex;
507
508         /* the best found extent */
509         struct ext4_free_extent ac_b_ex;
510
511         /* copy of the bext found extent taken before preallocation efforts */
512         struct ext4_free_extent ac_f_ex;
513
514         /* number of iterations done. we have to track to limit searching */
515         unsigned long ac_ex_scanned;
516         __u16 ac_groups_scanned;
517         __u16 ac_found;
518         __u16 ac_tail;
519         __u16 ac_buddy;
520         __u16 ac_flags;         /* allocation hints */
521         __u8 ac_status;
522         __u8 ac_criteria;
523         __u8 ac_repeats;
524         __u8 ac_2order;         /* if request is to allocate 2^N blocks and
525                                  * N > 0, the field stores N, otherwise 0 */
526         __u8 ac_op;             /* operation, for history only */
527         struct page *ac_bitmap_page;
528         struct page *ac_buddy_page;
529         struct ext4_prealloc_space *ac_pa;
530         struct ext4_locality_group *ac_lg;
531 };
532
533 #define AC_STATUS_CONTINUE      1
534 #define AC_STATUS_FOUND         2
535 #define AC_STATUS_BREAK         3
536
537 struct ext4_mb_history {
538         struct ext4_free_extent orig;   /* orig allocation */
539         struct ext4_free_extent goal;   /* goal allocation */
540         struct ext4_free_extent result; /* result allocation */
541         unsigned pid;
542         unsigned ino;
543         __u16 found;    /* how many extents have been found */
544         __u16 groups;   /* how many groups have been scanned */
545         __u16 tail;     /* what tail broke some buddy */
546         __u16 buddy;    /* buddy the tail ^^^ broke */
547         __u16 flags;
548         __u8 cr:3;      /* which phase the result extent was found at */
549         __u8 op:4;
550         __u8 merged:1;
551 };
552
553 struct ext4_buddy {
554         struct page *bd_buddy_page;
555         void *bd_buddy;
556         struct page *bd_bitmap_page;
557         void *bd_bitmap;
558         struct ext4_group_info *bd_info;
559         struct super_block *bd_sb;
560         __u16 bd_blkbits;
561         ext4_group_t bd_group;
562 };
563 #define EXT4_MB_BITMAP(e4b)     ((e4b)->bd_bitmap)
564 #define EXT4_MB_BUDDY(e4b)      ((e4b)->bd_buddy)
565
566 #ifndef EXT4_MB_HISTORY
567 static inline void ext4_mb_store_history(struct ext4_allocation_context *ac)
568 {
569         return;
570 }
571 #else
572 static void ext4_mb_store_history(struct ext4_allocation_context *ac);
573 #endif
574
575 #define in_range(b, first, len) ((b) >= (first) && (b) <= (first) + (len) - 1)
576
577 static struct proc_dir_entry *proc_root_ext4;
578 struct buffer_head *read_block_bitmap(struct super_block *, ext4_group_t);
579
580 static void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
581                                         ext4_group_t group);
582 static void ext4_mb_poll_new_transaction(struct super_block *, handle_t *);
583 static void ext4_mb_free_committed_blocks(struct super_block *);
584 static void ext4_mb_return_to_preallocation(struct inode *inode,
585                                         struct ext4_buddy *e4b, sector_t block,
586                                         int count);
587 static void ext4_mb_put_pa(struct ext4_allocation_context *,
588                         struct super_block *, struct ext4_prealloc_space *pa);
589 static int ext4_mb_init_per_dev_proc(struct super_block *sb);
590 static int ext4_mb_destroy_per_dev_proc(struct super_block *sb);
591
592
593 static inline void ext4_lock_group(struct super_block *sb, ext4_group_t group)
594 {
595         struct ext4_group_info *grinfo = ext4_get_group_info(sb, group);
596
597         bit_spin_lock(EXT4_GROUP_INFO_LOCKED_BIT, &(grinfo->bb_state));
598 }
599
600 static inline void ext4_unlock_group(struct super_block *sb,
601                                         ext4_group_t group)
602 {
603         struct ext4_group_info *grinfo = ext4_get_group_info(sb, group);
604
605         bit_spin_unlock(EXT4_GROUP_INFO_LOCKED_BIT, &(grinfo->bb_state));
606 }
607
608 static inline int ext4_is_group_locked(struct super_block *sb,
609                                         ext4_group_t group)
610 {
611         struct ext4_group_info *grinfo = ext4_get_group_info(sb, group);
612
613         return bit_spin_is_locked(EXT4_GROUP_INFO_LOCKED_BIT,
614                                                 &(grinfo->bb_state));
615 }
616
617 static ext4_fsblk_t ext4_grp_offs_to_block(struct super_block *sb,
618                                         struct ext4_free_extent *fex)
619 {
620         ext4_fsblk_t block;
621
622         block = (ext4_fsblk_t) fex->fe_group * EXT4_BLOCKS_PER_GROUP(sb)
623                         + fex->fe_start
624                         + le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block);
625         return block;
626 }
627
628 static inline void *mb_correct_addr_and_bit(int *bit, void *addr)
629 {
630 #if BITS_PER_LONG == 64
631         *bit += ((unsigned long) addr & 7UL) << 3;
632         addr = (void *) ((unsigned long) addr & ~7UL);
633 #elif BITS_PER_LONG == 32
634         *bit += ((unsigned long) addr & 3UL) << 3;
635         addr = (void *) ((unsigned long) addr & ~3UL);
636 #else
637 #error "how many bits you are?!"
638 #endif
639         return addr;
640 }
641
642 static inline int mb_test_bit(int bit, void *addr)
643 {
644         /*
645          * ext4_test_bit on architecture like powerpc
646          * needs unsigned long aligned address
647          */
648         addr = mb_correct_addr_and_bit(&bit, addr);
649         return ext4_test_bit(bit, addr);
650 }
651
652 static inline void mb_set_bit(int bit, void *addr)
653 {
654         addr = mb_correct_addr_and_bit(&bit, addr);
655         ext4_set_bit(bit, addr);
656 }
657
658 static inline void mb_set_bit_atomic(spinlock_t *lock, int bit, void *addr)
659 {
660         addr = mb_correct_addr_and_bit(&bit, addr);
661         ext4_set_bit_atomic(lock, bit, addr);
662 }
663
664 static inline void mb_clear_bit(int bit, void *addr)
665 {
666         addr = mb_correct_addr_and_bit(&bit, addr);
667         ext4_clear_bit(bit, addr);
668 }
669
670 static inline void mb_clear_bit_atomic(spinlock_t *lock, int bit, void *addr)
671 {
672         addr = mb_correct_addr_and_bit(&bit, addr);
673         ext4_clear_bit_atomic(lock, bit, addr);
674 }
675
676 static inline int mb_find_next_zero_bit(void *addr, int max, int start)
677 {
678         int fix = 0;
679         addr = mb_correct_addr_and_bit(&fix, addr);
680         max += fix;
681         start += fix;
682
683         return ext4_find_next_zero_bit(addr, max, start) - fix;
684 }
685
686 static inline int mb_find_next_bit(void *addr, int max, int start)
687 {
688         int fix = 0;
689         addr = mb_correct_addr_and_bit(&fix, addr);
690         max += fix;
691         start += fix;
692
693         return ext4_find_next_bit(addr, max, start) - fix;
694 }
695
696 static void *mb_find_buddy(struct ext4_buddy *e4b, int order, int *max)
697 {
698         char *bb;
699
700         BUG_ON(EXT4_MB_BITMAP(e4b) == EXT4_MB_BUDDY(e4b));
701         BUG_ON(max == NULL);
702
703         if (order > e4b->bd_blkbits + 1) {
704                 *max = 0;
705                 return NULL;
706         }
707
708         /* at order 0 we see each particular block */
709         *max = 1 << (e4b->bd_blkbits + 3);
710         if (order == 0)
711                 return EXT4_MB_BITMAP(e4b);
712
713         bb = EXT4_MB_BUDDY(e4b) + EXT4_SB(e4b->bd_sb)->s_mb_offsets[order];
714         *max = EXT4_SB(e4b->bd_sb)->s_mb_maxs[order];
715
716         return bb;
717 }
718
719 #ifdef DOUBLE_CHECK
720 static void mb_free_blocks_double(struct inode *inode, struct ext4_buddy *e4b,
721                            int first, int count)
722 {
723         int i;
724         struct super_block *sb = e4b->bd_sb;
725
726         if (unlikely(e4b->bd_info->bb_bitmap == NULL))
727                 return;
728         BUG_ON(!ext4_is_group_locked(sb, e4b->bd_group));
729         for (i = 0; i < count; i++) {
730                 if (!mb_test_bit(first + i, e4b->bd_info->bb_bitmap)) {
731                         ext4_fsblk_t blocknr;
732                         blocknr = e4b->bd_group * EXT4_BLOCKS_PER_GROUP(sb);
733                         blocknr += first + i;
734                         blocknr +=
735                             le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block);
736
737                         ext4_error(sb, __FUNCTION__, "double-free of inode"
738                                    " %lu's block %llu(bit %u in group %lu)\n",
739                                    inode ? inode->i_ino : 0, blocknr,
740                                    first + i, e4b->bd_group);
741                 }
742                 mb_clear_bit(first + i, e4b->bd_info->bb_bitmap);
743         }
744 }
745
746 static void mb_mark_used_double(struct ext4_buddy *e4b, int first, int count)
747 {
748         int i;
749
750         if (unlikely(e4b->bd_info->bb_bitmap == NULL))
751                 return;
752         BUG_ON(!ext4_is_group_locked(e4b->bd_sb, e4b->bd_group));
753         for (i = 0; i < count; i++) {
754                 BUG_ON(mb_test_bit(first + i, e4b->bd_info->bb_bitmap));
755                 mb_set_bit(first + i, e4b->bd_info->bb_bitmap);
756         }
757 }
758
759 static void mb_cmp_bitmaps(struct ext4_buddy *e4b, void *bitmap)
760 {
761         if (memcmp(e4b->bd_info->bb_bitmap, bitmap, e4b->bd_sb->s_blocksize)) {
762                 unsigned char *b1, *b2;
763                 int i;
764                 b1 = (unsigned char *) e4b->bd_info->bb_bitmap;
765                 b2 = (unsigned char *) bitmap;
766                 for (i = 0; i < e4b->bd_sb->s_blocksize; i++) {
767                         if (b1[i] != b2[i]) {
768                                 printk("corruption in group %lu at byte %u(%u):"
769                                        " %x in copy != %x on disk/prealloc\n",
770                                         e4b->bd_group, i, i * 8, b1[i], b2[i]);
771                                 BUG();
772                         }
773                 }
774         }
775 }
776
777 #else
778 static inline void mb_free_blocks_double(struct inode *inode,
779                                 struct ext4_buddy *e4b, int first, int count)
780 {
781         return;
782 }
783 static inline void mb_mark_used_double(struct ext4_buddy *e4b,
784                                                 int first, int count)
785 {
786         return;
787 }
788 static inline void mb_cmp_bitmaps(struct ext4_buddy *e4b, void *bitmap)
789 {
790         return;
791 }
792 #endif
793
794 #ifdef AGGRESSIVE_CHECK
795
796 #define MB_CHECK_ASSERT(assert)                                         \
797 do {                                                                    \
798         if (!(assert)) {                                                \
799                 printk(KERN_EMERG                                       \
800                         "Assertion failure in %s() at %s:%d: \"%s\"\n", \
801                         function, file, line, # assert);                \
802                 BUG();                                                  \
803         }                                                               \
804 } while (0)
805
806 static int __mb_check_buddy(struct ext4_buddy *e4b, char *file,
807                                 const char *function, int line)
808 {
809         struct super_block *sb = e4b->bd_sb;
810         int order = e4b->bd_blkbits + 1;
811         int max;
812         int max2;
813         int i;
814         int j;
815         int k;
816         int count;
817         struct ext4_group_info *grp;
818         int fragments = 0;
819         int fstart;
820         struct list_head *cur;
821         void *buddy;
822         void *buddy2;
823
824         if (!test_opt(sb, MBALLOC))
825                 return 0;
826
827         {
828                 static int mb_check_counter;
829                 if (mb_check_counter++ % 100 != 0)
830                         return 0;
831         }
832
833         while (order > 1) {
834                 buddy = mb_find_buddy(e4b, order, &max);
835                 MB_CHECK_ASSERT(buddy);
836                 buddy2 = mb_find_buddy(e4b, order - 1, &max2);
837                 MB_CHECK_ASSERT(buddy2);
838                 MB_CHECK_ASSERT(buddy != buddy2);
839                 MB_CHECK_ASSERT(max * 2 == max2);
840
841                 count = 0;
842                 for (i = 0; i < max; i++) {
843
844                         if (mb_test_bit(i, buddy)) {
845                                 /* only single bit in buddy2 may be 1 */
846                                 if (!mb_test_bit(i << 1, buddy2)) {
847                                         MB_CHECK_ASSERT(
848                                                 mb_test_bit((i<<1)+1, buddy2));
849                                 } else if (!mb_test_bit((i << 1) + 1, buddy2)) {
850                                         MB_CHECK_ASSERT(
851                                                 mb_test_bit(i << 1, buddy2));
852                                 }
853                                 continue;
854                         }
855
856                         /* both bits in buddy2 must be 0 */
857                         MB_CHECK_ASSERT(mb_test_bit(i << 1, buddy2));
858                         MB_CHECK_ASSERT(mb_test_bit((i << 1) + 1, buddy2));
859
860                         for (j = 0; j < (1 << order); j++) {
861                                 k = (i * (1 << order)) + j;
862                                 MB_CHECK_ASSERT(
863                                         !mb_test_bit(k, EXT4_MB_BITMAP(e4b)));
864                         }
865                         count++;
866                 }
867                 MB_CHECK_ASSERT(e4b->bd_info->bb_counters[order] == count);
868                 order--;
869         }
870
871         fstart = -1;
872         buddy = mb_find_buddy(e4b, 0, &max);
873         for (i = 0; i < max; i++) {
874                 if (!mb_test_bit(i, buddy)) {
875                         MB_CHECK_ASSERT(i >= e4b->bd_info->bb_first_free);
876                         if (fstart == -1) {
877                                 fragments++;
878                                 fstart = i;
879                         }
880                         continue;
881                 }
882                 fstart = -1;
883                 /* check used bits only */
884                 for (j = 0; j < e4b->bd_blkbits + 1; j++) {
885                         buddy2 = mb_find_buddy(e4b, j, &max2);
886                         k = i >> j;
887                         MB_CHECK_ASSERT(k < max2);
888                         MB_CHECK_ASSERT(mb_test_bit(k, buddy2));
889                 }
890         }
891         MB_CHECK_ASSERT(!EXT4_MB_GRP_NEED_INIT(e4b->bd_info));
892         MB_CHECK_ASSERT(e4b->bd_info->bb_fragments == fragments);
893
894         grp = ext4_get_group_info(sb, e4b->bd_group);
895         buddy = mb_find_buddy(e4b, 0, &max);
896         list_for_each(cur, &grp->bb_prealloc_list) {
897                 ext4_group_t groupnr;
898                 struct ext4_prealloc_space *pa;
899                 pa = list_entry(cur, struct ext4_prealloc_space, group_list);
900                 ext4_get_group_no_and_offset(sb, pa->pstart, &groupnr, &k);
901                 MB_CHECK_ASSERT(groupnr == e4b->bd_group);
902                 for (i = 0; i < pa->len; i++)
903                         MB_CHECK_ASSERT(mb_test_bit(k + i, buddy));
904         }
905         return 0;
906 }
907 #undef MB_CHECK_ASSERT
908 #define mb_check_buddy(e4b) __mb_check_buddy(e4b,       \
909                                         __FILE__, __FUNCTION__, __LINE__)
910 #else
911 #define mb_check_buddy(e4b)
912 #endif
913
914 /* FIXME!! need more doc */
915 static void ext4_mb_mark_free_simple(struct super_block *sb,
916                                 void *buddy, unsigned first, int len,
917                                         struct ext4_group_info *grp)
918 {
919         struct ext4_sb_info *sbi = EXT4_SB(sb);
920         unsigned short min;
921         unsigned short max;
922         unsigned short chunk;
923         unsigned short border;
924
925         BUG_ON(len > EXT4_BLOCKS_PER_GROUP(sb));
926
927         border = 2 << sb->s_blocksize_bits;
928
929         while (len > 0) {
930                 /* find how many blocks can be covered since this position */
931                 max = ffs(first | border) - 1;
932
933                 /* find how many blocks of power 2 we need to mark */
934                 min = fls(len) - 1;
935
936                 if (max < min)
937                         min = max;
938                 chunk = 1 << min;
939
940                 /* mark multiblock chunks only */
941                 grp->bb_counters[min]++;
942                 if (min > 0)
943                         mb_clear_bit(first >> min,
944                                      buddy + sbi->s_mb_offsets[min]);
945
946                 len -= chunk;
947                 first += chunk;
948         }
949 }
950
951 static void ext4_mb_generate_buddy(struct super_block *sb,
952                                 void *buddy, void *bitmap, ext4_group_t group)
953 {
954         struct ext4_group_info *grp = ext4_get_group_info(sb, group);
955         unsigned short max = EXT4_BLOCKS_PER_GROUP(sb);
956         unsigned short i = 0;
957         unsigned short first;
958         unsigned short len;
959         unsigned free = 0;
960         unsigned fragments = 0;
961         unsigned long long period = get_cycles();
962
963         /* initialize buddy from bitmap which is aggregation
964          * of on-disk bitmap and preallocations */
965         i = mb_find_next_zero_bit(bitmap, max, 0);
966         grp->bb_first_free = i;
967         while (i < max) {
968                 fragments++;
969                 first = i;
970                 i = mb_find_next_bit(bitmap, max, i);
971                 len = i - first;
972                 free += len;
973                 if (len > 1)
974                         ext4_mb_mark_free_simple(sb, buddy, first, len, grp);
975                 else
976                         grp->bb_counters[0]++;
977                 if (i < max)
978                         i = mb_find_next_zero_bit(bitmap, max, i);
979         }
980         grp->bb_fragments = fragments;
981
982         if (free != grp->bb_free) {
983                 ext4_error(sb, __FUNCTION__,
984                         "EXT4-fs: group %lu: %u blocks in bitmap, %u in gd\n",
985                         group, free, grp->bb_free);
986                 /*
987                  * If we intent to continue, we consider group descritor
988                  * corrupt and update bb_free using bitmap value
989                  */
990                 grp->bb_free = free;
991         }
992
993         clear_bit(EXT4_GROUP_INFO_NEED_INIT_BIT, &(grp->bb_state));
994
995         period = get_cycles() - period;
996         spin_lock(&EXT4_SB(sb)->s_bal_lock);
997         EXT4_SB(sb)->s_mb_buddies_generated++;
998         EXT4_SB(sb)->s_mb_generation_time += period;
999         spin_unlock(&EXT4_SB(sb)->s_bal_lock);
1000 }
1001
1002 /* The buddy information is attached the buddy cache inode
1003  * for convenience. The information regarding each group
1004  * is loaded via ext4_mb_load_buddy. The information involve
1005  * block bitmap and buddy information. The information are
1006  * stored in the inode as
1007  *
1008  * {                        page                        }
1009  * [ group 0 buddy][ group 0 bitmap] [group 1][ group 1]...
1010  *
1011  *
1012  * one block each for bitmap and buddy information.
1013  * So for each group we take up 2 blocks. A page can
1014  * contain blocks_per_page (PAGE_CACHE_SIZE / blocksize)  blocks.
1015  * So it can have information regarding groups_per_page which
1016  * is blocks_per_page/2
1017  */
1018
1019 static int ext4_mb_init_cache(struct page *page, char *incore)
1020 {
1021         int blocksize;
1022         int blocks_per_page;
1023         int groups_per_page;
1024         int err = 0;
1025         int i;
1026         ext4_group_t first_group;
1027         int first_block;
1028         struct super_block *sb;
1029         struct buffer_head *bhs;
1030         struct buffer_head **bh;
1031         struct inode *inode;
1032         char *data;
1033         char *bitmap;
1034
1035         mb_debug("init page %lu\n", page->index);
1036
1037         inode = page->mapping->host;
1038         sb = inode->i_sb;
1039         blocksize = 1 << inode->i_blkbits;
1040         blocks_per_page = PAGE_CACHE_SIZE / blocksize;
1041
1042         groups_per_page = blocks_per_page >> 1;
1043         if (groups_per_page == 0)
1044                 groups_per_page = 1;
1045
1046         /* allocate buffer_heads to read bitmaps */
1047         if (groups_per_page > 1) {
1048                 err = -ENOMEM;
1049                 i = sizeof(struct buffer_head *) * groups_per_page;
1050                 bh = kzalloc(i, GFP_NOFS);
1051                 if (bh == NULL)
1052                         goto out;
1053         } else
1054                 bh = &bhs;
1055
1056         first_group = page->index * blocks_per_page / 2;
1057
1058         /* read all groups the page covers into the cache */
1059         for (i = 0; i < groups_per_page; i++) {
1060                 struct ext4_group_desc *desc;
1061
1062                 if (first_group + i >= EXT4_SB(sb)->s_groups_count)
1063                         break;
1064
1065                 err = -EIO;
1066                 desc = ext4_get_group_desc(sb, first_group + i, NULL);
1067                 if (desc == NULL)
1068                         goto out;
1069
1070                 err = -ENOMEM;
1071                 bh[i] = sb_getblk(sb, ext4_block_bitmap(sb, desc));
1072                 if (bh[i] == NULL)
1073                         goto out;
1074
1075                 if (bh_uptodate_or_lock(bh[i]))
1076                         continue;
1077
1078                 if (desc->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)) {
1079                         ext4_init_block_bitmap(sb, bh[i],
1080                                                 first_group + i, desc);
1081                         set_buffer_uptodate(bh[i]);
1082                         unlock_buffer(bh[i]);
1083                         continue;
1084                 }
1085                 get_bh(bh[i]);
1086                 bh[i]->b_end_io = end_buffer_read_sync;
1087                 submit_bh(READ, bh[i]);
1088                 mb_debug("read bitmap for group %lu\n", first_group + i);
1089         }
1090
1091         /* wait for I/O completion */
1092         for (i = 0; i < groups_per_page && bh[i]; i++)
1093                 wait_on_buffer(bh[i]);
1094
1095         err = -EIO;
1096         for (i = 0; i < groups_per_page && bh[i]; i++)
1097                 if (!buffer_uptodate(bh[i]))
1098                         goto out;
1099
1100         first_block = page->index * blocks_per_page;
1101         for (i = 0; i < blocks_per_page; i++) {
1102                 int group;
1103                 struct ext4_group_info *grinfo;
1104
1105                 group = (first_block + i) >> 1;
1106                 if (group >= EXT4_SB(sb)->s_groups_count)
1107                         break;
1108
1109                 /*
1110                  * data carry information regarding this
1111                  * particular group in the format specified
1112                  * above
1113                  *
1114                  */
1115                 data = page_address(page) + (i * blocksize);
1116                 bitmap = bh[group - first_group]->b_data;
1117
1118                 /*
1119                  * We place the buddy block and bitmap block
1120                  * close together
1121                  */
1122                 if ((first_block + i) & 1) {
1123                         /* this is block of buddy */
1124                         BUG_ON(incore == NULL);
1125                         mb_debug("put buddy for group %u in page %lu/%x\n",
1126                                 group, page->index, i * blocksize);
1127                         memset(data, 0xff, blocksize);
1128                         grinfo = ext4_get_group_info(sb, group);
1129                         grinfo->bb_fragments = 0;
1130                         memset(grinfo->bb_counters, 0,
1131                                sizeof(unsigned short)*(sb->s_blocksize_bits+2));
1132                         /*
1133                          * incore got set to the group block bitmap below
1134                          */
1135                         ext4_mb_generate_buddy(sb, data, incore, group);
1136                         incore = NULL;
1137                 } else {
1138                         /* this is block of bitmap */
1139                         BUG_ON(incore != NULL);
1140                         mb_debug("put bitmap for group %u in page %lu/%x\n",
1141                                 group, page->index, i * blocksize);
1142
1143                         /* see comments in ext4_mb_put_pa() */
1144                         ext4_lock_group(sb, group);
1145                         memcpy(data, bitmap, blocksize);
1146
1147                         /* mark all preallocated blks used in in-core bitmap */
1148                         ext4_mb_generate_from_pa(sb, data, group);
1149                         ext4_unlock_group(sb, group);
1150
1151                         /* set incore so that the buddy information can be
1152                          * generated using this
1153                          */
1154                         incore = data;
1155                 }
1156         }
1157         SetPageUptodate(page);
1158
1159 out:
1160         if (bh) {
1161                 for (i = 0; i < groups_per_page && bh[i]; i++)
1162                         brelse(bh[i]);
1163                 if (bh != &bhs)
1164                         kfree(bh);
1165         }
1166         return err;
1167 }
1168
1169 static noinline_for_stack int
1170 ext4_mb_load_buddy(struct super_block *sb, ext4_group_t group,
1171                                         struct ext4_buddy *e4b)
1172 {
1173         struct ext4_sb_info *sbi = EXT4_SB(sb);
1174         struct inode *inode = sbi->s_buddy_cache;
1175         int blocks_per_page;
1176         int block;
1177         int pnum;
1178         int poff;
1179         struct page *page;
1180
1181         mb_debug("load group %lu\n", group);
1182
1183         blocks_per_page = PAGE_CACHE_SIZE / sb->s_blocksize;
1184
1185         e4b->bd_blkbits = sb->s_blocksize_bits;
1186         e4b->bd_info = ext4_get_group_info(sb, group);
1187         e4b->bd_sb = sb;
1188         e4b->bd_group = group;
1189         e4b->bd_buddy_page = NULL;
1190         e4b->bd_bitmap_page = NULL;
1191
1192         /*
1193          * the buddy cache inode stores the block bitmap
1194          * and buddy information in consecutive blocks.
1195          * So for each group we need two blocks.
1196          */
1197         block = group * 2;
1198         pnum = block / blocks_per_page;
1199         poff = block % blocks_per_page;
1200
1201         /* we could use find_or_create_page(), but it locks page
1202          * what we'd like to avoid in fast path ... */
1203         page = find_get_page(inode->i_mapping, pnum);
1204         if (page == NULL || !PageUptodate(page)) {
1205                 if (page)
1206                         page_cache_release(page);
1207                 page = find_or_create_page(inode->i_mapping, pnum, GFP_NOFS);
1208                 if (page) {
1209                         BUG_ON(page->mapping != inode->i_mapping);
1210                         if (!PageUptodate(page)) {
1211                                 ext4_mb_init_cache(page, NULL);
1212                                 mb_cmp_bitmaps(e4b, page_address(page) +
1213                                                (poff * sb->s_blocksize));
1214                         }
1215                         unlock_page(page);
1216                 }
1217         }
1218         if (page == NULL || !PageUptodate(page))
1219                 goto err;
1220         e4b->bd_bitmap_page = page;
1221         e4b->bd_bitmap = page_address(page) + (poff * sb->s_blocksize);
1222         mark_page_accessed(page);
1223
1224         block++;
1225         pnum = block / blocks_per_page;
1226         poff = block % blocks_per_page;
1227
1228         page = find_get_page(inode->i_mapping, pnum);
1229         if (page == NULL || !PageUptodate(page)) {
1230                 if (page)
1231                         page_cache_release(page);
1232                 page = find_or_create_page(inode->i_mapping, pnum, GFP_NOFS);
1233                 if (page) {
1234                         BUG_ON(page->mapping != inode->i_mapping);
1235                         if (!PageUptodate(page))
1236                                 ext4_mb_init_cache(page, e4b->bd_bitmap);
1237
1238                         unlock_page(page);
1239                 }
1240         }
1241         if (page == NULL || !PageUptodate(page))
1242                 goto err;
1243         e4b->bd_buddy_page = page;
1244         e4b->bd_buddy = page_address(page) + (poff * sb->s_blocksize);
1245         mark_page_accessed(page);
1246
1247         BUG_ON(e4b->bd_bitmap_page == NULL);
1248         BUG_ON(e4b->bd_buddy_page == NULL);
1249
1250         return 0;
1251
1252 err:
1253         if (e4b->bd_bitmap_page)
1254                 page_cache_release(e4b->bd_bitmap_page);
1255         if (e4b->bd_buddy_page)
1256                 page_cache_release(e4b->bd_buddy_page);
1257         e4b->bd_buddy = NULL;
1258         e4b->bd_bitmap = NULL;
1259         return -EIO;
1260 }
1261
1262 static void ext4_mb_release_desc(struct ext4_buddy *e4b)
1263 {
1264         if (e4b->bd_bitmap_page)
1265                 page_cache_release(e4b->bd_bitmap_page);
1266         if (e4b->bd_buddy_page)
1267                 page_cache_release(e4b->bd_buddy_page);
1268 }
1269
1270
1271 static int mb_find_order_for_block(struct ext4_buddy *e4b, int block)
1272 {
1273         int order = 1;
1274         void *bb;
1275
1276         BUG_ON(EXT4_MB_BITMAP(e4b) == EXT4_MB_BUDDY(e4b));
1277         BUG_ON(block >= (1 << (e4b->bd_blkbits + 3)));
1278
1279         bb = EXT4_MB_BUDDY(e4b);
1280         while (order <= e4b->bd_blkbits + 1) {
1281                 block = block >> 1;
1282                 if (!mb_test_bit(block, bb)) {
1283                         /* this block is part of buddy of order 'order' */
1284                         return order;
1285                 }
1286                 bb += 1 << (e4b->bd_blkbits - order);
1287                 order++;
1288         }
1289         return 0;
1290 }
1291
1292 static void mb_clear_bits(spinlock_t *lock, void *bm, int cur, int len)
1293 {
1294         __u32 *addr;
1295
1296         len = cur + len;
1297         while (cur < len) {
1298                 if ((cur & 31) == 0 && (len - cur) >= 32) {
1299                         /* fast path: clear whole word at once */
1300                         addr = bm + (cur >> 3);
1301                         *addr = 0;
1302                         cur += 32;
1303                         continue;
1304                 }
1305                 mb_clear_bit_atomic(lock, cur, bm);
1306                 cur++;
1307         }
1308 }
1309
1310 static void mb_set_bits(spinlock_t *lock, void *bm, int cur, int len)
1311 {
1312         __u32 *addr;
1313
1314         len = cur + len;
1315         while (cur < len) {
1316                 if ((cur & 31) == 0 && (len - cur) >= 32) {
1317                         /* fast path: set whole word at once */
1318                         addr = bm + (cur >> 3);
1319                         *addr = 0xffffffff;
1320                         cur += 32;
1321                         continue;
1322                 }
1323                 mb_set_bit_atomic(lock, cur, bm);
1324                 cur++;
1325         }
1326 }
1327
1328 static int mb_free_blocks(struct inode *inode, struct ext4_buddy *e4b,
1329                           int first, int count)
1330 {
1331         int block = 0;
1332         int max = 0;
1333         int order;
1334         void *buddy;
1335         void *buddy2;
1336         struct super_block *sb = e4b->bd_sb;
1337
1338         BUG_ON(first + count > (sb->s_blocksize << 3));
1339         BUG_ON(!ext4_is_group_locked(sb, e4b->bd_group));
1340         mb_check_buddy(e4b);
1341         mb_free_blocks_double(inode, e4b, first, count);
1342
1343         e4b->bd_info->bb_free += count;
1344         if (first < e4b->bd_info->bb_first_free)
1345                 e4b->bd_info->bb_first_free = first;
1346
1347         /* let's maintain fragments counter */
1348         if (first != 0)
1349                 block = !mb_test_bit(first - 1, EXT4_MB_BITMAP(e4b));
1350         if (first + count < EXT4_SB(sb)->s_mb_maxs[0])
1351                 max = !mb_test_bit(first + count, EXT4_MB_BITMAP(e4b));
1352         if (block && max)
1353                 e4b->bd_info->bb_fragments--;
1354         else if (!block && !max)
1355                 e4b->bd_info->bb_fragments++;
1356
1357         /* let's maintain buddy itself */
1358         while (count-- > 0) {
1359                 block = first++;
1360                 order = 0;
1361
1362                 if (!mb_test_bit(block, EXT4_MB_BITMAP(e4b))) {
1363                         ext4_fsblk_t blocknr;
1364                         blocknr = e4b->bd_group * EXT4_BLOCKS_PER_GROUP(sb);
1365                         blocknr += block;
1366                         blocknr +=
1367                             le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block);
1368
1369                         ext4_error(sb, __FUNCTION__, "double-free of inode"
1370                                    " %lu's block %llu(bit %u in group %lu)\n",
1371                                    inode ? inode->i_ino : 0, blocknr, block,
1372                                    e4b->bd_group);
1373                 }
1374                 mb_clear_bit(block, EXT4_MB_BITMAP(e4b));
1375                 e4b->bd_info->bb_counters[order]++;
1376
1377                 /* start of the buddy */
1378                 buddy = mb_find_buddy(e4b, order, &max);
1379
1380                 do {
1381                         block &= ~1UL;
1382                         if (mb_test_bit(block, buddy) ||
1383                                         mb_test_bit(block + 1, buddy))
1384                                 break;
1385
1386                         /* both the buddies are free, try to coalesce them */
1387                         buddy2 = mb_find_buddy(e4b, order + 1, &max);
1388
1389                         if (!buddy2)
1390                                 break;
1391
1392                         if (order > 0) {
1393                                 /* for special purposes, we don't set
1394                                  * free bits in bitmap */
1395                                 mb_set_bit(block, buddy);
1396                                 mb_set_bit(block + 1, buddy);
1397                         }
1398                         e4b->bd_info->bb_counters[order]--;
1399                         e4b->bd_info->bb_counters[order]--;
1400
1401                         block = block >> 1;
1402                         order++;
1403                         e4b->bd_info->bb_counters[order]++;
1404
1405                         mb_clear_bit(block, buddy2);
1406                         buddy = buddy2;
1407                 } while (1);
1408         }
1409         mb_check_buddy(e4b);
1410
1411         return 0;
1412 }
1413
1414 static int mb_find_extent(struct ext4_buddy *e4b, int order, int block,
1415                                 int needed, struct ext4_free_extent *ex)
1416 {
1417         int next = block;
1418         int max;
1419         int ord;
1420         void *buddy;
1421
1422         BUG_ON(!ext4_is_group_locked(e4b->bd_sb, e4b->bd_group));
1423         BUG_ON(ex == NULL);
1424
1425         buddy = mb_find_buddy(e4b, order, &max);
1426         BUG_ON(buddy == NULL);
1427         BUG_ON(block >= max);
1428         if (mb_test_bit(block, buddy)) {
1429                 ex->fe_len = 0;
1430                 ex->fe_start = 0;
1431                 ex->fe_group = 0;
1432                 return 0;
1433         }
1434
1435         /* FIXME dorp order completely ? */
1436         if (likely(order == 0)) {
1437                 /* find actual order */
1438                 order = mb_find_order_for_block(e4b, block);
1439                 block = block >> order;
1440         }
1441
1442         ex->fe_len = 1 << order;
1443         ex->fe_start = block << order;
1444         ex->fe_group = e4b->bd_group;
1445
1446         /* calc difference from given start */
1447         next = next - ex->fe_start;
1448         ex->fe_len -= next;
1449         ex->fe_start += next;
1450
1451         while (needed > ex->fe_len &&
1452                (buddy = mb_find_buddy(e4b, order, &max))) {
1453
1454                 if (block + 1 >= max)
1455                         break;
1456
1457                 next = (block + 1) * (1 << order);
1458                 if (mb_test_bit(next, EXT4_MB_BITMAP(e4b)))
1459                         break;
1460
1461                 ord = mb_find_order_for_block(e4b, next);
1462
1463                 order = ord;
1464                 block = next >> order;
1465                 ex->fe_len += 1 << order;
1466         }
1467
1468         BUG_ON(ex->fe_start + ex->fe_len > (1 << (e4b->bd_blkbits + 3)));
1469         return ex->fe_len;
1470 }
1471
1472 static int mb_mark_used(struct ext4_buddy *e4b, struct ext4_free_extent *ex)
1473 {
1474         int ord;
1475         int mlen = 0;
1476         int max = 0;
1477         int cur;
1478         int start = ex->fe_start;
1479         int len = ex->fe_len;
1480         unsigned ret = 0;
1481         int len0 = len;
1482         void *buddy;
1483
1484         BUG_ON(start + len > (e4b->bd_sb->s_blocksize << 3));
1485         BUG_ON(e4b->bd_group != ex->fe_group);
1486         BUG_ON(!ext4_is_group_locked(e4b->bd_sb, e4b->bd_group));
1487         mb_check_buddy(e4b);
1488         mb_mark_used_double(e4b, start, len);
1489
1490         e4b->bd_info->bb_free -= len;
1491         if (e4b->bd_info->bb_first_free == start)
1492                 e4b->bd_info->bb_first_free += len;
1493
1494         /* let's maintain fragments counter */
1495         if (start != 0)
1496                 mlen = !mb_test_bit(start - 1, EXT4_MB_BITMAP(e4b));
1497         if (start + len < EXT4_SB(e4b->bd_sb)->s_mb_maxs[0])
1498                 max = !mb_test_bit(start + len, EXT4_MB_BITMAP(e4b));
1499         if (mlen && max)
1500                 e4b->bd_info->bb_fragments++;
1501         else if (!mlen && !max)
1502                 e4b->bd_info->bb_fragments--;
1503
1504         /* let's maintain buddy itself */
1505         while (len) {
1506                 ord = mb_find_order_for_block(e4b, start);
1507
1508                 if (((start >> ord) << ord) == start && len >= (1 << ord)) {
1509                         /* the whole chunk may be allocated at once! */
1510                         mlen = 1 << ord;
1511                         buddy = mb_find_buddy(e4b, ord, &max);
1512                         BUG_ON((start >> ord) >= max);
1513                         mb_set_bit(start >> ord, buddy);
1514                         e4b->bd_info->bb_counters[ord]--;
1515                         start += mlen;
1516                         len -= mlen;
1517                         BUG_ON(len < 0);
1518                         continue;
1519                 }
1520
1521                 /* store for history */
1522                 if (ret == 0)
1523                         ret = len | (ord << 16);
1524
1525                 /* we have to split large buddy */
1526                 BUG_ON(ord <= 0);
1527                 buddy = mb_find_buddy(e4b, ord, &max);
1528                 mb_set_bit(start >> ord, buddy);
1529                 e4b->bd_info->bb_counters[ord]--;
1530
1531                 ord--;
1532                 cur = (start >> ord) & ~1U;
1533                 buddy = mb_find_buddy(e4b, ord, &max);
1534                 mb_clear_bit(cur, buddy);
1535                 mb_clear_bit(cur + 1, buddy);
1536                 e4b->bd_info->bb_counters[ord]++;
1537                 e4b->bd_info->bb_counters[ord]++;
1538         }
1539
1540         mb_set_bits(sb_bgl_lock(EXT4_SB(e4b->bd_sb), ex->fe_group),
1541                         EXT4_MB_BITMAP(e4b), ex->fe_start, len0);
1542         mb_check_buddy(e4b);
1543
1544         return ret;
1545 }
1546
1547 /*
1548  * Must be called under group lock!
1549  */
1550 static void ext4_mb_use_best_found(struct ext4_allocation_context *ac,
1551                                         struct ext4_buddy *e4b)
1552 {
1553         struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1554         int ret;
1555
1556         BUG_ON(ac->ac_b_ex.fe_group != e4b->bd_group);
1557         BUG_ON(ac->ac_status == AC_STATUS_FOUND);
1558
1559         ac->ac_b_ex.fe_len = min(ac->ac_b_ex.fe_len, ac->ac_g_ex.fe_len);
1560         ac->ac_b_ex.fe_logical = ac->ac_g_ex.fe_logical;
1561         ret = mb_mark_used(e4b, &ac->ac_b_ex);
1562
1563         /* preallocation can change ac_b_ex, thus we store actually
1564          * allocated blocks for history */
1565         ac->ac_f_ex = ac->ac_b_ex;
1566
1567         ac->ac_status = AC_STATUS_FOUND;
1568         ac->ac_tail = ret & 0xffff;
1569         ac->ac_buddy = ret >> 16;
1570
1571         /* XXXXXXX: SUCH A HORRIBLE **CK */
1572         /*FIXME!! Why ? */
1573         ac->ac_bitmap_page = e4b->bd_bitmap_page;
1574         get_page(ac->ac_bitmap_page);
1575         ac->ac_buddy_page = e4b->bd_buddy_page;
1576         get_page(ac->ac_buddy_page);
1577
1578         /* store last allocated for subsequent stream allocation */
1579         if ((ac->ac_flags & EXT4_MB_HINT_DATA)) {
1580                 spin_lock(&sbi->s_md_lock);
1581                 sbi->s_mb_last_group = ac->ac_f_ex.fe_group;
1582                 sbi->s_mb_last_start = ac->ac_f_ex.fe_start;
1583                 spin_unlock(&sbi->s_md_lock);
1584         }
1585 }
1586
1587 /*
1588  * regular allocator, for general purposes allocation
1589  */
1590
1591 static void ext4_mb_check_limits(struct ext4_allocation_context *ac,
1592                                         struct ext4_buddy *e4b,
1593                                         int finish_group)
1594 {
1595         struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1596         struct ext4_free_extent *bex = &ac->ac_b_ex;
1597         struct ext4_free_extent *gex = &ac->ac_g_ex;
1598         struct ext4_free_extent ex;
1599         int max;
1600
1601         /*
1602          * We don't want to scan for a whole year
1603          */
1604         if (ac->ac_found > sbi->s_mb_max_to_scan &&
1605                         !(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
1606                 ac->ac_status = AC_STATUS_BREAK;
1607                 return;
1608         }
1609
1610         /*
1611          * Haven't found good chunk so far, let's continue
1612          */
1613         if (bex->fe_len < gex->fe_len)
1614                 return;
1615
1616         if ((finish_group || ac->ac_found > sbi->s_mb_min_to_scan)
1617                         && bex->fe_group == e4b->bd_group) {
1618                 /* recheck chunk's availability - we don't know
1619                  * when it was found (within this lock-unlock
1620                  * period or not) */
1621                 max = mb_find_extent(e4b, 0, bex->fe_start, gex->fe_len, &ex);
1622                 if (max >= gex->fe_len) {
1623                         ext4_mb_use_best_found(ac, e4b);
1624                         return;
1625                 }
1626         }
1627 }
1628
1629 /*
1630  * The routine checks whether found extent is good enough. If it is,
1631  * then the extent gets marked used and flag is set to the context
1632  * to stop scanning. Otherwise, the extent is compared with the
1633  * previous found extent and if new one is better, then it's stored
1634  * in the context. Later, the best found extent will be used, if
1635  * mballoc can't find good enough extent.
1636  *
1637  * FIXME: real allocation policy is to be designed yet!
1638  */
1639 static void ext4_mb_measure_extent(struct ext4_allocation_context *ac,
1640                                         struct ext4_free_extent *ex,
1641                                         struct ext4_buddy *e4b)
1642 {
1643         struct ext4_free_extent *bex = &ac->ac_b_ex;
1644         struct ext4_free_extent *gex = &ac->ac_g_ex;
1645
1646         BUG_ON(ex->fe_len <= 0);
1647         BUG_ON(ex->fe_len >= EXT4_BLOCKS_PER_GROUP(ac->ac_sb));
1648         BUG_ON(ex->fe_start >= EXT4_BLOCKS_PER_GROUP(ac->ac_sb));
1649         BUG_ON(ac->ac_status != AC_STATUS_CONTINUE);
1650
1651         ac->ac_found++;
1652
1653         /*
1654          * The special case - take what you catch first
1655          */
1656         if (unlikely(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
1657                 *bex = *ex;
1658                 ext4_mb_use_best_found(ac, e4b);
1659                 return;
1660         }
1661
1662         /*
1663          * Let's check whether the chuck is good enough
1664          */
1665         if (ex->fe_len == gex->fe_len) {
1666                 *bex = *ex;
1667                 ext4_mb_use_best_found(ac, e4b);
1668                 return;
1669         }
1670
1671         /*
1672          * If this is first found extent, just store it in the context
1673          */
1674         if (bex->fe_len == 0) {
1675                 *bex = *ex;
1676                 return;
1677         }
1678
1679         /*
1680          * If new found extent is better, store it in the context
1681          */
1682         if (bex->fe_len < gex->fe_len) {
1683                 /* if the request isn't satisfied, any found extent
1684                  * larger than previous best one is better */
1685                 if (ex->fe_len > bex->fe_len)
1686                         *bex = *ex;
1687         } else if (ex->fe_len > gex->fe_len) {
1688                 /* if the request is satisfied, then we try to find
1689                  * an extent that still satisfy the request, but is
1690                  * smaller than previous one */
1691                 if (ex->fe_len < bex->fe_len)
1692                         *bex = *ex;
1693         }
1694
1695         ext4_mb_check_limits(ac, e4b, 0);
1696 }
1697
1698 static int ext4_mb_try_best_found(struct ext4_allocation_context *ac,
1699                                         struct ext4_buddy *e4b)
1700 {
1701         struct ext4_free_extent ex = ac->ac_b_ex;
1702         ext4_group_t group = ex.fe_group;
1703         int max;
1704         int err;
1705
1706         BUG_ON(ex.fe_len <= 0);
1707         err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
1708         if (err)
1709                 return err;
1710
1711         ext4_lock_group(ac->ac_sb, group);
1712         max = mb_find_extent(e4b, 0, ex.fe_start, ex.fe_len, &ex);
1713
1714         if (max > 0) {
1715                 ac->ac_b_ex = ex;
1716                 ext4_mb_use_best_found(ac, e4b);
1717         }
1718
1719         ext4_unlock_group(ac->ac_sb, group);
1720         ext4_mb_release_desc(e4b);
1721
1722         return 0;
1723 }
1724
1725 static int ext4_mb_find_by_goal(struct ext4_allocation_context *ac,
1726                                 struct ext4_buddy *e4b)
1727 {
1728         ext4_group_t group = ac->ac_g_ex.fe_group;
1729         int max;
1730         int err;
1731         struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
1732         struct ext4_super_block *es = sbi->s_es;
1733         struct ext4_free_extent ex;
1734
1735         if (!(ac->ac_flags & EXT4_MB_HINT_TRY_GOAL))
1736                 return 0;
1737
1738         err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
1739         if (err)
1740                 return err;
1741
1742         ext4_lock_group(ac->ac_sb, group);
1743         max = mb_find_extent(e4b, 0, ac->ac_g_ex.fe_start,
1744                              ac->ac_g_ex.fe_len, &ex);
1745
1746         if (max >= ac->ac_g_ex.fe_len && ac->ac_g_ex.fe_len == sbi->s_stripe) {
1747                 ext4_fsblk_t start;
1748
1749                 start = (e4b->bd_group * EXT4_BLOCKS_PER_GROUP(ac->ac_sb)) +
1750                         ex.fe_start + le32_to_cpu(es->s_first_data_block);
1751                 /* use do_div to get remainder (would be 64-bit modulo) */
1752                 if (do_div(start, sbi->s_stripe) == 0) {
1753                         ac->ac_found++;
1754                         ac->ac_b_ex = ex;
1755                         ext4_mb_use_best_found(ac, e4b);
1756                 }
1757         } else if (max >= ac->ac_g_ex.fe_len) {
1758                 BUG_ON(ex.fe_len <= 0);
1759                 BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
1760                 BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
1761                 ac->ac_found++;
1762                 ac->ac_b_ex = ex;
1763                 ext4_mb_use_best_found(ac, e4b);
1764         } else if (max > 0 && (ac->ac_flags & EXT4_MB_HINT_MERGE)) {
1765                 /* Sometimes, caller may want to merge even small
1766                  * number of blocks to an existing extent */
1767                 BUG_ON(ex.fe_len <= 0);
1768                 BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
1769                 BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
1770                 ac->ac_found++;
1771                 ac->ac_b_ex = ex;
1772                 ext4_mb_use_best_found(ac, e4b);
1773         }
1774         ext4_unlock_group(ac->ac_sb, group);
1775         ext4_mb_release_desc(e4b);
1776
1777         return 0;
1778 }
1779
1780 /*
1781  * The routine scans buddy structures (not bitmap!) from given order
1782  * to max order and tries to find big enough chunk to satisfy the req
1783  */
1784 static void ext4_mb_simple_scan_group(struct ext4_allocation_context *ac,
1785                                         struct ext4_buddy *e4b)
1786 {
1787         struct super_block *sb = ac->ac_sb;
1788         struct ext4_group_info *grp = e4b->bd_info;
1789         void *buddy;
1790         int i;
1791         int k;
1792         int max;
1793
1794         BUG_ON(ac->ac_2order <= 0);
1795         for (i = ac->ac_2order; i <= sb->s_blocksize_bits + 1; i++) {
1796                 if (grp->bb_counters[i] == 0)
1797                         continue;
1798
1799                 buddy = mb_find_buddy(e4b, i, &max);
1800                 BUG_ON(buddy == NULL);
1801
1802                 k = mb_find_next_zero_bit(buddy, max, 0);
1803                 BUG_ON(k >= max);
1804
1805                 ac->ac_found++;
1806
1807                 ac->ac_b_ex.fe_len = 1 << i;
1808                 ac->ac_b_ex.fe_start = k << i;
1809                 ac->ac_b_ex.fe_group = e4b->bd_group;
1810
1811                 ext4_mb_use_best_found(ac, e4b);
1812
1813                 BUG_ON(ac->ac_b_ex.fe_len != ac->ac_g_ex.fe_len);
1814
1815                 if (EXT4_SB(sb)->s_mb_stats)
1816                         atomic_inc(&EXT4_SB(sb)->s_bal_2orders);
1817
1818                 break;
1819         }
1820 }
1821
1822 /*
1823  * The routine scans the group and measures all found extents.
1824  * In order to optimize scanning, caller must pass number of
1825  * free blocks in the group, so the routine can know upper limit.
1826  */
1827 static void ext4_mb_complex_scan_group(struct ext4_allocation_context *ac,
1828                                         struct ext4_buddy *e4b)
1829 {
1830         struct super_block *sb = ac->ac_sb;
1831         void *bitmap = EXT4_MB_BITMAP(e4b);
1832         struct ext4_free_extent ex;
1833         int i;
1834         int free;
1835
1836         free = e4b->bd_info->bb_free;
1837         BUG_ON(free <= 0);
1838
1839         i = e4b->bd_info->bb_first_free;
1840
1841         while (free && ac->ac_status == AC_STATUS_CONTINUE) {
1842                 i = mb_find_next_zero_bit(bitmap,
1843                                                 EXT4_BLOCKS_PER_GROUP(sb), i);
1844                 if (i >= EXT4_BLOCKS_PER_GROUP(sb)) {
1845                         /*
1846                          * IF we have corrupt bitmap, we won't find any
1847                          * free blocks even though group info says we
1848                          * we have free blocks
1849                          */
1850                         ext4_error(sb, __FUNCTION__, "%d free blocks as per "
1851                                         "group info. But bitmap says 0\n",
1852                                         free);
1853                         break;
1854                 }
1855
1856                 mb_find_extent(e4b, 0, i, ac->ac_g_ex.fe_len, &ex);
1857                 BUG_ON(ex.fe_len <= 0);
1858                 if (free < ex.fe_len) {
1859                         ext4_error(sb, __FUNCTION__, "%d free blocks as per "
1860                                         "group info. But got %d blocks\n",
1861                                         free, ex.fe_len);
1862                         /*
1863                          * The number of free blocks differs. This mostly
1864                          * indicate that the bitmap is corrupt. So exit
1865                          * without claiming the space.
1866                          */
1867                         break;
1868                 }
1869
1870                 ext4_mb_measure_extent(ac, &ex, e4b);
1871
1872                 i += ex.fe_len;
1873                 free -= ex.fe_len;
1874         }
1875
1876         ext4_mb_check_limits(ac, e4b, 1);
1877 }
1878
1879 /*
1880  * This is a special case for storages like raid5
1881  * we try to find stripe-aligned chunks for stripe-size requests
1882  * XXX should do so at least for multiples of stripe size as well
1883  */
1884 static void ext4_mb_scan_aligned(struct ext4_allocation_context *ac,
1885                                  struct ext4_buddy *e4b)
1886 {
1887         struct super_block *sb = ac->ac_sb;
1888         struct ext4_sb_info *sbi = EXT4_SB(sb);
1889         void *bitmap = EXT4_MB_BITMAP(e4b);
1890         struct ext4_free_extent ex;
1891         ext4_fsblk_t first_group_block;
1892         ext4_fsblk_t a;
1893         ext4_grpblk_t i;
1894         int max;
1895
1896         BUG_ON(sbi->s_stripe == 0);
1897
1898         /* find first stripe-aligned block in group */
1899         first_group_block = e4b->bd_group * EXT4_BLOCKS_PER_GROUP(sb)
1900                 + le32_to_cpu(sbi->s_es->s_first_data_block);
1901         a = first_group_block + sbi->s_stripe - 1;
1902         do_div(a, sbi->s_stripe);
1903         i = (a * sbi->s_stripe) - first_group_block;
1904
1905         while (i < EXT4_BLOCKS_PER_GROUP(sb)) {
1906                 if (!mb_test_bit(i, bitmap)) {
1907                         max = mb_find_extent(e4b, 0, i, sbi->s_stripe, &ex);
1908                         if (max >= sbi->s_stripe) {
1909                                 ac->ac_found++;
1910                                 ac->ac_b_ex = ex;
1911                                 ext4_mb_use_best_found(ac, e4b);
1912                                 break;
1913                         }
1914                 }
1915                 i += sbi->s_stripe;
1916         }
1917 }
1918
1919 static int ext4_mb_good_group(struct ext4_allocation_context *ac,
1920                                 ext4_group_t group, int cr)
1921 {
1922         unsigned free, fragments;
1923         unsigned i, bits;
1924         struct ext4_group_desc *desc;
1925         struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
1926
1927         BUG_ON(cr < 0 || cr >= 4);
1928         BUG_ON(EXT4_MB_GRP_NEED_INIT(grp));
1929
1930         free = grp->bb_free;
1931         fragments = grp->bb_fragments;
1932         if (free == 0)
1933                 return 0;
1934         if (fragments == 0)
1935                 return 0;
1936
1937         switch (cr) {
1938         case 0:
1939                 BUG_ON(ac->ac_2order == 0);
1940                 /* If this group is uninitialized, skip it initially */
1941                 desc = ext4_get_group_desc(ac->ac_sb, group, NULL);
1942                 if (desc->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))
1943                         return 0;
1944
1945                 bits = ac->ac_sb->s_blocksize_bits + 1;
1946                 for (i = ac->ac_2order; i <= bits; i++)
1947                         if (grp->bb_counters[i] > 0)
1948                                 return 1;
1949                 break;
1950         case 1:
1951                 if ((free / fragments) >= ac->ac_g_ex.fe_len)
1952                         return 1;
1953                 break;
1954         case 2:
1955                 if (free >= ac->ac_g_ex.fe_len)
1956                         return 1;
1957                 break;
1958         case 3:
1959                 return 1;
1960         default:
1961                 BUG();
1962         }
1963
1964         return 0;
1965 }
1966
1967 static noinline_for_stack int
1968 ext4_mb_regular_allocator(struct ext4_allocation_context *ac)
1969 {
1970         ext4_group_t group;
1971         ext4_group_t i;
1972         int cr;
1973         int err = 0;
1974         int bsbits;
1975         struct ext4_sb_info *sbi;
1976         struct super_block *sb;
1977         struct ext4_buddy e4b;
1978         loff_t size, isize;
1979
1980         sb = ac->ac_sb;
1981         sbi = EXT4_SB(sb);
1982         BUG_ON(ac->ac_status == AC_STATUS_FOUND);
1983
1984         /* first, try the goal */
1985         err = ext4_mb_find_by_goal(ac, &e4b);
1986         if (err || ac->ac_status == AC_STATUS_FOUND)
1987                 goto out;
1988
1989         if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
1990                 goto out;
1991
1992         /*
1993          * ac->ac2_order is set only if the fe_len is a power of 2
1994          * if ac2_order is set we also set criteria to 0 so that we
1995          * try exact allocation using buddy.
1996          */
1997         i = fls(ac->ac_g_ex.fe_len);
1998         ac->ac_2order = 0;
1999         /*
2000          * We search using buddy data only if the order of the request
2001          * is greater than equal to the sbi_s_mb_order2_reqs
2002          * You can tune it via /proc/fs/ext4/<partition>/order2_req
2003          */
2004         if (i >= sbi->s_mb_order2_reqs) {
2005                 /*
2006                  * This should tell if fe_len is exactly power of 2
2007                  */
2008                 if ((ac->ac_g_ex.fe_len & (~(1 << (i - 1)))) == 0)
2009                         ac->ac_2order = i - 1;
2010         }
2011
2012         bsbits = ac->ac_sb->s_blocksize_bits;
2013         /* if stream allocation is enabled, use global goal */
2014         size = ac->ac_o_ex.fe_logical + ac->ac_o_ex.fe_len;
2015         isize = i_size_read(ac->ac_inode) >> bsbits;
2016         if (size < isize)
2017                 size = isize;
2018
2019         if (size < sbi->s_mb_stream_request &&
2020                         (ac->ac_flags & EXT4_MB_HINT_DATA)) {
2021                 /* TBD: may be hot point */
2022                 spin_lock(&sbi->s_md_lock);
2023                 ac->ac_g_ex.fe_group = sbi->s_mb_last_group;
2024                 ac->ac_g_ex.fe_start = sbi->s_mb_last_start;
2025                 spin_unlock(&sbi->s_md_lock);
2026         }
2027
2028         /* searching for the right group start from the goal value specified */
2029         group = ac->ac_g_ex.fe_group;
2030
2031         /* Let's just scan groups to find more-less suitable blocks */
2032         cr = ac->ac_2order ? 0 : 1;
2033         /*
2034          * cr == 0 try to get exact allocation,
2035          * cr == 3  try to get anything
2036          */
2037 repeat:
2038         for (; cr < 4 && ac->ac_status == AC_STATUS_CONTINUE; cr++) {
2039                 ac->ac_criteria = cr;
2040                 for (i = 0; i < EXT4_SB(sb)->s_groups_count; group++, i++) {
2041                         struct ext4_group_info *grp;
2042                         struct ext4_group_desc *desc;
2043
2044                         if (group == EXT4_SB(sb)->s_groups_count)
2045                                 group = 0;
2046
2047                         /* quick check to skip empty groups */
2048                         grp = ext4_get_group_info(ac->ac_sb, group);
2049                         if (grp->bb_free == 0)
2050                                 continue;
2051
2052                         /*
2053                          * if the group is already init we check whether it is
2054                          * a good group and if not we don't load the buddy
2055                          */
2056                         if (EXT4_MB_GRP_NEED_INIT(grp)) {
2057                                 /*
2058                                  * we need full data about the group
2059                                  * to make a good selection
2060                                  */
2061                                 err = ext4_mb_load_buddy(sb, group, &e4b);
2062                                 if (err)
2063                                         goto out;
2064                                 ext4_mb_release_desc(&e4b);
2065                         }
2066
2067                         /*
2068                          * If the particular group doesn't satisfy our
2069                          * criteria we continue with the next group
2070                          */
2071                         if (!ext4_mb_good_group(ac, group, cr))
2072                                 continue;
2073
2074                         err = ext4_mb_load_buddy(sb, group, &e4b);
2075                         if (err)
2076                                 goto out;
2077
2078                         ext4_lock_group(sb, group);
2079                         if (!ext4_mb_good_group(ac, group, cr)) {
2080                                 /* someone did allocation from this group */
2081                                 ext4_unlock_group(sb, group);
2082                                 ext4_mb_release_desc(&e4b);
2083                                 continue;
2084                         }
2085
2086                         ac->ac_groups_scanned++;
2087                         desc = ext4_get_group_desc(sb, group, NULL);
2088                         if (cr == 0 || (desc->bg_flags &
2089                                         cpu_to_le16(EXT4_BG_BLOCK_UNINIT) &&
2090                                         ac->ac_2order != 0))
2091                                 ext4_mb_simple_scan_group(ac, &e4b);
2092                         else if (cr == 1 &&
2093                                         ac->ac_g_ex.fe_len == sbi->s_stripe)
2094                                 ext4_mb_scan_aligned(ac, &e4b);
2095                         else
2096                                 ext4_mb_complex_scan_group(ac, &e4b);
2097
2098                         ext4_unlock_group(sb, group);
2099                         ext4_mb_release_desc(&e4b);
2100
2101                         if (ac->ac_status != AC_STATUS_CONTINUE)
2102                                 break;
2103                 }
2104         }
2105
2106         if (ac->ac_b_ex.fe_len > 0 && ac->ac_status != AC_STATUS_FOUND &&
2107             !(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
2108                 /*
2109                  * We've been searching too long. Let's try to allocate
2110                  * the best chunk we've found so far
2111                  */
2112
2113                 ext4_mb_try_best_found(ac, &e4b);
2114                 if (ac->ac_status != AC_STATUS_FOUND) {
2115                         /*
2116                          * Someone more lucky has already allocated it.
2117                          * The only thing we can do is just take first
2118                          * found block(s)
2119                         printk(KERN_DEBUG "EXT4-fs: someone won our chunk\n");
2120                          */
2121                         ac->ac_b_ex.fe_group = 0;
2122                         ac->ac_b_ex.fe_start = 0;
2123                         ac->ac_b_ex.fe_len = 0;
2124                         ac->ac_status = AC_STATUS_CONTINUE;
2125                         ac->ac_flags |= EXT4_MB_HINT_FIRST;
2126                         cr = 3;
2127                         atomic_inc(&sbi->s_mb_lost_chunks);
2128                         goto repeat;
2129                 }
2130         }
2131 out:
2132         return err;
2133 }
2134
2135 #ifdef EXT4_MB_HISTORY
2136 struct ext4_mb_proc_session {
2137         struct ext4_mb_history *history;
2138         struct super_block *sb;
2139         int start;
2140         int max;
2141 };
2142
2143 static void *ext4_mb_history_skip_empty(struct ext4_mb_proc_session *s,
2144                                         struct ext4_mb_history *hs,
2145                                         int first)
2146 {
2147         if (hs == s->history + s->max)
2148                 hs = s->history;
2149         if (!first && hs == s->history + s->start)
2150                 return NULL;
2151         while (hs->orig.fe_len == 0) {
2152                 hs++;
2153                 if (hs == s->history + s->max)
2154                         hs = s->history;
2155                 if (hs == s->history + s->start)
2156                         return NULL;
2157         }
2158         return hs;
2159 }
2160
2161 static void *ext4_mb_seq_history_start(struct seq_file *seq, loff_t *pos)
2162 {
2163         struct ext4_mb_proc_session *s = seq->private;
2164         struct ext4_mb_history *hs;
2165         int l = *pos;
2166
2167         if (l == 0)
2168                 return SEQ_START_TOKEN;
2169         hs = ext4_mb_history_skip_empty(s, s->history + s->start, 1);
2170         if (!hs)
2171                 return NULL;
2172         while (--l && (hs = ext4_mb_history_skip_empty(s, ++hs, 0)) != NULL);
2173         return hs;
2174 }
2175
2176 static void *ext4_mb_seq_history_next(struct seq_file *seq, void *v,
2177                                       loff_t *pos)
2178 {
2179         struct ext4_mb_proc_session *s = seq->private;
2180         struct ext4_mb_history *hs = v;
2181
2182         ++*pos;
2183         if (v == SEQ_START_TOKEN)
2184                 return ext4_mb_history_skip_empty(s, s->history + s->start, 1);
2185         else
2186                 return ext4_mb_history_skip_empty(s, ++hs, 0);
2187 }
2188
2189 static int ext4_mb_seq_history_show(struct seq_file *seq, void *v)
2190 {
2191         char buf[25], buf2[25], buf3[25], *fmt;
2192         struct ext4_mb_history *hs = v;
2193
2194         if (v == SEQ_START_TOKEN) {
2195                 seq_printf(seq, "%-5s %-8s %-23s %-23s %-23s %-5s "
2196                                 "%-5s %-2s %-5s %-5s %-5s %-6s\n",
2197                           "pid", "inode", "original", "goal", "result", "found",
2198                            "grps", "cr", "flags", "merge", "tail", "broken");
2199                 return 0;
2200         }
2201
2202         if (hs->op == EXT4_MB_HISTORY_ALLOC) {
2203                 fmt = "%-5u %-8u %-23s %-23s %-23s %-5u %-5u %-2u "
2204                         "%-5u %-5s %-5u %-6u\n";
2205                 sprintf(buf2, "%lu/%d/%u@%u", hs->result.fe_group,
2206                         hs->result.fe_start, hs->result.fe_len,
2207                         hs->result.fe_logical);
2208                 sprintf(buf, "%lu/%d/%u@%u", hs->orig.fe_group,
2209                         hs->orig.fe_start, hs->orig.fe_len,
2210                         hs->orig.fe_logical);
2211                 sprintf(buf3, "%lu/%d/%u@%u", hs->goal.fe_group,
2212                         hs->goal.fe_start, hs->goal.fe_len,
2213                         hs->goal.fe_logical);
2214                 seq_printf(seq, fmt, hs->pid, hs->ino, buf, buf3, buf2,
2215                                 hs->found, hs->groups, hs->cr, hs->flags,
2216                                 hs->merged ? "M" : "", hs->tail,
2217                                 hs->buddy ? 1 << hs->buddy : 0);
2218         } else if (hs->op == EXT4_MB_HISTORY_PREALLOC) {
2219                 fmt = "%-5u %-8u %-23s %-23s %-23s\n";
2220                 sprintf(buf2, "%lu/%d/%u@%u", hs->result.fe_group,
2221                         hs->result.fe_start, hs->result.fe_len,
2222                         hs->result.fe_logical);
2223                 sprintf(buf, "%lu/%d/%u@%u", hs->orig.fe_group,
2224                         hs->orig.fe_start, hs->orig.fe_len,
2225                         hs->orig.fe_logical);
2226                 seq_printf(seq, fmt, hs->pid, hs->ino, buf, "", buf2);
2227         } else if (hs->op == EXT4_MB_HISTORY_DISCARD) {
2228                 sprintf(buf2, "%lu/%d/%u", hs->result.fe_group,
2229                         hs->result.fe_start, hs->result.fe_len);
2230                 seq_printf(seq, "%-5u %-8u %-23s discard\n",
2231                                 hs->pid, hs->ino, buf2);
2232         } else if (hs->op == EXT4_MB_HISTORY_FREE) {
2233                 sprintf(buf2, "%lu/%d/%u", hs->result.fe_group,
2234                         hs->result.fe_start, hs->result.fe_len);
2235                 seq_printf(seq, "%-5u %-8u %-23s free\n",
2236                                 hs->pid, hs->ino, buf2);
2237         }
2238         return 0;
2239 }
2240
2241 static void ext4_mb_seq_history_stop(struct seq_file *seq, void *v)
2242 {
2243 }
2244
2245 static struct seq_operations ext4_mb_seq_history_ops = {
2246         .start  = ext4_mb_seq_history_start,
2247         .next   = ext4_mb_seq_history_next,
2248         .stop   = ext4_mb_seq_history_stop,
2249         .show   = ext4_mb_seq_history_show,
2250 };
2251
2252 static int ext4_mb_seq_history_open(struct inode *inode, struct file *file)
2253 {
2254         struct super_block *sb = PDE(inode)->data;
2255         struct ext4_sb_info *sbi = EXT4_SB(sb);
2256         struct ext4_mb_proc_session *s;
2257         int rc;
2258         int size;
2259
2260         s = kmalloc(sizeof(*s), GFP_KERNEL);
2261         if (s == NULL)
2262                 return -ENOMEM;
2263         s->sb = sb;
2264         size = sizeof(struct ext4_mb_history) * sbi->s_mb_history_max;
2265         s->history = kmalloc(size, GFP_KERNEL);
2266         if (s->history == NULL) {
2267                 kfree(s);
2268                 return -ENOMEM;
2269         }
2270
2271         spin_lock(&sbi->s_mb_history_lock);
2272         memcpy(s->history, sbi->s_mb_history, size);
2273         s->max = sbi->s_mb_history_max;
2274         s->start = sbi->s_mb_history_cur % s->max;
2275         spin_unlock(&sbi->s_mb_history_lock);
2276
2277         rc = seq_open(file, &ext4_mb_seq_history_ops);
2278         if (rc == 0) {
2279                 struct seq_file *m = (struct seq_file *)file->private_data;
2280                 m->private = s;
2281         } else {
2282                 kfree(s->history);
2283                 kfree(s);
2284         }
2285         return rc;
2286
2287 }
2288
2289 static int ext4_mb_seq_history_release(struct inode *inode, struct file *file)
2290 {
2291         struct seq_file *seq = (struct seq_file *)file->private_data;
2292         struct ext4_mb_proc_session *s = seq->private;
2293         kfree(s->history);
2294         kfree(s);
2295         return seq_release(inode, file);
2296 }
2297
2298 static ssize_t ext4_mb_seq_history_write(struct file *file,
2299                                 const char __user *buffer,
2300                                 size_t count, loff_t *ppos)
2301 {
2302         struct seq_file *seq = (struct seq_file *)file->private_data;
2303         struct ext4_mb_proc_session *s = seq->private;
2304         struct super_block *sb = s->sb;
2305         char str[32];
2306         int value;
2307
2308         if (count >= sizeof(str)) {
2309                 printk(KERN_ERR "EXT4-fs: %s string too long, max %u bytes\n",
2310                                 "mb_history", (int)sizeof(str));
2311                 return -EOVERFLOW;
2312         }
2313
2314         if (copy_from_user(str, buffer, count))
2315                 return -EFAULT;
2316
2317         value = simple_strtol(str, NULL, 0);
2318         if (value < 0)
2319                 return -ERANGE;
2320         EXT4_SB(sb)->s_mb_history_filter = value;
2321
2322         return count;
2323 }
2324
2325 static struct file_operations ext4_mb_seq_history_fops = {
2326         .owner          = THIS_MODULE,
2327         .open           = ext4_mb_seq_history_open,
2328         .read           = seq_read,
2329         .write          = ext4_mb_seq_history_write,
2330         .llseek         = seq_lseek,
2331         .release        = ext4_mb_seq_history_release,
2332 };
2333
2334 static void *ext4_mb_seq_groups_start(struct seq_file *seq, loff_t *pos)
2335 {
2336         struct super_block *sb = seq->private;
2337         struct ext4_sb_info *sbi = EXT4_SB(sb);
2338         ext4_group_t group;
2339
2340         if (*pos < 0 || *pos >= sbi->s_groups_count)
2341                 return NULL;
2342
2343         group = *pos + 1;
2344         return (void *) group;
2345 }
2346
2347 static void *ext4_mb_seq_groups_next(struct seq_file *seq, void *v, loff_t *pos)
2348 {
2349         struct super_block *sb = seq->private;
2350         struct ext4_sb_info *sbi = EXT4_SB(sb);
2351         ext4_group_t group;
2352
2353         ++*pos;
2354         if (*pos < 0 || *pos >= sbi->s_groups_count)
2355                 return NULL;
2356         group = *pos + 1;
2357         return (void *) group;;
2358 }
2359
2360 static int ext4_mb_seq_groups_show(struct seq_file *seq, void *v)
2361 {
2362         struct super_block *sb = seq->private;
2363         long group = (long) v;
2364         int i;
2365         int err;
2366         struct ext4_buddy e4b;
2367         struct sg {
2368                 struct ext4_group_info info;
2369                 unsigned short counters[16];
2370         } sg;
2371
2372         group--;
2373         if (group == 0)
2374                 seq_printf(seq, "#%-5s: %-5s %-5s %-5s "
2375                                 "[ %-5s %-5s %-5s %-5s %-5s %-5s %-5s "
2376                                   "%-5s %-5s %-5s %-5s %-5s %-5s %-5s ]\n",
2377                            "group", "free", "frags", "first",
2378                            "2^0", "2^1", "2^2", "2^3", "2^4", "2^5", "2^6",
2379                            "2^7", "2^8", "2^9", "2^10", "2^11", "2^12", "2^13");
2380
2381         i = (sb->s_blocksize_bits + 2) * sizeof(sg.info.bb_counters[0]) +
2382                 sizeof(struct ext4_group_info);
2383         err = ext4_mb_load_buddy(sb, group, &e4b);
2384         if (err) {
2385                 seq_printf(seq, "#%-5lu: I/O error\n", group);
2386                 return 0;
2387         }
2388         ext4_lock_group(sb, group);
2389         memcpy(&sg, ext4_get_group_info(sb, group), i);
2390         ext4_unlock_group(sb, group);
2391         ext4_mb_release_desc(&e4b);
2392
2393         seq_printf(seq, "#%-5lu: %-5u %-5u %-5u [", group, sg.info.bb_free,
2394                         sg.info.bb_fragments, sg.info.bb_first_free);
2395         for (i = 0; i <= 13; i++)
2396                 seq_printf(seq, " %-5u", i <= sb->s_blocksize_bits + 1 ?
2397                                 sg.info.bb_counters[i] : 0);
2398         seq_printf(seq, " ]\n");
2399
2400         return 0;
2401 }
2402
2403 static void ext4_mb_seq_groups_stop(struct seq_file *seq, void *v)
2404 {
2405 }
2406
2407 static struct seq_operations ext4_mb_seq_groups_ops = {
2408         .start  = ext4_mb_seq_groups_start,
2409         .next   = ext4_mb_seq_groups_next,
2410         .stop   = ext4_mb_seq_groups_stop,
2411         .show   = ext4_mb_seq_groups_show,
2412 };
2413
2414 static int ext4_mb_seq_groups_open(struct inode *inode, struct file *file)
2415 {
2416         struct super_block *sb = PDE(inode)->data;
2417         int rc;
2418
2419         rc = seq_open(file, &ext4_mb_seq_groups_ops);
2420         if (rc == 0) {
2421                 struct seq_file *m = (struct seq_file *)file->private_data;
2422                 m->private = sb;
2423         }
2424         return rc;
2425
2426 }
2427
2428 static struct file_operations ext4_mb_seq_groups_fops = {
2429         .owner          = THIS_MODULE,
2430         .open           = ext4_mb_seq_groups_open,
2431         .read           = seq_read,
2432         .llseek         = seq_lseek,
2433         .release        = seq_release,
2434 };
2435
2436 static void ext4_mb_history_release(struct super_block *sb)
2437 {
2438         struct ext4_sb_info *sbi = EXT4_SB(sb);
2439
2440         remove_proc_entry("mb_groups", sbi->s_mb_proc);
2441         remove_proc_entry("mb_history", sbi->s_mb_proc);
2442
2443         kfree(sbi->s_mb_history);
2444 }
2445
2446 static void ext4_mb_history_init(struct super_block *sb)
2447 {
2448         struct ext4_sb_info *sbi = EXT4_SB(sb);
2449         int i;
2450
2451         if (sbi->s_mb_proc != NULL) {
2452                 proc_create_data("mb_history", S_IRUGO, sbi->s_mb_proc,
2453                                  &ext4_mb_seq_history_fops, sb);
2454                 proc_create_data("mb_groups", S_IRUGO, sbi->s_mb_proc,
2455                                  &ext4_mb_seq_groups_fops, sb);
2456         }
2457
2458         sbi->s_mb_history_max = 1000;
2459         sbi->s_mb_history_cur = 0;
2460         spin_lock_init(&sbi->s_mb_history_lock);
2461         i = sbi->s_mb_history_max * sizeof(struct ext4_mb_history);
2462         sbi->s_mb_history = kmalloc(i, GFP_KERNEL);
2463         if (likely(sbi->s_mb_history != NULL))
2464                 memset(sbi->s_mb_history, 0, i);
2465         /* if we can't allocate history, then we simple won't use it */
2466 }
2467
2468 static noinline_for_stack void
2469 ext4_mb_store_history(struct ext4_allocation_context *ac)
2470 {
2471         struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
2472         struct ext4_mb_history h;
2473
2474         if (unlikely(sbi->s_mb_history == NULL))
2475                 return;
2476
2477         if (!(ac->ac_op & sbi->s_mb_history_filter))
2478                 return;
2479
2480         h.op = ac->ac_op;
2481         h.pid = current->pid;
2482         h.ino = ac->ac_inode ? ac->ac_inode->i_ino : 0;
2483         h.orig = ac->ac_o_ex;
2484         h.result = ac->ac_b_ex;
2485         h.flags = ac->ac_flags;
2486         h.found = ac->ac_found;
2487         h.groups = ac->ac_groups_scanned;
2488         h.cr = ac->ac_criteria;
2489         h.tail = ac->ac_tail;
2490         h.buddy = ac->ac_buddy;
2491         h.merged = 0;
2492         if (ac->ac_op == EXT4_MB_HISTORY_ALLOC) {
2493                 if (ac->ac_g_ex.fe_start == ac->ac_b_ex.fe_start &&
2494                                 ac->ac_g_ex.fe_group == ac->ac_b_ex.fe_group)
2495                         h.merged = 1;
2496                 h.goal = ac->ac_g_ex;
2497                 h.result = ac->ac_f_ex;
2498         }
2499
2500         spin_lock(&sbi->s_mb_history_lock);
2501         memcpy(sbi->s_mb_history + sbi->s_mb_history_cur, &h, sizeof(h));
2502         if (++sbi->s_mb_history_cur >= sbi->s_mb_history_max)
2503                 sbi->s_mb_history_cur = 0;
2504         spin_unlock(&sbi->s_mb_history_lock);
2505 }
2506
2507 #else
2508 #define ext4_mb_history_release(sb)
2509 #define ext4_mb_history_init(sb)
2510 #endif
2511
2512 static int ext4_mb_init_backend(struct super_block *sb)
2513 {
2514         ext4_group_t i;
2515         int j, len, metalen;
2516         struct ext4_sb_info *sbi = EXT4_SB(sb);
2517         int num_meta_group_infos =
2518                 (sbi->s_groups_count + EXT4_DESC_PER_BLOCK(sb) - 1) >>
2519                         EXT4_DESC_PER_BLOCK_BITS(sb);
2520         struct ext4_group_info **meta_group_info;
2521
2522         /* An 8TB filesystem with 64-bit pointers requires a 4096 byte
2523          * kmalloc. A 128kb malloc should suffice for a 256TB filesystem.
2524          * So a two level scheme suffices for now. */
2525         sbi->s_group_info = kmalloc(sizeof(*sbi->s_group_info) *
2526                                     num_meta_group_infos, GFP_KERNEL);
2527         if (sbi->s_group_info == NULL) {
2528                 printk(KERN_ERR "EXT4-fs: can't allocate buddy meta group\n");
2529                 return -ENOMEM;
2530         }
2531         sbi->s_buddy_cache = new_inode(sb);
2532         if (sbi->s_buddy_cache == NULL) {
2533                 printk(KERN_ERR "EXT4-fs: can't get new inode\n");
2534                 goto err_freesgi;
2535         }
2536         EXT4_I(sbi->s_buddy_cache)->i_disksize = 0;
2537
2538         metalen = sizeof(*meta_group_info) << EXT4_DESC_PER_BLOCK_BITS(sb);
2539         for (i = 0; i < num_meta_group_infos; i++) {
2540                 if ((i + 1) == num_meta_group_infos)
2541                         metalen = sizeof(*meta_group_info) *
2542                                 (sbi->s_groups_count -
2543                                         (i << EXT4_DESC_PER_BLOCK_BITS(sb)));
2544                 meta_group_info = kmalloc(metalen, GFP_KERNEL);
2545                 if (meta_group_info == NULL) {
2546                         printk(KERN_ERR "EXT4-fs: can't allocate mem for a "
2547                                "buddy group\n");
2548                         goto err_freemeta;
2549                 }
2550                 sbi->s_group_info[i] = meta_group_info;
2551         }
2552
2553         /*
2554          * calculate needed size. if change bb_counters size,
2555          * don't forget about ext4_mb_generate_buddy()
2556          */
2557         len = sizeof(struct ext4_group_info);
2558         len += sizeof(unsigned short) * (sb->s_blocksize_bits + 2);
2559         for (i = 0; i < sbi->s_groups_count; i++) {
2560                 struct ext4_group_desc *desc;
2561
2562                 meta_group_info =
2563                         sbi->s_group_info[i >> EXT4_DESC_PER_BLOCK_BITS(sb)];
2564                 j = i & (EXT4_DESC_PER_BLOCK(sb) - 1);
2565
2566                 meta_group_info[j] = kzalloc(len, GFP_KERNEL);
2567                 if (meta_group_info[j] == NULL) {
2568                         printk(KERN_ERR "EXT4-fs: can't allocate buddy mem\n");
2569                         i--;
2570                         goto err_freebuddy;
2571                 }
2572                 desc = ext4_get_group_desc(sb, i, NULL);
2573                 if (desc == NULL) {
2574                         printk(KERN_ERR
2575                                 "EXT4-fs: can't read descriptor %lu\n", i);
2576                         goto err_freebuddy;
2577                 }
2578                 memset(meta_group_info[j], 0, len);
2579                 set_bit(EXT4_GROUP_INFO_NEED_INIT_BIT,
2580                         &(meta_group_info[j]->bb_state));
2581
2582                 /*
2583                  * initialize bb_free to be able to skip
2584                  * empty groups without initialization
2585                  */
2586                 if (desc->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)) {
2587                         meta_group_info[j]->bb_free =
2588                                 ext4_free_blocks_after_init(sb, i, desc);
2589                 } else {
2590                         meta_group_info[j]->bb_free =
2591                                 le16_to_cpu(desc->bg_free_blocks_count);
2592                 }
2593
2594                 INIT_LIST_HEAD(&meta_group_info[j]->bb_prealloc_list);
2595
2596 #ifdef DOUBLE_CHECK
2597                 {
2598                         struct buffer_head *bh;
2599                         meta_group_info[j]->bb_bitmap =
2600                                 kmalloc(sb->s_blocksize, GFP_KERNEL);
2601                         BUG_ON(meta_group_info[j]->bb_bitmap == NULL);
2602                         bh = read_block_bitmap(sb, i);
2603                         BUG_ON(bh == NULL);
2604                         memcpy(meta_group_info[j]->bb_bitmap, bh->b_data,
2605                                         sb->s_blocksize);
2606                         put_bh(bh);
2607                 }
2608 #endif
2609
2610         }
2611
2612         return 0;
2613
2614 err_freebuddy:
2615         while (i >= 0) {
2616                 kfree(ext4_get_group_info(sb, i));
2617                 i--;
2618         }
2619         i = num_meta_group_infos;
2620 err_freemeta:
2621         while (--i >= 0)
2622                 kfree(sbi->s_group_info[i]);
2623         iput(sbi->s_buddy_cache);
2624 err_freesgi:
2625         kfree(sbi->s_group_info);
2626         return -ENOMEM;
2627 }
2628
2629 int ext4_mb_init(struct super_block *sb, int needs_recovery)
2630 {
2631         struct ext4_sb_info *sbi = EXT4_SB(sb);
2632         unsigned i;
2633         unsigned offset;
2634         unsigned max;
2635
2636         if (!test_opt(sb, MBALLOC))
2637                 return 0;
2638
2639         i = (sb->s_blocksize_bits + 2) * sizeof(unsigned short);
2640
2641         sbi->s_mb_offsets = kmalloc(i, GFP_KERNEL);
2642         if (sbi->s_mb_offsets == NULL) {
2643                 clear_opt(sbi->s_mount_opt, MBALLOC);
2644                 return -ENOMEM;
2645         }
2646         sbi->s_mb_maxs = kmalloc(i, GFP_KERNEL);
2647         if (sbi->s_mb_maxs == NULL) {
2648                 clear_opt(sbi->s_mount_opt, MBALLOC);
2649                 kfree(sbi->s_mb_maxs);
2650                 return -ENOMEM;
2651         }
2652
2653         /* order 0 is regular bitmap */
2654         sbi->s_mb_maxs[0] = sb->s_blocksize << 3;
2655         sbi->s_mb_offsets[0] = 0;
2656
2657         i = 1;
2658         offset = 0;
2659         max = sb->s_blocksize << 2;
2660         do {
2661                 sbi->s_mb_offsets[i] = offset;
2662                 sbi->s_mb_maxs[i] = max;
2663                 offset += 1 << (sb->s_blocksize_bits - i);
2664                 max = max >> 1;
2665                 i++;
2666         } while (i <= sb->s_blocksize_bits + 1);
2667
2668         /* init file for buddy data */
2669         i = ext4_mb_init_backend(sb);
2670         if (i) {
2671                 clear_opt(sbi->s_mount_opt, MBALLOC);
2672                 kfree(sbi->s_mb_offsets);
2673                 kfree(sbi->s_mb_maxs);
2674                 return i;
2675         }
2676
2677         spin_lock_init(&sbi->s_md_lock);
2678         INIT_LIST_HEAD(&sbi->s_active_transaction);
2679         INIT_LIST_HEAD(&sbi->s_closed_transaction);
2680         INIT_LIST_HEAD(&sbi->s_committed_transaction);
2681         spin_lock_init(&sbi->s_bal_lock);
2682
2683         sbi->s_mb_max_to_scan = MB_DEFAULT_MAX_TO_SCAN;
2684         sbi->s_mb_min_to_scan = MB_DEFAULT_MIN_TO_SCAN;
2685         sbi->s_mb_stats = MB_DEFAULT_STATS;
2686         sbi->s_mb_stream_request = MB_DEFAULT_STREAM_THRESHOLD;
2687         sbi->s_mb_order2_reqs = MB_DEFAULT_ORDER2_REQS;
2688         sbi->s_mb_history_filter = EXT4_MB_HISTORY_DEFAULT;
2689         sbi->s_mb_group_prealloc = MB_DEFAULT_GROUP_PREALLOC;
2690
2691         i = sizeof(struct ext4_locality_group) * NR_CPUS;
2692         sbi->s_locality_groups = kmalloc(i, GFP_KERNEL);
2693         if (sbi->s_locality_groups == NULL) {
2694                 clear_opt(sbi->s_mount_opt, MBALLOC);
2695                 kfree(sbi->s_mb_offsets);
2696                 kfree(sbi->s_mb_maxs);
2697                 return -ENOMEM;
2698         }
2699         for (i = 0; i < NR_CPUS; i++) {
2700                 struct ext4_locality_group *lg;
2701                 lg = &sbi->s_locality_groups[i];
2702                 mutex_init(&lg->lg_mutex);
2703                 INIT_LIST_HEAD(&lg->lg_prealloc_list);
2704                 spin_lock_init(&lg->lg_prealloc_lock);
2705         }
2706
2707         ext4_mb_init_per_dev_proc(sb);
2708         ext4_mb_history_init(sb);
2709
2710         printk("EXT4-fs: mballoc enabled\n");
2711         return 0;
2712 }
2713
2714 /* need to called with ext4 group lock (ext4_lock_group) */
2715 static void ext4_mb_cleanup_pa(struct ext4_group_info *grp)
2716 {
2717         struct ext4_prealloc_space *pa;
2718         struct list_head *cur, *tmp;
2719         int count = 0;
2720
2721         list_for_each_safe(cur, tmp, &grp->bb_prealloc_list) {
2722                 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
2723                 list_del(&pa->pa_group_list);
2724                 count++;
2725                 kfree(pa);
2726         }
2727         if (count)
2728                 mb_debug("mballoc: %u PAs left\n", count);
2729
2730 }
2731
2732 int ext4_mb_release(struct super_block *sb)
2733 {
2734         ext4_group_t i;
2735         int num_meta_group_infos;
2736         struct ext4_group_info *grinfo;
2737         struct ext4_sb_info *sbi = EXT4_SB(sb);
2738
2739         if (!test_opt(sb, MBALLOC))
2740                 return 0;
2741
2742         /* release freed, non-committed blocks */
2743         spin_lock(&sbi->s_md_lock);
2744         list_splice_init(&sbi->s_closed_transaction,
2745                         &sbi->s_committed_transaction);
2746         list_splice_init(&sbi->s_active_transaction,
2747                         &sbi->s_committed_transaction);
2748         spin_unlock(&sbi->s_md_lock);
2749         ext4_mb_free_committed_blocks(sb);
2750
2751         if (sbi->s_group_info) {
2752                 for (i = 0; i < sbi->s_groups_count; i++) {
2753                         grinfo = ext4_get_group_info(sb, i);
2754 #ifdef DOUBLE_CHECK
2755                         kfree(grinfo->bb_bitmap);
2756 #endif
2757                         ext4_lock_group(sb, i);
2758                         ext4_mb_cleanup_pa(grinfo);
2759                         ext4_unlock_group(sb, i);
2760                         kfree(grinfo);
2761                 }
2762                 num_meta_group_infos = (sbi->s_groups_count +
2763                                 EXT4_DESC_PER_BLOCK(sb) - 1) >>
2764                         EXT4_DESC_PER_BLOCK_BITS(sb);
2765                 for (i = 0; i < num_meta_group_infos; i++)
2766                         kfree(sbi->s_group_info[i]);
2767                 kfree(sbi->s_group_info);
2768         }
2769         kfree(sbi->s_mb_offsets);
2770         kfree(sbi->s_mb_maxs);
2771         if (sbi->s_buddy_cache)
2772                 iput(sbi->s_buddy_cache);
2773         if (sbi->s_mb_stats) {
2774                 printk(KERN_INFO
2775                        "EXT4-fs: mballoc: %u blocks %u reqs (%u success)\n",
2776                                 atomic_read(&sbi->s_bal_allocated),
2777                                 atomic_read(&sbi->s_bal_reqs),
2778                                 atomic_read(&sbi->s_bal_success));
2779                 printk(KERN_INFO
2780                       "EXT4-fs: mballoc: %u extents scanned, %u goal hits, "
2781                                 "%u 2^N hits, %u breaks, %u lost\n",
2782                                 atomic_read(&sbi->s_bal_ex_scanned),
2783                                 atomic_read(&sbi->s_bal_goals),
2784                                 atomic_read(&sbi->s_bal_2orders),
2785                                 atomic_read(&sbi->s_bal_breaks),
2786                                 atomic_read(&sbi->s_mb_lost_chunks));
2787                 printk(KERN_INFO
2788                        "EXT4-fs: mballoc: %lu generated and it took %Lu\n",
2789                                 sbi->s_mb_buddies_generated++,
2790                                 sbi->s_mb_generation_time);
2791                 printk(KERN_INFO
2792                        "EXT4-fs: mballoc: %u preallocated, %u discarded\n",
2793                                 atomic_read(&sbi->s_mb_preallocated),
2794                                 atomic_read(&sbi->s_mb_discarded));
2795         }
2796
2797         kfree(sbi->s_locality_groups);
2798
2799         ext4_mb_history_release(sb);
2800         ext4_mb_destroy_per_dev_proc(sb);
2801
2802         return 0;
2803 }
2804
2805 static noinline_for_stack void
2806 ext4_mb_free_committed_blocks(struct super_block *sb)
2807 {
2808         struct ext4_sb_info *sbi = EXT4_SB(sb);
2809         int err;
2810         int i;
2811         int count = 0;
2812         int count2 = 0;
2813         struct ext4_free_metadata *md;
2814         struct ext4_buddy e4b;
2815
2816         if (list_empty(&sbi->s_committed_transaction))
2817                 return;
2818
2819         /* there is committed blocks to be freed yet */
2820         do {
2821                 /* get next array of blocks */
2822                 md = NULL;
2823                 spin_lock(&sbi->s_md_lock);
2824                 if (!list_empty(&sbi->s_committed_transaction)) {
2825                         md = list_entry(sbi->s_committed_transaction.next,
2826                                         struct ext4_free_metadata, list);
2827                         list_del(&md->list);
2828                 }
2829                 spin_unlock(&sbi->s_md_lock);
2830
2831                 if (md == NULL)
2832                         break;
2833
2834                 mb_debug("gonna free %u blocks in group %lu (0x%p):",
2835                                 md->num, md->group, md);
2836
2837                 err = ext4_mb_load_buddy(sb, md->group, &e4b);
2838                 /* we expect to find existing buddy because it's pinned */
2839                 BUG_ON(err != 0);
2840
2841                 /* there are blocks to put in buddy to make them really free */
2842                 count += md->num;
2843                 count2++;
2844                 ext4_lock_group(sb, md->group);
2845                 for (i = 0; i < md->num; i++) {
2846                         mb_debug(" %u", md->blocks[i]);
2847                         err = mb_free_blocks(NULL, &e4b, md->blocks[i], 1);
2848                         BUG_ON(err != 0);
2849                 }
2850                 mb_debug("\n");
2851                 ext4_unlock_group(sb, md->group);
2852
2853                 /* balance refcounts from ext4_mb_free_metadata() */
2854                 page_cache_release(e4b.bd_buddy_page);
2855                 page_cache_release(e4b.bd_bitmap_page);
2856
2857                 kfree(md);
2858                 ext4_mb_release_desc(&e4b);
2859
2860         } while (md);
2861
2862         mb_debug("freed %u blocks in %u structures\n", count, count2);
2863 }
2864
2865 #define EXT4_MB_STATS_NAME              "stats"
2866 #define EXT4_MB_MAX_TO_SCAN_NAME        "max_to_scan"
2867 #define EXT4_MB_MIN_TO_SCAN_NAME        "min_to_scan"
2868 #define EXT4_MB_ORDER2_REQ              "order2_req"
2869 #define EXT4_MB_STREAM_REQ              "stream_req"
2870 #define EXT4_MB_GROUP_PREALLOC          "group_prealloc"
2871
2872
2873
2874 #define MB_PROC_VALUE_READ(name)                                \
2875 static int ext4_mb_read_##name(char *page, char **start,        \
2876                 off_t off, int count, int *eof, void *data)     \
2877 {                                                               \
2878         struct ext4_sb_info *sbi = data;                        \
2879         int len;                                                \
2880         *eof = 1;                                               \
2881         if (off != 0)                                           \
2882                 return 0;                                       \
2883         len = sprintf(page, "%ld\n", sbi->s_mb_##name);         \
2884         *start = page;                                          \
2885         return len;                                             \
2886 }
2887
2888 #define MB_PROC_VALUE_WRITE(name)                               \
2889 static int ext4_mb_write_##name(struct file *file,              \
2890                 const char __user *buf, unsigned long cnt, void *data)  \
2891 {                                                               \
2892         struct ext4_sb_info *sbi = data;                        \
2893         char str[32];                                           \
2894         long value;                                             \
2895         if (cnt >= sizeof(str))                                 \
2896                 return -EINVAL;                                 \
2897         if (copy_from_user(str, buf, cnt))                      \
2898                 return -EFAULT;                                 \
2899         value = simple_strtol(str, NULL, 0);                    \
2900         if (value <= 0)                                         \
2901                 return -ERANGE;                                 \
2902         sbi->s_mb_##name = value;                               \
2903         return cnt;                                             \
2904 }
2905
2906 MB_PROC_VALUE_READ(stats);
2907 MB_PROC_VALUE_WRITE(stats);
2908 MB_PROC_VALUE_READ(max_to_scan);
2909 MB_PROC_VALUE_WRITE(max_to_scan);
2910 MB_PROC_VALUE_READ(min_to_scan);
2911 MB_PROC_VALUE_WRITE(min_to_scan);
2912 MB_PROC_VALUE_READ(order2_reqs);
2913 MB_PROC_VALUE_WRITE(order2_reqs);
2914 MB_PROC_VALUE_READ(stream_request);
2915 MB_PROC_VALUE_WRITE(stream_request);
2916 MB_PROC_VALUE_READ(group_prealloc);
2917 MB_PROC_VALUE_WRITE(group_prealloc);
2918
2919 #define MB_PROC_HANDLER(name, var)                                      \
2920 do {                                                                    \
2921         proc = create_proc_entry(name, mode, sbi->s_mb_proc);           \
2922         if (proc == NULL) {                                             \
2923                 printk(KERN_ERR "EXT4-fs: can't to create %s\n", name); \
2924                 goto err_out;                                           \
2925         }                                                               \
2926         proc->data = sbi;                                               \
2927         proc->read_proc  = ext4_mb_read_##var ;                         \
2928         proc->write_proc = ext4_mb_write_##var;                         \
2929 } while (0)
2930
2931 static int ext4_mb_init_per_dev_proc(struct super_block *sb)
2932 {
2933         mode_t mode = S_IFREG | S_IRUGO | S_IWUSR;
2934         struct ext4_sb_info *sbi = EXT4_SB(sb);
2935         struct proc_dir_entry *proc;
2936         char devname[64];
2937
2938         snprintf(devname, sizeof(devname) - 1, "%s",
2939                 bdevname(sb->s_bdev, devname));
2940         sbi->s_mb_proc = proc_mkdir(devname, proc_root_ext4);
2941
2942         MB_PROC_HANDLER(EXT4_MB_STATS_NAME, stats);
2943         MB_PROC_HANDLER(EXT4_MB_MAX_TO_SCAN_NAME, max_to_scan);
2944         MB_PROC_HANDLER(EXT4_MB_MIN_TO_SCAN_NAME, min_to_scan);
2945         MB_PROC_HANDLER(EXT4_MB_ORDER2_REQ, order2_reqs);
2946         MB_PROC_HANDLER(EXT4_MB_STREAM_REQ, stream_request);
2947         MB_PROC_HANDLER(EXT4_MB_GROUP_PREALLOC, group_prealloc);
2948
2949         return 0;
2950
2951 err_out:
2952         printk(KERN_ERR "EXT4-fs: Unable to create %s\n", devname);
2953         remove_proc_entry(EXT4_MB_GROUP_PREALLOC, sbi->s_mb_proc);
2954         remove_proc_entry(EXT4_MB_STREAM_REQ, sbi->s_mb_proc);
2955         remove_proc_entry(EXT4_MB_ORDER2_REQ, sbi->s_mb_proc);
2956         remove_proc_entry(EXT4_MB_MIN_TO_SCAN_NAME, sbi->s_mb_proc);
2957         remove_proc_entry(EXT4_MB_MAX_TO_SCAN_NAME, sbi->s_mb_proc);
2958         remove_proc_entry(EXT4_MB_STATS_NAME, sbi->s_mb_proc);
2959         remove_proc_entry(devname, proc_root_ext4);
2960         sbi->s_mb_proc = NULL;
2961
2962         return -ENOMEM;
2963 }
2964
2965 static int ext4_mb_destroy_per_dev_proc(struct super_block *sb)
2966 {
2967         struct ext4_sb_info *sbi = EXT4_SB(sb);
2968         char devname[64];
2969
2970         if (sbi->s_mb_proc == NULL)
2971                 return -EINVAL;
2972
2973         snprintf(devname, sizeof(devname) - 1, "%s",
2974                 bdevname(sb->s_bdev, devname));
2975         remove_proc_entry(EXT4_MB_GROUP_PREALLOC, sbi->s_mb_proc);
2976         remove_proc_entry(EXT4_MB_STREAM_REQ, sbi->s_mb_proc);
2977         remove_proc_entry(EXT4_MB_ORDER2_REQ, sbi->s_mb_proc);
2978         remove_proc_entry(EXT4_MB_MIN_TO_SCAN_NAME, sbi->s_mb_proc);
2979         remove_proc_entry(EXT4_MB_MAX_TO_SCAN_NAME, sbi->s_mb_proc);
2980         remove_proc_entry(EXT4_MB_STATS_NAME, sbi->s_mb_proc);
2981         remove_proc_entry(devname, proc_root_ext4);
2982
2983         return 0;
2984 }
2985
2986 int __init init_ext4_mballoc(void)
2987 {
2988         ext4_pspace_cachep =
2989                 kmem_cache_create("ext4_prealloc_space",
2990                                      sizeof(struct ext4_prealloc_space),
2991                                      0, SLAB_RECLAIM_ACCOUNT, NULL);
2992         if (ext4_pspace_cachep == NULL)
2993                 return -ENOMEM;
2994
2995         ext4_ac_cachep =
2996                 kmem_cache_create("ext4_alloc_context",
2997                                      sizeof(struct ext4_allocation_context),
2998                                      0, SLAB_RECLAIM_ACCOUNT, NULL);
2999         if (ext4_ac_cachep == NULL) {
3000                 kmem_cache_destroy(ext4_pspace_cachep);
3001                 return -ENOMEM;
3002         }
3003 #ifdef CONFIG_PROC_FS
3004         proc_root_ext4 = proc_mkdir("fs/ext4", NULL);
3005         if (proc_root_ext4 == NULL)
3006                 printk(KERN_ERR "EXT4-fs: Unable to create fs/ext4\n");
3007 #endif
3008         return 0;
3009 }
3010
3011 void exit_ext4_mballoc(void)
3012 {
3013         /* XXX: synchronize_rcu(); */
3014         kmem_cache_destroy(ext4_pspace_cachep);
3015         kmem_cache_destroy(ext4_ac_cachep);
3016 #ifdef CONFIG_PROC_FS
3017         remove_proc_entry("fs/ext4", NULL);
3018 #endif
3019 }
3020
3021
3022 /*
3023  * Check quota and mark choosed space (ac->ac_b_ex) non-free in bitmaps
3024  * Returns 0 if success or error code
3025  */
3026 static noinline_for_stack int
3027 ext4_mb_mark_diskspace_used(struct ext4_allocation_context *ac,
3028                                 handle_t *handle)
3029 {
3030         struct buffer_head *bitmap_bh = NULL;
3031         struct ext4_super_block *es;
3032         struct ext4_group_desc *gdp;
3033         struct buffer_head *gdp_bh;
3034         struct ext4_sb_info *sbi;
3035         struct super_block *sb;
3036         ext4_fsblk_t block;
3037         int err;
3038
3039         BUG_ON(ac->ac_status != AC_STATUS_FOUND);
3040         BUG_ON(ac->ac_b_ex.fe_len <= 0);
3041
3042         sb = ac->ac_sb;
3043         sbi = EXT4_SB(sb);
3044         es = sbi->s_es;
3045
3046         ext4_debug("using block group %lu(%d)\n", ac->ac_b_ex.fe_group,
3047                         gdp->bg_free_blocks_count);
3048
3049         err = -EIO;
3050         bitmap_bh = read_block_bitmap(sb, ac->ac_b_ex.fe_group);
3051         if (!bitmap_bh)
3052                 goto out_err;
3053
3054         err = ext4_journal_get_write_access(handle, bitmap_bh);
3055         if (err)
3056                 goto out_err;
3057
3058         err = -EIO;
3059         gdp = ext4_get_group_desc(sb, ac->ac_b_ex.fe_group, &gdp_bh);
3060         if (!gdp)
3061                 goto out_err;
3062
3063         err = ext4_journal_get_write_access(handle, gdp_bh);
3064         if (err)
3065                 goto out_err;
3066
3067         block = ac->ac_b_ex.fe_group * EXT4_BLOCKS_PER_GROUP(sb)
3068                 + ac->ac_b_ex.fe_start
3069                 + le32_to_cpu(es->s_first_data_block);
3070
3071         if (block == ext4_block_bitmap(sb, gdp) ||
3072                         block == ext4_inode_bitmap(sb, gdp) ||
3073                         in_range(block, ext4_inode_table(sb, gdp),
3074                                 EXT4_SB(sb)->s_itb_per_group)) {
3075
3076                 ext4_error(sb, __FUNCTION__,
3077                            "Allocating block in system zone - block = %llu",
3078                            block);
3079         }
3080 #ifdef AGGRESSIVE_CHECK
3081         {
3082                 int i;
3083                 for (i = 0; i < ac->ac_b_ex.fe_len; i++) {
3084                         BUG_ON(mb_test_bit(ac->ac_b_ex.fe_start + i,
3085                                                 bitmap_bh->b_data));
3086                 }
3087         }
3088 #endif
3089         mb_set_bits(sb_bgl_lock(sbi, ac->ac_b_ex.fe_group), bitmap_bh->b_data,
3090                                 ac->ac_b_ex.fe_start, ac->ac_b_ex.fe_len);
3091
3092         spin_lock(sb_bgl_lock(sbi, ac->ac_b_ex.fe_group));
3093         if (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT)) {
3094                 gdp->bg_flags &= cpu_to_le16(~EXT4_BG_BLOCK_UNINIT);
3095                 gdp->bg_free_blocks_count =
3096                         cpu_to_le16(ext4_free_blocks_after_init(sb,
3097                                                 ac->ac_b_ex.fe_group,
3098                                                 gdp));
3099         }
3100         le16_add_cpu(&gdp->bg_free_blocks_count, -ac->ac_b_ex.fe_len);
3101         gdp->bg_checksum = ext4_group_desc_csum(sbi, ac->ac_b_ex.fe_group, gdp);
3102         spin_unlock(sb_bgl_lock(sbi, ac->ac_b_ex.fe_group));
3103         percpu_counter_sub(&sbi->s_freeblocks_counter, ac->ac_b_ex.fe_len);
3104
3105         err = ext4_journal_dirty_metadata(handle, bitmap_bh);
3106         if (err)
3107                 goto out_err;
3108         err = ext4_journal_dirty_metadata(handle, gdp_bh);
3109
3110 out_err:
3111         sb->s_dirt = 1;
3112         brelse(bitmap_bh);
3113         return err;
3114 }
3115
3116 /*
3117  * here we normalize request for locality group
3118  * Group request are normalized to s_strip size if we set the same via mount
3119  * option. If not we set it to s_mb_group_prealloc which can be configured via
3120  * /proc/fs/ext4/<partition>/group_prealloc
3121  *
3122  * XXX: should we try to preallocate more than the group has now?
3123  */
3124 static void ext4_mb_normalize_group_request(struct ext4_allocation_context *ac)
3125 {
3126         struct super_block *sb = ac->ac_sb;
3127         struct ext4_locality_group *lg = ac->ac_lg;
3128
3129         BUG_ON(lg == NULL);
3130         if (EXT4_SB(sb)->s_stripe)
3131                 ac->ac_g_ex.fe_len = EXT4_SB(sb)->s_stripe;
3132         else
3133                 ac->ac_g_ex.fe_len = EXT4_SB(sb)->s_mb_group_prealloc;
3134         mb_debug("#%u: goal %lu blocks for locality group\n",
3135                 current->pid, ac->ac_g_ex.fe_len);
3136 }
3137
3138 /*
3139  * Normalization means making request better in terms of
3140  * size and alignment
3141  */
3142 static noinline_for_stack void
3143 ext4_mb_normalize_request(struct ext4_allocation_context *ac,
3144                                 struct ext4_allocation_request *ar)
3145 {
3146         int bsbits, max;
3147         ext4_lblk_t end;
3148         loff_t size, orig_size, start_off;
3149         ext4_lblk_t start, orig_start;
3150         struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
3151         struct ext4_prealloc_space *pa;
3152
3153         /* do normalize only data requests, metadata requests
3154            do not need preallocation */
3155         if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
3156                 return;
3157
3158         /* sometime caller may want exact blocks */
3159         if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
3160                 return;
3161
3162         /* caller may indicate that preallocation isn't
3163          * required (it's a tail, for example) */
3164         if (ac->ac_flags & EXT4_MB_HINT_NOPREALLOC)
3165                 return;
3166
3167         if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC) {
3168                 ext4_mb_normalize_group_request(ac);
3169                 return ;
3170         }
3171
3172         bsbits = ac->ac_sb->s_blocksize_bits;
3173
3174         /* first, let's learn actual file size
3175          * given current request is allocated */
3176         size = ac->ac_o_ex.fe_logical + ac->ac_o_ex.fe_len;
3177         size = size << bsbits;
3178         if (size < i_size_read(ac->ac_inode))
3179                 size = i_size_read(ac->ac_inode);
3180
3181         /* max available blocks in a free group */
3182         max = EXT4_BLOCKS_PER_GROUP(ac->ac_sb) - 1 - 1 -
3183                                 EXT4_SB(ac->ac_sb)->s_itb_per_group;
3184
3185 #define NRL_CHECK_SIZE(req, size, max,bits)     \
3186                 (req <= (size) || max <= ((size) >> bits))
3187
3188         /* first, try to predict filesize */
3189         /* XXX: should this table be tunable? */
3190         start_off = 0;
3191         if (size <= 16 * 1024) {
3192                 size = 16 * 1024;
3193         } else if (size <= 32 * 1024) {
3194                 size = 32 * 1024;
3195         } else if (size <= 64 * 1024) {
3196                 size = 64 * 1024;
3197         } else if (size <= 128 * 1024) {
3198                 size = 128 * 1024;
3199         } else if (size <= 256 * 1024) {
3200                 size = 256 * 1024;
3201         } else if (size <= 512 * 1024) {
3202                 size = 512 * 1024;
3203         } else if (size <= 1024 * 1024) {
3204                 size = 1024 * 1024;
3205         } else if (NRL_CHECK_SIZE(size, 4 * 1024 * 1024, max, bsbits)) {
3206                 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
3207                                                 (20 - bsbits)) << 20;
3208                 size = 1024 * 1024;
3209         } else if (NRL_CHECK_SIZE(size, 8 * 1024 * 1024, max, bsbits)) {
3210                 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
3211                                                         (22 - bsbits)) << 22;
3212                 size = 4 * 1024 * 1024;
3213         } else if (NRL_CHECK_SIZE(ac->ac_o_ex.fe_len,
3214                                         (8<<20)>>bsbits, max, bsbits)) {
3215                 start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
3216                                                         (23 - bsbits)) << 23;
3217                 size = 8 * 1024 * 1024;
3218         } else {
3219                 start_off = (loff_t)ac->ac_o_ex.fe_logical << bsbits;
3220                 size      = ac->ac_o_ex.fe_len << bsbits;
3221         }
3222         orig_size = size = size >> bsbits;
3223         orig_start = start = start_off >> bsbits;
3224
3225         /* don't cover already allocated blocks in selected range */
3226         if (ar->pleft && start <= ar->lleft) {
3227                 size -= ar->lleft + 1 - start;
3228                 start = ar->lleft + 1;
3229         }
3230         if (ar->pright && start + size - 1 >= ar->lright)
3231                 size -= start + size - ar->lright;
3232
3233         end = start + size;
3234
3235         /* check we don't cross already preallocated blocks */
3236         rcu_read_lock();
3237         list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3238                 unsigned long pa_end;
3239
3240                 if (pa->pa_deleted)
3241                         continue;
3242                 spin_lock(&pa->pa_lock);
3243                 if (pa->pa_deleted) {
3244                         spin_unlock(&pa->pa_lock);
3245                         continue;
3246                 }
3247
3248                 pa_end = pa->pa_lstart + pa->pa_len;
3249
3250                 /* PA must not overlap original request */
3251                 BUG_ON(!(ac->ac_o_ex.fe_logical >= pa_end ||
3252                         ac->ac_o_ex.fe_logical < pa->pa_lstart));
3253
3254                 /* skip PA normalized request doesn't overlap with */
3255                 if (pa->pa_lstart >= end) {
3256                         spin_unlock(&pa->pa_lock);
3257                         continue;
3258                 }
3259                 if (pa_end <= start) {
3260                         spin_unlock(&pa->pa_lock);
3261                         continue;
3262                 }
3263                 BUG_ON(pa->pa_lstart <= start && pa_end >= end);
3264
3265                 if (pa_end <= ac->ac_o_ex.fe_logical) {
3266                         BUG_ON(pa_end < start);
3267                         start = pa_end;
3268                 }
3269
3270                 if (pa->pa_lstart > ac->ac_o_ex.fe_logical) {
3271                         BUG_ON(pa->pa_lstart > end);
3272                         end = pa->pa_lstart;
3273                 }
3274                 spin_unlock(&pa->pa_lock);
3275         }
3276         rcu_read_unlock();
3277         size = end - start;
3278
3279         /* XXX: extra loop to check we really don't overlap preallocations */
3280         rcu_read_lock();
3281         list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3282                 unsigned long pa_end;
3283                 spin_lock(&pa->pa_lock);
3284                 if (pa->pa_deleted == 0) {
3285                         pa_end = pa->pa_lstart + pa->pa_len;
3286                         BUG_ON(!(start >= pa_end || end <= pa->pa_lstart));
3287                 }
3288                 spin_unlock(&pa->pa_lock);
3289         }
3290         rcu_read_unlock();
3291
3292         if (start + size <= ac->ac_o_ex.fe_logical &&
3293                         start > ac->ac_o_ex.fe_logical) {
3294                 printk(KERN_ERR "start %lu, size %lu, fe_logical %lu\n",
3295                         (unsigned long) start, (unsigned long) size,
3296                         (unsigned long) ac->ac_o_ex.fe_logical);
3297         }
3298         BUG_ON(start + size <= ac->ac_o_ex.fe_logical &&
3299                         start > ac->ac_o_ex.fe_logical);
3300         BUG_ON(size <= 0 || size >= EXT4_BLOCKS_PER_GROUP(ac->ac_sb));
3301
3302         /* now prepare goal request */
3303
3304         /* XXX: is it better to align blocks WRT to logical
3305          * placement or satisfy big request as is */
3306         ac->ac_g_ex.fe_logical = start;
3307         ac->ac_g_ex.fe_len = size;
3308
3309         /* define goal start in order to merge */
3310         if (ar->pright && (ar->lright == (start + size))) {
3311                 /* merge to the right */
3312                 ext4_get_group_no_and_offset(ac->ac_sb, ar->pright - size,
3313                                                 &ac->ac_f_ex.fe_group,
3314                                                 &ac->ac_f_ex.fe_start);
3315                 ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
3316         }
3317         if (ar->pleft && (ar->lleft + 1 == start)) {
3318                 /* merge to the left */
3319                 ext4_get_group_no_and_offset(ac->ac_sb, ar->pleft + 1,
3320                                                 &ac->ac_f_ex.fe_group,
3321                                                 &ac->ac_f_ex.fe_start);
3322                 ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
3323         }
3324
3325         mb_debug("goal: %u(was %u) blocks at %u\n", (unsigned) size,
3326                 (unsigned) orig_size, (unsigned) start);
3327 }
3328
3329 static void ext4_mb_collect_stats(struct ext4_allocation_context *ac)
3330 {
3331         struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
3332
3333         if (sbi->s_mb_stats && ac->ac_g_ex.fe_len > 1) {
3334                 atomic_inc(&sbi->s_bal_reqs);
3335                 atomic_add(ac->ac_b_ex.fe_len, &sbi->s_bal_allocated);
3336                 if (ac->ac_o_ex.fe_len >= ac->ac_g_ex.fe_len)
3337                         atomic_inc(&sbi->s_bal_success);
3338                 atomic_add(ac->ac_found, &sbi->s_bal_ex_scanned);
3339                 if (ac->ac_g_ex.fe_start == ac->ac_b_ex.fe_start &&
3340                                 ac->ac_g_ex.fe_group == ac->ac_b_ex.fe_group)
3341                         atomic_inc(&sbi->s_bal_goals);
3342                 if (ac->ac_found > sbi->s_mb_max_to_scan)
3343                         atomic_inc(&sbi->s_bal_breaks);
3344         }
3345
3346         ext4_mb_store_history(ac);
3347 }
3348
3349 /*
3350  * use blocks preallocated to inode
3351  */
3352 static void ext4_mb_use_inode_pa(struct ext4_allocation_context *ac,
3353                                 struct ext4_prealloc_space *pa)
3354 {
3355         ext4_fsblk_t start;
3356         ext4_fsblk_t end;
3357         int len;
3358
3359         /* found preallocated blocks, use them */
3360         start = pa->pa_pstart + (ac->ac_o_ex.fe_logical - pa->pa_lstart);
3361         end = min(pa->pa_pstart + pa->pa_len, start + ac->ac_o_ex.fe_len);
3362         len = end - start;
3363         ext4_get_group_no_and_offset(ac->ac_sb, start, &ac->ac_b_ex.fe_group,
3364                                         &ac->ac_b_ex.fe_start);
3365         ac->ac_b_ex.fe_len = len;
3366         ac->ac_status = AC_STATUS_FOUND;
3367         ac->ac_pa = pa;
3368
3369         BUG_ON(start < pa->pa_pstart);
3370         BUG_ON(start + len > pa->pa_pstart + pa->pa_len);
3371         BUG_ON(pa->pa_free < len);
3372         pa->pa_free -= len;
3373
3374         mb_debug("use %llu/%lu from inode pa %p\n", start, len, pa);
3375 }
3376
3377 /*
3378  * use blocks preallocated to locality group
3379  */
3380 static void ext4_mb_use_group_pa(struct ext4_allocation_context *ac,
3381                                 struct ext4_prealloc_space *pa)
3382 {
3383         unsigned len = ac->ac_o_ex.fe_len;
3384
3385         ext4_get_group_no_and_offset(ac->ac_sb, pa->pa_pstart,
3386                                         &ac->ac_b_ex.fe_group,
3387                                         &ac->ac_b_ex.fe_start);
3388         ac->ac_b_ex.fe_len = len;
3389         ac->ac_status = AC_STATUS_FOUND;
3390         ac->ac_pa = pa;
3391
3392         /* we don't correct pa_pstart or pa_plen here to avoid
3393          * possible race when the group is being loaded concurrently
3394          * instead we correct pa later, after blocks are marked
3395          * in on-disk bitmap -- see ext4_mb_release_context()
3396          * Other CPUs are prevented from allocating from this pa by lg_mutex
3397          */
3398         mb_debug("use %u/%u from group pa %p\n", pa->pa_lstart-len, len, pa);
3399 }
3400
3401 /*
3402  * search goal blocks in preallocated space
3403  */
3404 static noinline_for_stack int
3405 ext4_mb_use_preallocated(struct ext4_allocation_context *ac)
3406 {
3407         struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
3408         struct ext4_locality_group *lg;
3409         struct ext4_prealloc_space *pa;
3410
3411         /* only data can be preallocated */
3412         if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
3413                 return 0;
3414
3415         /* first, try per-file preallocation */
3416         rcu_read_lock();
3417         list_for_each_entry_rcu(pa, &ei->i_prealloc_list, pa_inode_list) {
3418
3419                 /* all fields in this condition don't change,
3420                  * so we can skip locking for them */
3421                 if (ac->ac_o_ex.fe_logical < pa->pa_lstart ||
3422                         ac->ac_o_ex.fe_logical >= pa->pa_lstart + pa->pa_len)
3423                         continue;
3424
3425                 /* found preallocated blocks, use them */
3426                 spin_lock(&pa->pa_lock);
3427                 if (pa->pa_deleted == 0 && pa->pa_free) {
3428                         atomic_inc(&pa->pa_count);
3429                         ext4_mb_use_inode_pa(ac, pa);
3430                         spin_unlock(&pa->pa_lock);
3431                         ac->ac_criteria = 10;
3432                         rcu_read_unlock();
3433                         return 1;
3434                 }
3435                 spin_unlock(&pa->pa_lock);
3436         }
3437         rcu_read_unlock();
3438
3439         /* can we use group allocation? */
3440         if (!(ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC))
3441                 return 0;
3442
3443         /* inode may have no locality group for some reason */
3444         lg = ac->ac_lg;
3445         if (lg == NULL)
3446                 return 0;
3447
3448         rcu_read_lock();
3449         list_for_each_entry_rcu(pa, &lg->lg_prealloc_list, pa_inode_list) {
3450                 spin_lock(&pa->pa_lock);
3451                 if (pa->pa_deleted == 0 && pa->pa_free >= ac->ac_o_ex.fe_len) {
3452                         atomic_inc(&pa->pa_count);
3453                         ext4_mb_use_group_pa(ac, pa);
3454                         spin_unlock(&pa->pa_lock);
3455                         ac->ac_criteria = 20;
3456                         rcu_read_unlock();
3457                         return 1;
3458                 }
3459                 spin_unlock(&pa->pa_lock);
3460         }
3461         rcu_read_unlock();
3462
3463         return 0;
3464 }
3465
3466 /*
3467  * the function goes through all preallocation in this group and marks them
3468  * used in in-core bitmap. buddy must be generated from this bitmap
3469  * Need to be called with ext4 group lock (ext4_lock_group)
3470  */
3471 static void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
3472                                         ext4_group_t group)
3473 {
3474         struct ext4_group_info *grp = ext4_get_group_info(sb, group);
3475         struct ext4_prealloc_space *pa;
3476         struct list_head *cur;
3477         ext4_group_t groupnr;
3478         ext4_grpblk_t start;
3479         int preallocated = 0;
3480         int count = 0;
3481         int len;
3482
3483         /* all form of preallocation discards first load group,
3484          * so the only competing code is preallocation use.
3485          * we don't need any locking here
3486          * notice we do NOT ignore preallocations with pa_deleted
3487          * otherwise we could leave used blocks available for
3488          * allocation in buddy when concurrent ext4_mb_put_pa()
3489          * is dropping preallocation
3490          */
3491         list_for_each(cur, &grp->bb_prealloc_list) {
3492                 pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
3493                 spin_lock(&pa->pa_lock);
3494                 ext4_get_group_no_and_offset(sb, pa->pa_pstart,
3495                                              &groupnr, &start);
3496                 len = pa->pa_len;
3497                 spin_unlock(&pa->pa_lock);
3498                 if (unlikely(len == 0))
3499                         continue;
3500                 BUG_ON(groupnr != group);
3501                 mb_set_bits(sb_bgl_lock(EXT4_SB(sb), group),
3502                                                 bitmap, start, len);
3503                 preallocated += len;
3504                 count++;
3505         }
3506         mb_debug("prellocated %u for group %lu\n", preallocated, group);
3507 }
3508
3509 static void ext4_mb_pa_callback(struct rcu_head *head)
3510 {
3511         struct ext4_prealloc_space *pa;
3512         pa = container_of(head, struct ext4_prealloc_space, u.pa_rcu);
3513         kmem_cache_free(ext4_pspace_cachep, pa);
3514 }
3515
3516 /*
3517  * drops a reference to preallocated space descriptor
3518  * if this was the last reference and the space is consumed
3519  */
3520 static void ext4_mb_put_pa(struct ext4_allocation_context *ac,
3521                         struct super_block *sb, struct ext4_prealloc_space *pa)
3522 {
3523         unsigned long grp;
3524
3525         if (!atomic_dec_and_test(&pa->pa_count) || pa->pa_free != 0)
3526                 return;
3527
3528         /* in this short window concurrent discard can set pa_deleted */
3529         spin_lock(&pa->pa_lock);
3530         if (pa->pa_deleted == 1) {
3531                 spin_unlock(&pa->pa_lock);
3532                 return;
3533         }
3534
3535         pa->pa_deleted = 1;
3536         spin_unlock(&pa->pa_lock);
3537
3538         /* -1 is to protect from crossing allocation group */
3539         ext4_get_group_no_and_offset(sb, pa->pa_pstart - 1, &grp, NULL);
3540
3541         /*
3542          * possible race:
3543          *
3544          *  P1 (buddy init)                     P2 (regular allocation)
3545          *                                      find block B in PA
3546          *  copy on-disk bitmap to buddy
3547          *                                      mark B in on-disk bitmap
3548          *                                      drop PA from group
3549          *  mark all PAs in buddy
3550          *
3551          * thus, P1 initializes buddy with B available. to prevent this
3552          * we make "copy" and "mark all PAs" atomic and serialize "drop PA"
3553          * against that pair
3554          */
3555         ext4_lock_group(sb, grp);
3556         list_del(&pa->pa_group_list);
3557         ext4_unlock_group(sb, grp);
3558
3559         spin_lock(pa->pa_obj_lock);
3560         list_del_rcu(&pa->pa_inode_list);
3561         spin_unlock(pa->pa_obj_lock);
3562
3563         call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
3564 }
3565
3566 /*
3567  * creates new preallocated space for given inode
3568  */
3569 static noinline_for_stack int
3570 ext4_mb_new_inode_pa(struct ext4_allocation_context *ac)
3571 {
3572         struct super_block *sb = ac->ac_sb;
3573         struct ext4_prealloc_space *pa;
3574         struct ext4_group_info *grp;
3575         struct ext4_inode_info *ei;
3576
3577         /* preallocate only when found space is larger then requested */
3578         BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
3579         BUG_ON(ac->ac_status != AC_STATUS_FOUND);
3580         BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
3581
3582         pa = kmem_cache_alloc(ext4_pspace_cachep, GFP_NOFS);
3583         if (pa == NULL)
3584                 return -ENOMEM;
3585
3586         if (ac->ac_b_ex.fe_len < ac->ac_g_ex.fe_len) {
3587                 int winl;
3588                 int wins;
3589                 int win;
3590                 int offs;
3591
3592                 /* we can't allocate as much as normalizer wants.
3593                  * so, found space must get proper lstart
3594                  * to cover original request */
3595                 BUG_ON(ac->ac_g_ex.fe_logical > ac->ac_o_ex.fe_logical);
3596                 BUG_ON(ac->ac_g_ex.fe_len < ac->ac_o_ex.fe_len);
3597
3598                 /* we're limited by original request in that
3599                  * logical block must be covered any way
3600                  * winl is window we can move our chunk within */
3601                 winl = ac->ac_o_ex.fe_logical - ac->ac_g_ex.fe_logical;
3602
3603                 /* also, we should cover whole original request */
3604                 wins = ac->ac_b_ex.fe_len - ac->ac_o_ex.fe_len;
3605
3606                 /* the smallest one defines real window */
3607                 win = min(winl, wins);
3608
3609                 offs = ac->ac_o_ex.fe_logical % ac->ac_b_ex.fe_len;
3610                 if (offs && offs < win)
3611                         win = offs;
3612
3613                 ac->ac_b_ex.fe_logical = ac->ac_o_ex.fe_logical - win;
3614                 BUG_ON(ac->ac_o_ex.fe_logical < ac->ac_b_ex.fe_logical);
3615                 BUG_ON(ac->ac_o_ex.fe_len > ac->ac_b_ex.fe_len);
3616         }
3617
3618         /* preallocation can change ac_b_ex, thus we store actually
3619          * allocated blocks for history */
3620         ac->ac_f_ex = ac->ac_b_ex;
3621
3622         pa->pa_lstart = ac->ac_b_ex.fe_logical;
3623         pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
3624         pa->pa_len = ac->ac_b_ex.fe_len;
3625         pa->pa_free = pa->pa_len;
3626         atomic_set(&pa->pa_count, 1);
3627         spin_lock_init(&pa->pa_lock);
3628         pa->pa_deleted = 0;
3629         pa->pa_linear = 0;
3630
3631         mb_debug("new inode pa %p: %llu/%u for %u\n", pa,
3632                         pa->pa_pstart, pa->pa_len, pa->pa_lstart);
3633
3634         ext4_mb_use_inode_pa(ac, pa);
3635         atomic_add(pa->pa_free, &EXT4_SB(sb)->s_mb_preallocated);
3636
3637         ei = EXT4_I(ac->ac_inode);
3638         grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
3639
3640         pa->pa_obj_lock = &ei->i_prealloc_lock;
3641         pa->pa_inode = ac->ac_inode;
3642
3643         ext4_lock_group(sb, ac->ac_b_ex.fe_group);
3644         list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
3645         ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3646
3647         spin_lock(pa->pa_obj_lock);
3648         list_add_rcu(&pa->pa_inode_list, &ei->i_prealloc_list);
3649         spin_unlock(pa->pa_obj_lock);
3650
3651         return 0;
3652 }
3653
3654 /*
3655  * creates new preallocated space for locality group inodes belongs to
3656  */
3657 static noinline_for_stack int
3658 ext4_mb_new_group_pa(struct ext4_allocation_context *ac)
3659 {
3660         struct super_block *sb = ac->ac_sb;
3661         struct ext4_locality_group *lg;
3662         struct ext4_prealloc_space *pa;
3663         struct ext4_group_info *grp;
3664
3665         /* preallocate only when found space is larger then requested */
3666         BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
3667         BUG_ON(ac->ac_status != AC_STATUS_FOUND);
3668         BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
3669
3670         BUG_ON(ext4_pspace_cachep == NULL);
3671         pa = kmem_cache_alloc(ext4_pspace_cachep, GFP_NOFS);
3672         if (pa == NULL)
3673                 return -ENOMEM;
3674
3675         /* preallocation can change ac_b_ex, thus we store actually
3676          * allocated blocks for history */
3677         ac->ac_f_ex = ac->ac_b_ex;
3678
3679         pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
3680         pa->pa_lstart = pa->pa_pstart;
3681         pa->pa_len = ac->ac_b_ex.fe_len;
3682         pa->pa_free = pa->pa_len;
3683         atomic_set(&pa->pa_count, 1);
3684         spin_lock_init(&pa->pa_lock);
3685         pa->pa_deleted = 0;
3686         pa->pa_linear = 1;
3687
3688         mb_debug("new group pa %p: %llu/%u for %u\n", pa,
3689                         pa->pa_pstart, pa->pa_len, pa->pa_lstart);
3690
3691         ext4_mb_use_group_pa(ac, pa);
3692         atomic_add(pa->pa_free, &EXT4_SB(sb)->s_mb_preallocated);
3693
3694         grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
3695         lg = ac->ac_lg;
3696         BUG_ON(lg == NULL);
3697
3698         pa->pa_obj_lock = &lg->lg_prealloc_lock;
3699         pa->pa_inode = NULL;
3700
3701         ext4_lock_group(sb, ac->ac_b_ex.fe_group);
3702         list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
3703         ext4_unlock_group(sb, ac->ac_b_ex.fe_group);
3704
3705         spin_lock(pa->pa_obj_lock);
3706         list_add_tail_rcu(&pa->pa_inode_list, &lg->lg_prealloc_list);
3707         spin_unlock(pa->pa_obj_lock);
3708
3709         return 0;
3710 }
3711
3712 static int ext4_mb_new_preallocation(struct ext4_allocation_context *ac)
3713 {
3714         int err;
3715
3716         if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
3717                 err = ext4_mb_new_group_pa(ac);
3718         else
3719                 err = ext4_mb_new_inode_pa(ac);
3720         return err;
3721 }
3722
3723 /*
3724  * finds all unused blocks in on-disk bitmap, frees them in
3725  * in-core bitmap and buddy.
3726  * @pa must be unlinked from inode and group lists, so that
3727  * nobody else can find/use it.
3728  * the caller MUST hold group/inode locks.
3729  * TODO: optimize the case when there are no in-core structures yet
3730  */
3731 static noinline_for_stack int
3732 ext4_mb_release_inode_pa(struct ext4_buddy *e4b, struct buffer_head *bitmap_bh,
3733                                 struct ext4_prealloc_space *pa)
3734 {
3735         struct ext4_allocation_context *ac;
3736         struct super_block *sb = e4b->bd_sb;
3737         struct ext4_sb_info *sbi = EXT4_SB(sb);
3738         unsigned long end;
3739         unsigned long next;
3740         ext4_group_t group;
3741         ext4_grpblk_t bit;
3742         sector_t start;
3743         int err = 0;
3744         int free = 0;
3745
3746         BUG_ON(pa->pa_deleted == 0);
3747         ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
3748         BUG_ON(group != e4b->bd_group && pa->pa_len != 0);
3749         end = bit + pa->pa_len;
3750
3751         ac = kmem_cache_alloc(ext4_ac_cachep, GFP_NOFS);
3752
3753         if (ac) {
3754                 ac->ac_sb = sb;
3755                 ac->ac_inode = pa->pa_inode;
3756                 ac->ac_op = EXT4_MB_HISTORY_DISCARD;
3757         }
3758
3759         while (bit < end) {
3760                 bit = mb_find_next_zero_bit(bitmap_bh->b_data, end, bit);
3761                 if (bit >= end)
3762                         break;
3763                 next = mb_find_next_bit(bitmap_bh->b_data, end, bit);
3764                 if (next > end)
3765                         next = end;
3766                 start = group * EXT4_BLOCKS_PER_GROUP(sb) + bit +
3767                                 le32_to_cpu(sbi->s_es->s_first_data_block);
3768                 mb_debug("    free preallocated %u/%u in group %u\n",
3769                                 (unsigned) start, (unsigned) next - bit,
3770                                 (unsigned) group);
3771                 free += next - bit;
3772
3773                 if (ac) {
3774                         ac->ac_b_ex.fe_group = group;
3775                         ac->ac_b_ex.fe_start = bit;
3776                         ac->ac_b_ex.fe_len = next - bit;
3777                         ac->ac_b_ex.fe_logical = 0;
3778                         ext4_mb_store_history(ac);
3779                 }
3780
3781                 mb_free_blocks(pa->pa_inode, e4b, bit, next - bit);
3782                 bit = next + 1;
3783         }
3784         if (free != pa->pa_free) {
3785                 printk(KERN_CRIT "pa %p: logic %lu, phys. %lu, len %lu\n",
3786                         pa, (unsigned long) pa->pa_lstart,
3787                         (unsigned long) pa->pa_pstart,
3788                         (unsigned long) pa->pa_len);
3789                 ext4_error(sb, __FUNCTION__, "free %u, pa_free %u\n",
3790                                                 free, pa->pa_free);
3791                 /*
3792                  * pa is already deleted so we use the value obtained
3793                  * from the bitmap and continue.
3794                  */
3795         }
3796         atomic_add(free, &sbi->s_mb_discarded);
3797         if (ac)
3798                 kmem_cache_free(ext4_ac_cachep, ac);
3799
3800         return err;
3801 }
3802
3803 static noinline_for_stack int
3804 ext4_mb_release_group_pa(struct ext4_buddy *e4b,
3805                                 struct ext4_prealloc_space *pa)
3806 {
3807         struct ext4_allocation_context *ac;
3808         struct super_block *sb = e4b->bd_sb;
3809         ext4_group_t group;
3810         ext4_grpblk_t bit;
3811
3812         ac = kmem_cache_alloc(ext4_ac_cachep, GFP_NOFS);
3813
3814         if (ac)
3815                 ac->ac_op = EXT4_MB_HISTORY_DISCARD;
3816
3817         BUG_ON(pa->pa_deleted == 0);
3818         ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
3819         BUG_ON(group != e4b->bd_group && pa->pa_len != 0);
3820         mb_free_blocks(pa->pa_inode, e4b, bit, pa->pa_len);
3821         atomic_add(pa->pa_len, &EXT4_SB(sb)->s_mb_discarded);
3822
3823         if (ac) {
3824                 ac->ac_sb = sb;
3825                 ac->ac_inode = NULL;
3826                 ac->ac_b_ex.fe_group = group;
3827                 ac->ac_b_ex.fe_start = bit;
3828                 ac->ac_b_ex.fe_len = pa->pa_len;
3829                 ac->ac_b_ex.fe_logical = 0;
3830                 ext4_mb_store_history(ac);
3831                 kmem_cache_free(ext4_ac_cachep, ac);
3832         }
3833
3834         return 0;
3835 }
3836
3837 /*
3838  * releases all preallocations in given group
3839  *
3840  * first, we need to decide discard policy:
3841  * - when do we discard
3842  *   1) ENOSPC
3843  * - how many do we discard
3844  *   1) how many requested
3845  */
3846 static noinline_for_stack int
3847 ext4_mb_discard_group_preallocations(struct super_block *sb,
3848                                         ext4_group_t group, int needed)
3849 {
3850         struct ext4_group_info *grp = ext4_get_group_info(sb, group);
3851         struct buffer_head *bitmap_bh = NULL;
3852         struct ext4_prealloc_space *pa, *tmp;
3853         struct list_head list;
3854         struct ext4_buddy e4b;
3855         int err;
3856         int busy = 0;
3857         int free = 0;
3858
3859         mb_debug("discard preallocation for group %lu\n", group);
3860
3861         if (list_empty(&grp->bb_prealloc_list))
3862                 return 0;
3863
3864         bitmap_bh = read_block_bitmap(sb, group);
3865         if (bitmap_bh == NULL) {
3866                 /* error handling here */
3867                 ext4_mb_release_desc(&e4b);
3868                 BUG_ON(bitmap_bh == NULL);
3869         }
3870
3871         err = ext4_mb_load_buddy(sb, group, &e4b);
3872         BUG_ON(err != 0); /* error handling here */
3873
3874         if (needed == 0)
3875                 needed = EXT4_BLOCKS_PER_GROUP(sb) + 1;
3876
3877         grp = ext4_get_group_info(sb, group);
3878         INIT_LIST_HEAD(&list);
3879
3880 repeat:
3881         ext4_lock_group(sb, group);
3882         list_for_each_entry_safe(pa, tmp,
3883                                 &grp->bb_prealloc_list, pa_group_list) {
3884                 spin_lock(&pa->pa_lock);
3885                 if (atomic_read(&pa->pa_count)) {
3886                         spin_unlock(&pa->pa_lock);
3887                         busy = 1;
3888                         continue;
3889                 }
3890                 if (pa->pa_deleted) {
3891                         spin_unlock(&pa->pa_lock);
3892                         continue;
3893                 }
3894
3895                 /* seems this one can be freed ... */
3896                 pa->pa_deleted = 1;
3897
3898                 /* we can trust pa_free ... */
3899                 free += pa->pa_free;
3900
3901                 spin_unlock(&pa->pa_lock);
3902
3903                 list_del(&pa->pa_group_list);
3904                 list_add(&pa->u.pa_tmp_list, &list);
3905         }
3906
3907         /* if we still need more blocks and some PAs were used, try again */
3908         if (free < needed && busy) {
3909                 busy = 0;
3910                 ext4_unlock_group(sb, group);
3911                 /*
3912                  * Yield the CPU here so that we don't get soft lockup
3913                  * in non preempt case.
3914                  */
3915                 yield();
3916                 goto repeat;
3917         }
3918
3919         /* found anything to free? */
3920         if (list_empty(&list)) {
3921                 BUG_ON(free != 0);
3922                 goto out;
3923         }
3924
3925         /* now free all selected PAs */
3926         list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
3927
3928                 /* remove from object (inode or locality group) */
3929                 spin_lock(pa->pa_obj_lock);
3930                 list_del_rcu(&pa->pa_inode_list);
3931                 spin_unlock(pa->pa_obj_lock);
3932
3933                 if (pa->pa_linear)
3934                         ext4_mb_release_group_pa(&e4b, pa);
3935                 else
3936                         ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa);
3937
3938                 list_del(&pa->u.pa_tmp_list);
3939                 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
3940         }
3941
3942 out:
3943         ext4_unlock_group(sb, group);
3944         ext4_mb_release_desc(&e4b);
3945         put_bh(bitmap_bh);
3946         return free;
3947 }
3948
3949 /*
3950  * releases all non-used preallocated blocks for given inode
3951  *
3952  * It's important to discard preallocations under i_data_sem
3953  * We don't want another block to be served from the prealloc
3954  * space when we are discarding the inode prealloc space.
3955  *
3956  * FIXME!! Make sure it is valid at all the call sites
3957  */
3958 void ext4_mb_discard_inode_preallocations(struct inode *inode)
3959 {
3960         struct ext4_inode_info *ei = EXT4_I(inode);
3961         struct super_block *sb = inode->i_sb;
3962         struct buffer_head *bitmap_bh = NULL;
3963         struct ext4_prealloc_space *pa, *tmp;
3964         ext4_group_t group = 0;
3965         struct list_head list;
3966         struct ext4_buddy e4b;
3967         int err;
3968
3969         if (!test_opt(sb, MBALLOC) || !S_ISREG(inode->i_mode)) {
3970                 /*BUG_ON(!list_empty(&ei->i_prealloc_list));*/
3971                 return;
3972         }
3973
3974         mb_debug("discard preallocation for inode %lu\n", inode->i_ino);
3975
3976         INIT_LIST_HEAD(&list);
3977
3978 repeat:
3979         /* first, collect all pa's in the inode */
3980         spin_lock(&ei->i_prealloc_lock);
3981         while (!list_empty(&ei->i_prealloc_list)) {
3982                 pa = list_entry(ei->i_prealloc_list.next,
3983                                 struct ext4_prealloc_space, pa_inode_list);
3984                 BUG_ON(pa->pa_obj_lock != &ei->i_prealloc_lock);
3985                 spin_lock(&pa->pa_lock);
3986                 if (atomic_read(&pa->pa_count)) {
3987                         /* this shouldn't happen often - nobody should
3988                          * use preallocation while we're discarding it */
3989                         spin_unlock(&pa->pa_lock);
3990                         spin_unlock(&ei->i_prealloc_lock);
3991                         printk(KERN_ERR "uh-oh! used pa while discarding\n");
3992                         WARN_ON(1);
3993                         schedule_timeout_uninterruptible(HZ);
3994                         goto repeat;
3995
3996                 }
3997                 if (pa->pa_deleted == 0) {
3998                         pa->pa_deleted = 1;
3999                         spin_unlock(&pa->pa_lock);
4000                         list_del_rcu(&pa->pa_inode_list);
4001                         list_add(&pa->u.pa_tmp_list, &list);
4002                         continue;
4003                 }
4004
4005                 /* someone is deleting pa right now */
4006                 spin_unlock(&pa->pa_lock);
4007                 spin_unlock(&ei->i_prealloc_lock);
4008
4009                 /* we have to wait here because pa_deleted
4010                  * doesn't mean pa is already unlinked from
4011                  * the list. as we might be called from
4012                  * ->clear_inode() the inode will get freed
4013                  * and concurrent thread which is unlinking
4014                  * pa from inode's list may access already
4015                  * freed memory, bad-bad-bad */
4016
4017                 /* XXX: if this happens too often, we can
4018                  * add a flag to force wait only in case
4019                  * of ->clear_inode(), but not in case of
4020                  * regular truncate */
4021                 schedule_timeout_uninterruptible(HZ);
4022                 goto repeat;
4023         }
4024         spin_unlock(&ei->i_prealloc_lock);
4025
4026         list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
4027                 BUG_ON(pa->pa_linear != 0);
4028                 ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, NULL);
4029
4030                 err = ext4_mb_load_buddy(sb, group, &e4b);
4031                 BUG_ON(err != 0); /* error handling here */
4032
4033                 bitmap_bh = read_block_bitmap(sb, group);
4034                 if (bitmap_bh == NULL) {
4035                         /* error handling here */
4036                         ext4_mb_release_desc(&e4b);
4037                         BUG_ON(bitmap_bh == NULL);
4038                 }
4039
4040                 ext4_lock_group(sb, group);
4041                 list_del(&pa->pa_group_list);
4042                 ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa);
4043                 ext4_unlock_group(sb, group);
4044
4045                 ext4_mb_release_desc(&e4b);
4046                 put_bh(bitmap_bh);
4047
4048                 list_del(&pa->u.pa_tmp_list);
4049                 call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
4050         }
4051 }
4052
4053 /*
4054  * finds all preallocated spaces and return blocks being freed to them
4055  * if preallocated space becomes full (no block is used from the space)
4056  * then the function frees space in buddy
4057  * XXX: at the moment, truncate (which is the only way to free blocks)
4058  * discards all preallocations
4059  */
4060 static void ext4_mb_return_to_preallocation(struct inode *inode,
4061                                         struct ext4_buddy *e4b,
4062                                         sector_t block, int count)
4063 {
4064         BUG_ON(!list_empty(&EXT4_I(inode)->i_prealloc_list));
4065 }
4066 #ifdef MB_DEBUG
4067 static void ext4_mb_show_ac(struct ext4_allocation_context *ac)
4068 {
4069         struct super_block *sb = ac->ac_sb;
4070         ext4_group_t i;
4071
4072         printk(KERN_ERR "EXT4-fs: Can't allocate:"
4073                         " Allocation context details:\n");
4074         printk(KERN_ERR "EXT4-fs: status %d flags %d\n",
4075                         ac->ac_status, ac->ac_flags);
4076         printk(KERN_ERR "EXT4-fs: orig %lu/%lu/%lu@%lu, goal %lu/%lu/%lu@%lu, "
4077                         "best %lu/%lu/%lu@%lu cr %d\n",
4078                         (unsigned long)ac->ac_o_ex.fe_group,
4079                         (unsigned long)ac->ac_o_ex.fe_start,
4080                         (unsigned long)ac->ac_o_ex.fe_len,
4081                         (unsigned long)ac->ac_o_ex.fe_logical,
4082                         (unsigned long)ac->ac_g_ex.fe_group,
4083                         (unsigned long)ac->ac_g_ex.fe_start,
4084                         (unsigned long)ac->ac_g_ex.fe_len,
4085                         (unsigned long)ac->ac_g_ex.fe_logical,
4086                         (unsigned long)ac->ac_b_ex.fe_group,
4087                         (unsigned long)ac->ac_b_ex.fe_start,
4088                         (unsigned long)ac->ac_b_ex.fe_len,
4089                         (unsigned long)ac->ac_b_ex.fe_logical,
4090                         (int)ac->ac_criteria);
4091         printk(KERN_ERR "EXT4-fs: %lu scanned, %d found\n", ac->ac_ex_scanned,
4092                 ac->ac_found);
4093         printk(KERN_ERR "EXT4-fs: groups: \n");
4094         for (i = 0; i < EXT4_SB(sb)->s_groups_count; i++) {
4095                 struct ext4_group_info *grp = ext4_get_group_info(sb, i);
4096                 struct ext4_prealloc_space *pa;
4097                 ext4_grpblk_t start;
4098                 struct list_head *cur;
4099                 ext4_lock_group(sb, i);
4100                 list_for_each(cur, &grp->bb_prealloc_list) {
4101                         pa = list_entry(cur, struct ext4_prealloc_space,
4102                                         pa_group_list);
4103                         spin_lock(&pa->pa_lock);
4104                         ext4_get_group_no_and_offset(sb, pa->pa_pstart,
4105                                                      NULL, &start);
4106                         spin_unlock(&pa->pa_lock);
4107                         printk(KERN_ERR "PA:%lu:%d:%u \n", i,
4108                                                         start, pa->pa_len);
4109                 }
4110                 ext4_lock_group(sb, i);
4111
4112                 if (grp->bb_free == 0)
4113                         continue;
4114                 printk(KERN_ERR "%lu: %d/%d \n",
4115                        i, grp->bb_free, grp->bb_fragments);
4116         }
4117         printk(KERN_ERR "\n");
4118 }
4119 #else
4120 static inline void ext4_mb_show_ac(struct ext4_allocation_context *ac)
4121 {
4122         return;
4123 }
4124 #endif
4125
4126 /*
4127  * We use locality group preallocation for small size file. The size of the
4128  * file is determined by the current size or the resulting size after
4129  * allocation which ever is larger
4130  *
4131  * One can tune this size via /proc/fs/ext4/<partition>/stream_req
4132  */
4133 static void ext4_mb_group_or_file(struct ext4_allocation_context *ac)
4134 {
4135         struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
4136         int bsbits = ac->ac_sb->s_blocksize_bits;
4137         loff_t size, isize;
4138
4139         if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
4140                 return;
4141
4142         size = ac->ac_o_ex.fe_logical + ac->ac_o_ex.fe_len;
4143         isize = i_size_read(ac->ac_inode) >> bsbits;
4144         size = max(size, isize);
4145
4146         /* don't use group allocation for large files */
4147         if (size >= sbi->s_mb_stream_request)
4148                 return;
4149
4150         if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
4151                 return;
4152
4153         BUG_ON(ac->ac_lg != NULL);
4154         /*
4155          * locality group prealloc space are per cpu. The reason for having
4156          * per cpu locality group is to reduce the contention between block
4157          * request from multiple CPUs.
4158          */
4159         ac->ac_lg = &sbi->s_locality_groups[get_cpu()];
4160         put_cpu();
4161
4162         /* we're going to use group allocation */
4163         ac->ac_flags |= EXT4_MB_HINT_GROUP_ALLOC;
4164
4165         /* serialize all allocations in the group */
4166         mutex_lock(&ac->ac_lg->lg_mutex);
4167 }
4168
4169 static noinline_for_stack int
4170 ext4_mb_initialize_context(struct ext4_allocation_context *ac,
4171                                 struct ext4_allocation_request *ar)
4172 {
4173         struct super_block *sb = ar->inode->i_sb;
4174         struct ext4_sb_info *sbi = EXT4_SB(sb);
4175         struct ext4_super_block *es = sbi->s_es;
4176         ext4_group_t group;
4177         unsigned long len;
4178         unsigned long goal;
4179         ext4_grpblk_t block;
4180
4181         /* we can't allocate > group size */
4182         len = ar->len;
4183
4184         /* just a dirty hack to filter too big requests  */
4185         if (len >= EXT4_BLOCKS_PER_GROUP(sb) - 10)
4186                 len = EXT4_BLOCKS_PER_GROUP(sb) - 10;
4187
4188         /* start searching from the goal */
4189         goal = ar->goal;
4190         if (goal < le32_to_cpu(es->s_first_data_block) ||
4191                         goal >= ext4_blocks_count(es))
4192                 goal = le32_to_cpu(es->s_first_data_block);
4193         ext4_get_group_no_and_offset(sb, goal, &group, &block);
4194
4195         /* set up allocation goals */
4196         ac->ac_b_ex.fe_logical = ar->logical;
4197         ac->ac_b_ex.fe_group = 0;
4198         ac->ac_b_ex.fe_start = 0;
4199         ac->ac_b_ex.fe_len = 0;
4200         ac->ac_status = AC_STATUS_CONTINUE;
4201         ac->ac_groups_scanned = 0;
4202         ac->ac_ex_scanned = 0;
4203         ac->ac_found = 0;
4204         ac->ac_sb = sb;
4205         ac->ac_inode = ar->inode;
4206         ac->ac_o_ex.fe_logical = ar->logical;
4207         ac->ac_o_ex.fe_group = group;
4208         ac->ac_o_ex.fe_start = block;
4209         ac->ac_o_ex.fe_len = len;
4210         ac->ac_g_ex.fe_logical = ar->logical;
4211         ac->ac_g_ex.fe_group = group;
4212         ac->ac_g_ex.fe_start = block;
4213         ac->ac_g_ex.fe_len = len;
4214         ac->ac_f_ex.fe_len = 0;
4215         ac->ac_flags = ar->flags;
4216         ac->ac_2order = 0;
4217         ac->ac_criteria = 0;
4218         ac->ac_pa = NULL;
4219         ac->ac_bitmap_page = NULL;
4220         ac->ac_buddy_page = NULL;
4221         ac->ac_lg = NULL;
4222
4223         /* we have to define context: we'll we work with a file or
4224          * locality group. this is a policy, actually */
4225         ext4_mb_group_or_file(ac);
4226
4227         mb_debug("init ac: %u blocks @ %u, goal %u, flags %x, 2^%d, "
4228                         "left: %u/%u, right %u/%u to %swritable\n",
4229                         (unsigned) ar->len, (unsigned) ar->logical,
4230                         (unsigned) ar->goal, ac->ac_flags, ac->ac_2order,
4231                         (unsigned) ar->lleft, (unsigned) ar->pleft,
4232                         (unsigned) ar->lright, (unsigned) ar->pright,
4233                         atomic_read(&ar->inode->i_writecount) ? "" : "non-");
4234         return 0;
4235
4236 }
4237
4238 /*
4239  * release all resource we used in allocation
4240  */
4241 static int ext4_mb_release_context(struct ext4_allocation_context *ac)
4242 {
4243         if (ac->ac_pa) {
4244                 if (ac->ac_pa->pa_linear) {
4245                         /* see comment in ext4_mb_use_group_pa() */
4246                         spin_lock(&ac->ac_pa->pa_lock);
4247                         ac->ac_pa->pa_pstart += ac->ac_b_ex.fe_len;
4248                         ac->ac_pa->pa_lstart += ac->ac_b_ex.fe_len;
4249                         ac->ac_pa->pa_free -= ac->ac_b_ex.fe_len;
4250                         ac->ac_pa->pa_len -= ac->ac_b_ex.fe_len;
4251                         spin_unlock(&ac->ac_pa->pa_lock);
4252                 }
4253                 ext4_mb_put_pa(ac, ac->ac_sb, ac->ac_pa);
4254         }
4255         if (ac->ac_bitmap_page)
4256                 page_cache_release(ac->ac_bitmap_page);
4257         if (ac->ac_buddy_page)
4258                 page_cache_release(ac->ac_buddy_page);
4259         if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
4260                 mutex_unlock(&ac->ac_lg->lg_mutex);
4261         ext4_mb_collect_stats(ac);
4262         return 0;
4263 }
4264
4265 static int ext4_mb_discard_preallocations(struct super_block *sb, int needed)
4266 {
4267         ext4_group_t i;
4268         int ret;
4269         int freed = 0;
4270
4271         for (i = 0; i < EXT4_SB(sb)->s_groups_count && needed > 0; i++) {
4272                 ret = ext4_mb_discard_group_preallocations(sb, i, needed);
4273                 freed += ret;
4274                 needed -= ret;
4275         }
4276
4277         return freed;
4278 }
4279
4280 /*
4281  * Main entry point into mballoc to allocate blocks
4282  * it tries to use preallocation first, then falls back
4283  * to usual allocation
4284  */
4285 ext4_fsblk_t ext4_mb_new_blocks(handle_t *handle,
4286                                  struct ext4_allocation_request *ar, int *errp)
4287 {
4288         struct ext4_allocation_context *ac = NULL;
4289         struct ext4_sb_info *sbi;
4290         struct super_block *sb;
4291         ext4_fsblk_t block = 0;
4292         int freed;
4293         int inquota;
4294
4295         sb = ar->inode->i_sb;
4296         sbi = EXT4_SB(sb);
4297
4298         if (!test_opt(sb, MBALLOC)) {
4299                 block = ext4_new_blocks_old(handle, ar->inode, ar->goal,
4300                                             &(ar->len), errp);
4301                 return block;
4302         }
4303
4304         while (ar->len && DQUOT_ALLOC_BLOCK(ar->inode, ar->len)) {
4305                 ar->flags |= EXT4_MB_HINT_NOPREALLOC;
4306                 ar->len--;
4307         }
4308         if (ar->len == 0) {
4309                 *errp = -EDQUOT;
4310                 return 0;
4311         }
4312         inquota = ar->len;
4313
4314         ac = kmem_cache_alloc(ext4_ac_cachep, GFP_NOFS);
4315         if (!ac) {
4316                 *errp = -ENOMEM;
4317                 return 0;
4318         }
4319
4320         ext4_mb_poll_new_transaction(sb, handle);
4321
4322         *errp = ext4_mb_initialize_context(ac, ar);
4323         if (*errp) {
4324                 ar->len = 0;
4325                 goto out;
4326         }
4327
4328         ac->ac_op = EXT4_MB_HISTORY_PREALLOC;
4329         if (!ext4_mb_use_preallocated(ac)) {
4330
4331                 ac->ac_op = EXT4_MB_HISTORY_ALLOC;
4332                 ext4_mb_normalize_request(ac, ar);
4333
4334 repeat:
4335                 /* allocate space in core */
4336                 ext4_mb_regular_allocator(ac);
4337
4338                 /* as we've just preallocated more space than
4339                  * user requested orinally, we store allocated
4340                  * space in a special descriptor */
4341                 if (ac->ac_status == AC_STATUS_FOUND &&
4342                                 ac->ac_o_ex.fe_len < ac->ac_b_ex.fe_len)
4343                         ext4_mb_new_preallocation(ac);
4344         }
4345
4346         if (likely(ac->ac_status == AC_STATUS_FOUND)) {
4347                 ext4_mb_mark_diskspace_used(ac, handle);
4348                 *errp = 0;
4349                 block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
4350                 ar->len = ac->ac_b_ex.fe_len;
4351         } else {
4352                 freed  = ext4_mb_discard_preallocations(sb, ac->ac_o_ex.fe_len);
4353                 if (freed)
4354                         goto repeat;
4355                 *errp = -ENOSPC;
4356                 ac->ac_b_ex.fe_len = 0;
4357                 ar->len = 0;
4358                 ext4_mb_show_ac(ac);
4359         }
4360
4361         ext4_mb_release_context(ac);
4362
4363 out:
4364         if (ar->len < inquota)
4365                 DQUOT_FREE_BLOCK(ar->inode, inquota - ar->len);
4366
4367         kmem_cache_free(ext4_ac_cachep, ac);
4368         return block;
4369 }
4370 static void ext4_mb_poll_new_transaction(struct super_block *sb,
4371                                                 handle_t *handle)
4372 {
4373         struct ext4_sb_info *sbi = EXT4_SB(sb);
4374
4375         if (sbi->s_last_transaction == handle->h_transaction->t_tid)
4376                 return;
4377
4378         /* new transaction! time to close last one and free blocks for
4379          * committed transaction. we know that only transaction can be
4380          * active, so previos transaction can be being logged and we
4381          * know that transaction before previous is known to be already
4382          * logged. this means that now we may free blocks freed in all
4383          * transactions before previous one. hope I'm clear enough ... */
4384
4385         spin_lock(&sbi->s_md_lock);
4386         if (sbi->s_last_transaction != handle->h_transaction->t_tid) {
4387                 mb_debug("new transaction %lu, old %lu\n",
4388                                 (unsigned long) handle->h_transaction->t_tid,
4389                                 (unsigned long) sbi->s_last_transaction);
4390                 list_splice_init(&sbi->s_closed_transaction,
4391                                 &sbi->s_committed_transaction);
4392                 list_splice_init(&sbi->s_active_transaction,
4393                                 &sbi->s_closed_transaction);
4394                 sbi->s_last_transaction = handle->h_transaction->t_tid;
4395         }
4396         spin_unlock(&sbi->s_md_lock);
4397
4398         ext4_mb_free_committed_blocks(sb);
4399 }
4400
4401 static noinline_for_stack int
4402 ext4_mb_free_metadata(handle_t *handle, struct ext4_buddy *e4b,
4403                           ext4_group_t group, ext4_grpblk_t block, int count)
4404 {
4405         struct ext4_group_info *db = e4b->bd_info;
4406         struct super_block *sb = e4b->bd_sb;
4407         struct ext4_sb_info *sbi = EXT4_SB(sb);
4408         struct ext4_free_metadata *md;
4409         int i;
4410
4411         BUG_ON(e4b->bd_bitmap_page == NULL);
4412         BUG_ON(e4b->bd_buddy_page == NULL);
4413
4414         ext4_lock_group(sb, group);
4415         for (i = 0; i < count; i++) {
4416                 md = db->bb_md_cur;
4417                 if (md && db->bb_tid != handle->h_transaction->t_tid) {
4418                         db->bb_md_cur = NULL;
4419                         md = NULL;
4420                 }
4421
4422                 if (md == NULL) {
4423                         ext4_unlock_group(sb, group);
4424                         md = kmalloc(sizeof(*md), GFP_NOFS);
4425                         if (md == NULL)
4426                                 return -ENOMEM;
4427                         md->num = 0;
4428                         md->group = group;
4429
4430                         ext4_lock_group(sb, group);
4431                         if (db->bb_md_cur == NULL) {
4432                                 spin_lock(&sbi->s_md_lock);
4433                                 list_add(&md->list, &sbi->s_active_transaction);
4434                                 spin_unlock(&sbi->s_md_lock);
4435                                 /* protect buddy cache from being freed,
4436                                  * otherwise we'll refresh it from
4437                                  * on-disk bitmap and lose not-yet-available
4438                                  * blocks */
4439                                 page_cache_get(e4b->bd_buddy_page);
4440                                 page_cache_get(e4b->bd_bitmap_page);
4441                                 db->bb_md_cur = md;
4442                                 db->bb_tid = handle->h_transaction->t_tid;
4443                                 mb_debug("new md 0x%p for group %lu\n",
4444                                                 md, md->group);
4445                         } else {
4446                                 kfree(md);
4447                                 md = db->bb_md_cur;
4448                         }
4449                 }
4450
4451                 BUG_ON(md->num >= EXT4_BB_MAX_BLOCKS);
4452                 md->blocks[md->num] = block + i;
4453                 md->num++;
4454                 if (md->num == EXT4_BB_MAX_BLOCKS) {
4455                         /* no more space, put full container on a sb's list */
4456                         db->bb_md_cur = NULL;
4457                 }
4458         }
4459         ext4_unlock_group(sb, group);
4460         return 0;
4461 }
4462
4463 /*
4464  * Main entry point into mballoc to free blocks
4465  */
4466 void ext4_mb_free_blocks(handle_t *handle, struct inode *inode,
4467                         unsigned long block, unsigned long count,
4468                         int metadata, unsigned long *freed)
4469 {
4470         struct buffer_head *bitmap_bh = NULL;
4471         struct super_block *sb = inode->i_sb;
4472         struct ext4_allocation_context *ac = NULL;
4473         struct ext4_group_desc *gdp;
4474         struct ext4_super_block *es;
4475         unsigned long overflow;
4476         ext4_grpblk_t bit;
4477         struct buffer_head *gd_bh;
4478         ext4_group_t block_group;
4479         struct ext4_sb_info *sbi;
4480         struct ext4_buddy e4b;
4481         int err = 0;
4482         int ret;
4483
4484         *freed = 0;
4485
4486         ext4_mb_poll_new_transaction(sb, handle);
4487
4488         sbi = EXT4_SB(sb);
4489         es = EXT4_SB(sb)->s_es;
4490         if (block < le32_to_cpu(es->s_first_data_block) ||
4491             block + count < block ||
4492             block + count > ext4_blocks_count(es)) {
4493                 ext4_error(sb, __FUNCTION__,
4494                             "Freeing blocks not in datazone - "
4495                             "block = %lu, count = %lu", block, count);
4496                 goto error_return;
4497         }
4498
4499         ext4_debug("freeing block %lu\n", block);
4500
4501         ac = kmem_cache_alloc(ext4_ac_cachep, GFP_NOFS);
4502         if (ac) {
4503                 ac->ac_op = EXT4_MB_HISTORY_FREE;
4504                 ac->ac_inode = inode;
4505                 ac->ac_sb = sb;
4506         }
4507
4508 do_more:
4509         overflow = 0;
4510         ext4_get_group_no_and_offset(sb, block, &block_group, &bit);
4511
4512         /*
4513          * Check to see if we are freeing blocks across a group
4514          * boundary.
4515          */
4516         if (bit + count > EXT4_BLOCKS_PER_GROUP(sb)) {
4517                 overflow = bit + count - EXT4_BLOCKS_PER_GROUP(sb);
4518                 count -= overflow;
4519         }
4520         bitmap_bh = read_block_bitmap(sb, block_group);
4521         if (!bitmap_bh)
4522                 goto error_return;
4523         gdp = ext4_get_group_desc(sb, block_group, &gd_bh);
4524         if (!gdp)
4525                 goto error_return;
4526
4527         if (in_range(ext4_block_bitmap(sb, gdp), block, count) ||
4528             in_range(ext4_inode_bitmap(sb, gdp), block, count) ||
4529             in_range(block, ext4_inode_table(sb, gdp),
4530                       EXT4_SB(sb)->s_itb_per_group) ||
4531             in_range(block + count - 1, ext4_inode_table(sb, gdp),
4532                       EXT4_SB(sb)->s_itb_per_group)) {
4533
4534                 ext4_error(sb, __FUNCTION__,
4535                            "Freeing blocks in system zone - "
4536                            "Block = %lu, count = %lu", block, count);
4537         }
4538
4539         BUFFER_TRACE(bitmap_bh, "getting write access");
4540         err = ext4_journal_get_write_access(handle, bitmap_bh);
4541         if (err)
4542                 goto error_return;
4543
4544         /*
4545          * We are about to modify some metadata.  Call the journal APIs
4546          * to unshare ->b_data if a currently-committing transaction is
4547          * using it
4548          */
4549         BUFFER_TRACE(gd_bh, "get_write_access");
4550         err = ext4_journal_get_write_access(handle, gd_bh);
4551         if (err)
4552                 goto error_return;
4553
4554         err = ext4_mb_load_buddy(sb, block_group, &e4b);
4555         if (err)
4556                 goto error_return;
4557
4558 #ifdef AGGRESSIVE_CHECK
4559         {
4560                 int i;
4561                 for (i = 0; i < count; i++)
4562                         BUG_ON(!mb_test_bit(bit + i, bitmap_bh->b_data));
4563         }
4564 #endif
4565         mb_clear_bits(sb_bgl_lock(sbi, block_group), bitmap_bh->b_data,
4566                         bit, count);
4567
4568         /* We dirtied the bitmap block */
4569         BUFFER_TRACE(bitmap_bh, "dirtied bitmap block");
4570         err = ext4_journal_dirty_metadata(handle, bitmap_bh);
4571
4572         if (ac) {
4573                 ac->ac_b_ex.fe_group = block_group;
4574                 ac->ac_b_ex.fe_start = bit;
4575                 ac->ac_b_ex.fe_len = count;
4576                 ext4_mb_store_history(ac);
4577         }
4578
4579         if (metadata) {
4580                 /* blocks being freed are metadata. these blocks shouldn't
4581                  * be used until this transaction is committed */
4582                 ext4_mb_free_metadata(handle, &e4b, block_group, bit, count);
4583         } else {
4584                 ext4_lock_group(sb, block_group);
4585                 err = mb_free_blocks(inode, &e4b, bit, count);
4586                 ext4_mb_return_to_preallocation(inode, &e4b, block, count);
4587                 ext4_unlock_group(sb, block_group);
4588                 BUG_ON(err != 0);
4589         }
4590
4591         spin_lock(sb_bgl_lock(sbi, block_group));
4592         le16_add_cpu(&gdp->bg_free_blocks_count, count);
4593         gdp->bg_checksum = ext4_group_desc_csum(sbi, block_group, gdp);
4594         spin_unlock(sb_bgl_lock(sbi, block_group));
4595         percpu_counter_add(&sbi->s_freeblocks_counter, count);
4596
4597         ext4_mb_release_desc(&e4b);
4598
4599         *freed += count;
4600
4601         /* And the group descriptor block */
4602         BUFFER_TRACE(gd_bh, "dirtied group descriptor block");
4603         ret = ext4_journal_dirty_metadata(handle, gd_bh);
4604         if (!err)
4605                 err = ret;
4606
4607         if (overflow && !err) {
4608                 block += count;
4609                 count = overflow;
4610                 put_bh(bitmap_bh);
4611                 goto do_more;
4612         }
4613         sb->s_dirt = 1;
4614 error_return:
4615         brelse(bitmap_bh);
4616         ext4_std_error(sb, err);
4617         if (ac)
4618                 kmem_cache_free(ext4_ac_cachep, ac);
4619         return;
4620 }