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