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