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