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