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