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