Whamcloud - gitweb
fa8b4ae604e682d442e3cb5a5bad0f2b1a07fdda
[fs/lustre-release.git] / ldiskfs / kernel_patches / patches / ext3-mballoc3-core.patch
1 Index: linux-2.6.22.19/include/linux/ext3_fs.h
2 ===================================================================
3 --- linux-2.6.22.19.orig/include/linux/ext3_fs.h
4 +++ linux-2.6.22.19/include/linux/ext3_fs.h
5 @@ -54,6 +54,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 @@ -412,6 +437,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 @@ -813,6 +846,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 @@ -859,6 +906,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-2.6.22.19/include/linux/ext3_fs_sb.h
85 ===================================================================
86 --- linux-2.6.22.19.orig/include/linux/ext3_fs_sb.h
87 +++ linux-2.6.22.19/include/linux/ext3_fs_sb.h
88 @@ -88,6 +88,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-2.6.22.19/fs/ext3/super.c
158 ===================================================================
159 --- linux-2.6.22.19.orig/fs/ext3/super.c
160 +++ linux-2.6.22.19/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;
164  
165 +       ext3_mb_release(sb);
166         ext3_ext_release(sb);
167         ext3_xattr_put_super(sb);
168         journal_destroy(sbi->s_journal);
169 @@ -434,6 +435,10 @@ static void ext3_put_super (struct super
170                 invalidate_bdev(sbi->journal_bdev);
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 @@ -459,6 +464,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 @@ -1434,6 +1441,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 @@ -1448,6 +1456,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 @@ -1857,6 +1881,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 @@ -2787,9 +2815,46 @@ static struct file_system_type ext3_fs_t
232         .fs_flags       = FS_REQUIRES_DEV,
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 @@ -2811,6 +2876,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-2.6.22.19/fs/ext3/mballoc.c
288 ===================================================================
289 --- /dev/null
290 +++ linux-2.6.22.19/fs/ext3/mballoc.c
291 @@ -0,0 +1,4475 @@
292 +/*
293 + * Copyright 2008 Sun Microsystems, Inc.
294 + * Written by Alex Tomas <alex@clusterfs.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 +       if (page == NULL || !PageUptodate(page))
1373 +               goto err;
1374 +       e3b->bd_bitmap_page = page;
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 +       if (page == NULL || !PageUptodate(page))
1396 +               goto err;
1397 +       e3b->bd_buddy_page = page;
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 +               mb_clear_bit_atomic(lock, cur, bm);
1460 +               cur++;
1461 +       }
1462 +}
1463 +
1464 +static inline void mb_set_bits(spinlock_t *lock, void *bm, int cur, int len)
1465 +{
1466 +       __u32 *addr;
1467 +
1468 +       len = cur + len;
1469 +       while (cur < len) {
1470 +               if ((cur & 31) == 0 && (len - cur) >= 32) {
1471 +                       /* fast path: clear whole word at once */
1472 +                       addr = bm + (cur >> 3);
1473 +                       *addr = 0xffffffff;
1474 +                       cur += 32;
1475 +                       continue;
1476 +               }
1477 +               mb_set_bit_atomic(lock, cur, bm);
1478 +               cur++;
1479 +       }
1480 +}
1481 +
1482 +static int mb_free_blocks(struct inode *inode, struct ext3_buddy *e3b,
1483 +                         int first, int count)
1484 +{
1485 +       int block = 0, max = 0, order;
1486 +       void *buddy, *buddy2;
1487 +       struct super_block *sb = e3b->bd_sb;
1488 +
1489 +       BUG_ON(first + count > (sb->s_blocksize << 3));
1490 +       BUG_ON(!ext3_is_group_locked(sb, e3b->bd_group));
1491 +       mb_check_buddy(e3b);
1492 +       mb_free_blocks_double(inode, e3b, first, count);
1493 +
1494 +       e3b->bd_info->bb_free += count;
1495 +       if (first < e3b->bd_info->bb_first_free)
1496 +               e3b->bd_info->bb_first_free = first;
1497 +
1498 +       /* let's maintain fragments counter */
1499 +       if (first != 0)
1500 +               block = !mb_test_bit(first - 1, EXT3_MB_BITMAP(e3b));
1501 +       if (first + count < EXT3_SB(sb)->s_mb_maxs[0])
1502 +               max = !mb_test_bit(first + count, EXT3_MB_BITMAP(e3b));
1503 +       if (block && max)
1504 +               e3b->bd_info->bb_fragments--;
1505 +       else if (!block && !max)
1506 +               e3b->bd_info->bb_fragments++;
1507 +
1508 +       /* let's maintain buddy itself */
1509 +       while (count-- > 0) {
1510 +               block = first++;
1511 +               order = 0;
1512 +
1513 +               if (!mb_test_bit(block, EXT3_MB_BITMAP(e3b))) {
1514 +                       unsigned long blocknr;
1515 +                       blocknr = e3b->bd_group * EXT3_BLOCKS_PER_GROUP(sb);
1516 +                       blocknr += block;
1517 +                       blocknr +=
1518 +                           le32_to_cpu(EXT3_SB(sb)->s_es->s_first_data_block);
1519 +
1520 +                       ext3_error(sb, __FUNCTION__, "double-free of inode"
1521 +                                  " %lu's block %lu(bit %u in group %u)\n",
1522 +                                  inode ? inode->i_ino : 0, blocknr, block,
1523 +                                  e3b->bd_group);
1524 +               }
1525 +               mb_clear_bit(block, EXT3_MB_BITMAP(e3b));
1526 +               e3b->bd_info->bb_counters[order]++;
1527 +
1528 +               /* start of the buddy */
1529 +               buddy = mb_find_buddy(e3b, order, &max);
1530 +
1531 +               do {
1532 +                       block &= ~1UL;
1533 +                       if (mb_test_bit(block, buddy) ||
1534 +                                       mb_test_bit(block + 1, buddy))
1535 +                               break;
1536 +
1537 +                       /* both the buddies are free, try to coalesce them */
1538 +                       buddy2 = mb_find_buddy(e3b, order + 1, &max);
1539 +
1540 +                       if (!buddy2)
1541 +                               break;
1542 +
1543 +                       if (order > 0) {
1544 +                               /* for special purposes, we don't set
1545 +                                * free bits in bitmap */
1546 +                               mb_set_bit(block, buddy);
1547 +                               mb_set_bit(block + 1, buddy);
1548 +                       }
1549 +                       e3b->bd_info->bb_counters[order]--;
1550 +                       e3b->bd_info->bb_counters[order]--;
1551 +
1552 +                       block = block >> 1;
1553 +                       order++;
1554 +                       e3b->bd_info->bb_counters[order]++;
1555 +
1556 +                       mb_clear_bit(block, buddy2);
1557 +                       buddy = buddy2;
1558 +               } while (1);
1559 +       }
1560 +       mb_check_buddy(e3b);
1561 +
1562 +       return 0;
1563 +}
1564 +
1565 +static int mb_find_extent(struct ext3_buddy *e3b, int order, int block,
1566 +                               int needed, struct ext3_free_extent *ex)
1567 +{
1568 +       int next = block, max, ord;
1569 +       void *buddy;
1570 +
1571 +       BUG_ON(!ext3_is_group_locked(e3b->bd_sb, e3b->bd_group));
1572 +       BUG_ON(ex == NULL);
1573 +
1574 +       buddy = mb_find_buddy(e3b, order, &max);
1575 +       BUG_ON(buddy == NULL);
1576 +       BUG_ON(block >= max);
1577 +       if (mb_test_bit(block, buddy)) {
1578 +               ex->fe_len = 0;
1579 +               ex->fe_start = 0;
1580 +               ex->fe_group = 0;
1581 +               return 0;
1582 +       }
1583 +
1584 +       if (likely(order == 0)) {
1585 +               /* find actual order */
1586 +               order = mb_find_order_for_block(e3b, block);
1587 +               block = block >> order;
1588 +       }
1589 +
1590 +       ex->fe_len = 1 << order;
1591 +       ex->fe_start = block << order;
1592 +       ex->fe_group = e3b->bd_group;
1593 +
1594 +       /* calc difference from given start */
1595 +       next = next - ex->fe_start;
1596 +       ex->fe_len -= next;
1597 +       ex->fe_start += next;
1598 +
1599 +       while (needed > ex->fe_len && (buddy = mb_find_buddy(e3b, order, &max))) {
1600 +
1601 +               if (block + 1 >= max)
1602 +                       break;
1603 +
1604 +               next = (block + 1) * (1 << order);
1605 +               if (mb_test_bit(next, EXT3_MB_BITMAP(e3b)))
1606 +                       break;
1607 +
1608 +               ord = mb_find_order_for_block(e3b, next);
1609 +
1610 +               order = ord;
1611 +               block = next >> order;
1612 +               ex->fe_len += 1 << order;
1613 +       }
1614 +
1615 +       BUG_ON(ex->fe_start + ex->fe_len > (1 << (e3b->bd_blkbits + 3)));
1616 +       return ex->fe_len;
1617 +}
1618 +
1619 +static int mb_mark_used(struct ext3_buddy *e3b, struct ext3_free_extent *ex)
1620 +{
1621 +       int ord, mlen = 0, max = 0, cur;
1622 +       int start = ex->fe_start;
1623 +       int len = ex->fe_len;
1624 +       unsigned ret = 0;
1625 +       int len0 = len;
1626 +       void *buddy;
1627 +
1628 +       BUG_ON(start + len > (e3b->bd_sb->s_blocksize << 3));
1629 +       BUG_ON(e3b->bd_group != ex->fe_group);
1630 +       BUG_ON(!ext3_is_group_locked(e3b->bd_sb, e3b->bd_group));
1631 +       mb_check_buddy(e3b);
1632 +       mb_mark_used_double(e3b, start, len);
1633 +
1634 +       e3b->bd_info->bb_free -= len;
1635 +       if (e3b->bd_info->bb_first_free == start)
1636 +               e3b->bd_info->bb_first_free += len;
1637 +
1638 +       /* let's maintain fragments counter */
1639 +       if (start != 0)
1640 +               mlen = !mb_test_bit(start - 1, EXT3_MB_BITMAP(e3b));
1641 +       if (start + len < EXT3_SB(e3b->bd_sb)->s_mb_maxs[0])
1642 +               max = !mb_test_bit(start + len, EXT3_MB_BITMAP(e3b));
1643 +       if (mlen && max)
1644 +               e3b->bd_info->bb_fragments++;
1645 +       else if (!mlen && !max)
1646 +               e3b->bd_info->bb_fragments--;
1647 +
1648 +       /* let's maintain buddy itself */
1649 +       while (len) {
1650 +               ord = mb_find_order_for_block(e3b, start);
1651 +
1652 +               if (((start >> ord) << ord) == start && len >= (1 << ord)) {
1653 +                       /* the whole chunk may be allocated at once! */
1654 +                       mlen = 1 << ord;
1655 +                       buddy = mb_find_buddy(e3b, ord, &max);
1656 +                       BUG_ON((start >> ord) >= max);
1657 +                       mb_set_bit(start >> ord, buddy);
1658 +                       e3b->bd_info->bb_counters[ord]--;
1659 +                       start += mlen;
1660 +                       len -= mlen;
1661 +                       BUG_ON(len < 0);
1662 +                       continue;
1663 +               }
1664 +
1665 +               /* store for history */
1666 +               if (ret == 0)
1667 +                       ret = len | (ord << 16);
1668 +
1669 +               /* we have to split large buddy */
1670 +               BUG_ON(ord <= 0);
1671 +               buddy = mb_find_buddy(e3b, ord, &max);
1672 +               mb_set_bit(start >> ord, buddy);
1673 +               e3b->bd_info->bb_counters[ord]--;
1674 +
1675 +               ord--;
1676 +               cur = (start >> ord) & ~1U;
1677 +               buddy = mb_find_buddy(e3b, ord, &max);
1678 +               mb_clear_bit(cur, buddy);
1679 +               mb_clear_bit(cur + 1, buddy);
1680 +               e3b->bd_info->bb_counters[ord]++;
1681 +               e3b->bd_info->bb_counters[ord]++;
1682 +       }
1683 +
1684 +       mb_set_bits(sb_bgl_lock(EXT3_SB(e3b->bd_sb), ex->fe_group),
1685 +                   EXT3_MB_BITMAP(e3b), ex->fe_start, len0);
1686 +       mb_check_buddy(e3b);
1687 +
1688 +       return ret;
1689 +}
1690 +
1691 +/*
1692 + * Must be called under group lock!
1693 + */
1694 +static void ext3_mb_use_best_found(struct ext3_allocation_context *ac,
1695 +                                       struct ext3_buddy *e3b)
1696 +{
1697 +       struct ext3_sb_info *sbi = EXT3_SB(ac->ac_sb);
1698 +       unsigned long ret;
1699 +
1700 +       BUG_ON(ac->ac_b_ex.fe_group != e3b->bd_group);
1701 +       BUG_ON(ac->ac_status == AC_STATUS_FOUND);
1702 +
1703 +       ac->ac_b_ex.fe_len = min(ac->ac_b_ex.fe_len, ac->ac_g_ex.fe_len);
1704 +       ac->ac_b_ex.fe_logical = ac->ac_g_ex.fe_logical;
1705 +       ret = mb_mark_used(e3b, &ac->ac_b_ex);
1706 +
1707 +       /* preallocation can change ac_b_ex, thus we store actually
1708 +        * allocated blocks for history */
1709 +       ac->ac_f_ex = ac->ac_b_ex;
1710 +
1711 +       ac->ac_status = AC_STATUS_FOUND;
1712 +       ac->ac_tail = ret & 0xffff;
1713 +       ac->ac_buddy = ret >> 16;
1714 +
1715 +       /* XXXXXXX: SUCH A HORRIBLE **CK */
1716 +       ac->ac_bitmap_page = e3b->bd_bitmap_page;
1717 +       get_page(ac->ac_bitmap_page);
1718 +       ac->ac_buddy_page = e3b->bd_buddy_page;
1719 +       get_page(ac->ac_buddy_page);
1720 +
1721 +       /* store last allocated for subsequent stream allocation */
1722 +       if ((ac->ac_flags & EXT3_MB_HINT_DATA)) {
1723 +               spin_lock(&sbi->s_md_lock);
1724 +               sbi->s_mb_last_group = ac->ac_f_ex.fe_group;
1725 +               sbi->s_mb_last_start = ac->ac_f_ex.fe_start;
1726 +               spin_unlock(&sbi->s_md_lock);
1727 +       }
1728 +}
1729 +
1730 +/*
1731 + * regular allocator, for general purposes allocation
1732 + */
1733 +
1734 +void ext3_mb_check_limits(struct ext3_allocation_context *ac,
1735 +                                       struct ext3_buddy *e3b,
1736 +                                       int finish_group)
1737 +{
1738 +       struct ext3_sb_info *sbi = EXT3_SB(ac->ac_sb);
1739 +       struct ext3_free_extent *bex = &ac->ac_b_ex;
1740 +       struct ext3_free_extent *gex = &ac->ac_g_ex;
1741 +       struct ext3_free_extent ex;
1742 +       int max;
1743 +
1744 +       /*
1745 +        * We don't want to scan for a whole year
1746 +        */
1747 +       if (ac->ac_found > sbi->s_mb_max_to_scan &&
1748 +                       !(ac->ac_flags & EXT3_MB_HINT_FIRST)) {
1749 +               ac->ac_status = AC_STATUS_BREAK;
1750 +               return;
1751 +       }
1752 +
1753 +       /*
1754 +        * Haven't found good chunk so far, let's continue
1755 +        */
1756 +       if (bex->fe_len < gex->fe_len)
1757 +               return;
1758 +
1759 +       if ((finish_group || ac->ac_found > sbi->s_mb_min_to_scan)
1760 +                       && bex->fe_group == e3b->bd_group) {
1761 +               /* recheck chunk's availability - we don't know
1762 +                * when it was found (within this lock-unlock
1763 +                * period or not) */
1764 +               max = mb_find_extent(e3b, 0, bex->fe_start, gex->fe_len, &ex);
1765 +               if (max >= gex->fe_len) {
1766 +                       ext3_mb_use_best_found(ac, e3b);
1767 +                       return;
1768 +               }
1769 +       }
1770 +}
1771 +
1772 +/*
1773 + * The routine checks whether found extent is good enough. If it is,
1774 + * then the extent gets marked used and flag is set to the context
1775 + * to stop scanning. Otherwise, the extent is compared with the
1776 + * previous found extent and if new one is better, then it's stored
1777 + * in the context. Later, the best found extent will be used, if
1778 + * mballoc can't find good enough extent.
1779 + *
1780 + * FIXME: real allocation policy is to be designed yet!
1781 + */
1782 +static void ext3_mb_measure_extent(struct ext3_allocation_context *ac,
1783 +                                       struct ext3_free_extent *ex,
1784 +                                       struct ext3_buddy *e3b)
1785 +{
1786 +       struct ext3_free_extent *bex = &ac->ac_b_ex;
1787 +       struct ext3_free_extent *gex = &ac->ac_g_ex;
1788 +
1789 +       BUG_ON(ex->fe_len <= 0);
1790 +       BUG_ON(ex->fe_len >= EXT3_BLOCKS_PER_GROUP(ac->ac_sb));
1791 +       BUG_ON(ex->fe_start >= EXT3_BLOCKS_PER_GROUP(ac->ac_sb));
1792 +       BUG_ON(ac->ac_status != AC_STATUS_CONTINUE);
1793 +
1794 +       ac->ac_found++;
1795 +
1796 +       /*
1797 +        * The special case - take what you catch first
1798 +        */
1799 +       if (unlikely(ac->ac_flags & EXT3_MB_HINT_FIRST)) {
1800 +               *bex = *ex;
1801 +               ext3_mb_use_best_found(ac, e3b);
1802 +               return;
1803 +       }
1804 +
1805 +       /*
1806 +        * Let's check whether the chuck is good enough
1807 +        */
1808 +       if (ex->fe_len == gex->fe_len) {
1809 +               *bex = *ex;
1810 +               ext3_mb_use_best_found(ac, e3b);
1811 +               return;
1812 +       }
1813 +
1814 +       /*
1815 +        * If this is first found extent, just store it in the context
1816 +        */
1817 +       if (bex->fe_len == 0) {
1818 +               *bex = *ex;
1819 +               return;
1820 +       }
1821 +
1822 +       /*
1823 +        * If new found extent is better, store it in the context
1824 +        */
1825 +       if (bex->fe_len < gex->fe_len) {
1826 +               /* if the request isn't satisfied, any found extent
1827 +                * larger than previous best one is better */
1828 +               if (ex->fe_len > bex->fe_len)
1829 +                       *bex = *ex;
1830 +       } else if (ex->fe_len > gex->fe_len) {
1831 +               /* if the request is satisfied, then we try to find
1832 +                * an extent that still satisfy the request, but is
1833 +                * smaller than previous one */
1834 +               if (ex->fe_len < bex->fe_len)
1835 +                       *bex = *ex;
1836 +       }
1837 +
1838 +       ext3_mb_check_limits(ac, e3b, 0);
1839 +}
1840 +
1841 +static int ext3_mb_try_best_found(struct ext3_allocation_context *ac,
1842 +                                       struct ext3_buddy *e3b)
1843 +{
1844 +       struct ext3_free_extent ex = ac->ac_b_ex;
1845 +       int group = ex.fe_group, max, err;
1846 +
1847 +       BUG_ON(ex.fe_len <= 0);
1848 +       err = ext3_mb_load_buddy(ac->ac_sb, group, e3b);
1849 +       if (err)
1850 +               return err;
1851 +
1852 +       ext3_lock_group(ac->ac_sb, group);
1853 +       max = mb_find_extent(e3b, 0, ex.fe_start, ex.fe_len, &ex);
1854 +
1855 +       if (max > 0) {
1856 +               ac->ac_b_ex = ex;
1857 +               ext3_mb_use_best_found(ac, e3b);
1858 +       }
1859 +
1860 +       ext3_unlock_group(ac->ac_sb, group);
1861 +       ext3_mb_release_desc(e3b);
1862 +
1863 +       return 0;
1864 +}
1865 +
1866 +static int ext3_mb_find_by_goal(struct ext3_allocation_context *ac,
1867 +                               struct ext3_buddy *e3b)
1868 +{
1869 +       int group = ac->ac_g_ex.fe_group, max, err;
1870 +       struct ext3_sb_info *sbi = EXT3_SB(ac->ac_sb);
1871 +       struct ext3_super_block *es = sbi->s_es;
1872 +       struct ext3_free_extent ex;
1873 +
1874 +       if (!(ac->ac_flags & EXT3_MB_HINT_TRY_GOAL))
1875 +               return 0;
1876 +
1877 +       err = ext3_mb_load_buddy(ac->ac_sb, group, e3b);
1878 +       if (err)
1879 +               return err;
1880 +
1881 +       ext3_lock_group(ac->ac_sb, group);
1882 +       max = mb_find_extent(e3b, 0, ac->ac_g_ex.fe_start,
1883 +                            ac->ac_g_ex.fe_len, &ex);
1884 +
1885 +       if (max >= ac->ac_g_ex.fe_len && ac->ac_g_ex.fe_len == sbi->s_stripe) {
1886 +               unsigned long start;
1887 +               start = (e3b->bd_group * EXT3_BLOCKS_PER_GROUP(ac->ac_sb) +
1888 +                       ex.fe_start + le32_to_cpu(es->s_first_data_block));
1889 +               if (start % sbi->s_stripe == 0) {
1890 +                       ac->ac_found++;
1891 +                       ac->ac_b_ex = ex;
1892 +                       ext3_mb_use_best_found(ac, e3b);
1893 +               }
1894 +       } else if (max >= ac->ac_g_ex.fe_len) {
1895 +               BUG_ON(ex.fe_len <= 0);
1896 +               BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
1897 +               BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
1898 +               ac->ac_found++;
1899 +               ac->ac_b_ex = ex;
1900 +               ext3_mb_use_best_found(ac, e3b);
1901 +       } else if (max > 0 && (ac->ac_flags & EXT3_MB_HINT_MERGE)) {
1902 +               /* Sometimes, caller may want to merge even small
1903 +                * number of blocks to an existing extent */
1904 +               BUG_ON(ex.fe_len <= 0);
1905 +               BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
1906 +               BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
1907 +               ac->ac_found++;
1908 +               ac->ac_b_ex = ex;
1909 +               ext3_mb_use_best_found(ac, e3b);
1910 +       }
1911 +       ext3_unlock_group(ac->ac_sb, group);
1912 +       ext3_mb_release_desc(e3b);
1913 +
1914 +       return 0;
1915 +}
1916 +
1917 +/*
1918 + * The routine scans buddy structures (not bitmap!) from given order
1919 + * to max order and tries to find big enough chunk to satisfy the req
1920 + */
1921 +static void ext3_mb_simple_scan_group(struct ext3_allocation_context *ac,
1922 +                                       struct ext3_buddy *e3b)
1923 +{
1924 +       struct super_block *sb = ac->ac_sb;
1925 +       struct ext3_group_info *grp = e3b->bd_info;
1926 +       void *buddy;
1927 +       int i, k, max;
1928 +
1929 +       BUG_ON(ac->ac_2order <= 0);
1930 +       for (i = ac->ac_2order; i <= sb->s_blocksize_bits + 1; i++) {
1931 +               if (grp->bb_counters[i] == 0)
1932 +                       continue;
1933 +
1934 +               buddy = mb_find_buddy(e3b, i, &max);
1935 +               BUG_ON(buddy == NULL);
1936 +
1937 +               k = mb_find_next_zero_bit(buddy, max, 0);
1938 +               BUG_ON(k >= max);
1939 +
1940 +               ac->ac_found++;
1941 +
1942 +               ac->ac_b_ex.fe_len = 1 << i;
1943 +               ac->ac_b_ex.fe_start = k << i;
1944 +               ac->ac_b_ex.fe_group = e3b->bd_group;
1945 +
1946 +               ext3_mb_use_best_found(ac, e3b);
1947 +
1948 +               BUG_ON(ac->ac_b_ex.fe_len != ac->ac_g_ex.fe_len);
1949 +
1950 +               if (EXT3_SB(sb)->s_mb_stats)
1951 +                       atomic_inc(&EXT3_SB(sb)->s_bal_2orders);
1952 +
1953 +               break;
1954 +       }
1955 +}
1956 +
1957 +/*
1958 + * The routine scans the group and measures all found extents.
1959 + * In order to optimize scanning, caller must pass number of
1960 + * free blocks in the group, so the routine can know upper limit.
1961 + */
1962 +static void ext3_mb_complex_scan_group(struct ext3_allocation_context *ac,
1963 +                                       struct ext3_buddy *e3b)
1964 +{
1965 +       struct super_block *sb = ac->ac_sb;
1966 +       void *bitmap = EXT3_MB_BITMAP(e3b);
1967 +       struct ext3_free_extent ex;
1968 +       int i, free;
1969 +
1970 +       free = e3b->bd_info->bb_free;
1971 +       BUG_ON(free <= 0);
1972 +
1973 +       i = e3b->bd_info->bb_first_free;
1974 +
1975 +       while (free && ac->ac_status == AC_STATUS_CONTINUE) {
1976 +               i = mb_find_next_zero_bit(bitmap, EXT3_BLOCKS_PER_GROUP(sb), i);
1977 +               if (i >= EXT3_BLOCKS_PER_GROUP(sb)) {
1978 +                       BUG_ON(free != 0);
1979 +                       break;
1980 +               }
1981 +
1982 +               mb_find_extent(e3b, 0, i, ac->ac_g_ex.fe_len, &ex);
1983 +               BUG_ON(ex.fe_len <= 0);
1984 +               BUG_ON(free < ex.fe_len);
1985 +
1986 +               ext3_mb_measure_extent(ac, &ex, e3b);
1987 +
1988 +               i += ex.fe_len;
1989 +               free -= ex.fe_len;
1990 +       }
1991 +
1992 +       ext3_mb_check_limits(ac, e3b, 1);
1993 +}
1994 +
1995 +/*
1996 + * This is a special case for storages like raid5
1997 + * we try to find stripe-aligned chunks for stripe-size requests
1998 + */
1999 +static void ext3_mb_scan_aligned(struct ext3_allocation_context *ac,
2000 +                                struct ext3_buddy *e3b)
2001 +{
2002 +       struct super_block *sb = ac->ac_sb;
2003 +       struct ext3_sb_info *sbi = EXT3_SB(sb);
2004 +       void *bitmap = EXT3_MB_BITMAP(e3b);
2005 +       struct ext3_free_extent ex;
2006 +       unsigned long i, max;
2007 +
2008 +       BUG_ON(sbi->s_stripe == 0);
2009 +
2010 +       /* find first stripe-aligned block */
2011 +       i = e3b->bd_group * EXT3_BLOCKS_PER_GROUP(sb)
2012 +               + le32_to_cpu(sbi->s_es->s_first_data_block);
2013 +       i = ((i + sbi->s_stripe - 1) / sbi->s_stripe) * sbi->s_stripe;
2014 +       i = (i - le32_to_cpu(sbi->s_es->s_first_data_block))
2015 +                       % EXT3_BLOCKS_PER_GROUP(sb);
2016 +
2017 +       while (i < EXT3_BLOCKS_PER_GROUP(sb)) {
2018 +               if (!mb_test_bit(i, bitmap)) {
2019 +                       max = mb_find_extent(e3b, 0, i, sbi->s_stripe, &ex);
2020 +                       if (max >= sbi->s_stripe) {
2021 +                               ac->ac_found++;
2022 +                               ac->ac_b_ex = ex;
2023 +                               ext3_mb_use_best_found(ac, e3b);
2024 +                               break;
2025 +                       }
2026 +               }
2027 +               i += sbi->s_stripe;
2028 +       }
2029 +}
2030 +
2031 +static int ext3_mb_good_group(struct ext3_allocation_context *ac,
2032 +                               int group, int cr)
2033 +{
2034 +       struct ext3_group_info *grp = EXT3_GROUP_INFO(ac->ac_sb, group);
2035 +       unsigned free, fragments, i, bits;
2036 +
2037 +       BUG_ON(cr < 0 || cr >= 4);
2038 +       BUG_ON(EXT3_MB_GRP_NEED_INIT(grp));
2039 +
2040 +       free = grp->bb_free;
2041 +       fragments = grp->bb_fragments;
2042 +       if (free == 0)
2043 +               return 0;
2044 +       if (fragments == 0)
2045 +               return 0;
2046 +
2047 +       switch (cr) {
2048 +               case 0:
2049 +                       BUG_ON(ac->ac_2order == 0);
2050 +                       bits = ac->ac_sb->s_blocksize_bits + 1;
2051 +                       for (i = ac->ac_2order; i <= bits; i++)
2052 +                               if (grp->bb_counters[i] > 0)
2053 +                                       return 1;
2054 +                       break;
2055 +               case 1:
2056 +                       if ((free / fragments) >= ac->ac_g_ex.fe_len)
2057 +                               return 1;
2058 +                       break;
2059 +               case 2:
2060 +                       if (free >= ac->ac_g_ex.fe_len)
2061 +                               return 1;
2062 +                       break;
2063 +               case 3:
2064 +                       return 1;
2065 +               default:
2066 +                       BUG();
2067 +       }
2068 +
2069 +       return 0;
2070 +}
2071 +
2072 +int ext3_mb_regular_allocator(struct ext3_allocation_context *ac)
2073 +{
2074 +       int group, i, cr, err = 0;
2075 +       struct ext3_sb_info *sbi;
2076 +       struct super_block *sb;
2077 +       struct ext3_buddy e3b;
2078 +
2079 +       sb = ac->ac_sb;
2080 +       sbi = EXT3_SB(sb);
2081 +       BUG_ON(ac->ac_status == AC_STATUS_FOUND);
2082 +
2083 +       /* first, try the goal */
2084 +       err = ext3_mb_find_by_goal(ac, &e3b);
2085 +       if (err || ac->ac_status == AC_STATUS_FOUND)
2086 +               goto out;
2087 +
2088 +       if (unlikely(ac->ac_flags & EXT3_MB_HINT_GOAL_ONLY))
2089 +               goto out;
2090 +
2091 +       i = ffs(ac->ac_g_ex.fe_len);
2092 +       ac->ac_2order = 0;
2093 +       if (i >= sbi->s_mb_order2_reqs) {
2094 +               i--;
2095 +               if ((ac->ac_g_ex.fe_len & (~(1 << i))) == 0)
2096 +                       ac->ac_2order = i;
2097 +       }
2098 +
2099 +       /* if stream allocation is enabled, use global goal */
2100 +       if ((ac->ac_g_ex.fe_len < sbi->s_mb_large_req) &&
2101 +                       (ac->ac_flags & EXT3_MB_HINT_DATA)) {
2102 +               /* TBD: may be hot point */
2103 +               spin_lock(&sbi->s_md_lock);
2104 +               ac->ac_g_ex.fe_group = sbi->s_mb_last_group;
2105 +               ac->ac_g_ex.fe_start = sbi->s_mb_last_start;
2106 +               spin_unlock(&sbi->s_md_lock);
2107 +       }
2108 +
2109 +       group = ac->ac_g_ex.fe_group;
2110 +
2111 +       /* Let's just scan groups to find more-less suitable blocks */
2112 +       cr = ac->ac_2order ? 0 : 1;
2113 +repeat:
2114 +       for (; cr < 4 && ac->ac_status == AC_STATUS_CONTINUE; cr++) {
2115 +               ac->ac_criteria = cr;
2116 +               for (i = 0; i < EXT3_SB(sb)->s_groups_count; group++, i++) {
2117 +                       struct ext3_group_info *grp;
2118 +
2119 +                       if (group == EXT3_SB(sb)->s_groups_count)
2120 +                               group = 0;
2121 +
2122 +                       /* quick check to skip empty groups */
2123 +                       grp = EXT3_GROUP_INFO(ac->ac_sb, group);
2124 +                       if (grp->bb_free == 0)
2125 +                               continue;
2126 +
2127 +                       if (EXT3_MB_GRP_NEED_INIT(EXT3_GROUP_INFO(sb, group))) {
2128 +                               /* we need full data about the group
2129 +                                * to make a good selection */
2130 +                               err = ext3_mb_load_buddy(sb, group, &e3b);
2131 +                               if (err)
2132 +                                       goto out;
2133 +                               ext3_mb_release_desc(&e3b);
2134 +                       }
2135 +
2136 +                       /* check is group good for our criteries */
2137 +                       if (!ext3_mb_good_group(ac, group, cr))
2138 +                               continue;
2139 +
2140 +                       err = ext3_mb_load_buddy(sb, group, &e3b);
2141 +                       if (err)
2142 +                               goto out;
2143 +
2144 +                       ext3_lock_group(sb, group);
2145 +                       if (!ext3_mb_good_group(ac, group, cr)) {
2146 +                               /* someone did allocation from this group */
2147 +                               ext3_unlock_group(sb, group);
2148 +                               ext3_mb_release_desc(&e3b);
2149 +                               continue;
2150 +                       }
2151 +
2152 +                       ac->ac_groups_scanned++;
2153 +                       if (cr == 0)
2154 +                               ext3_mb_simple_scan_group(ac, &e3b);
2155 +                       else if (cr == 1 && ac->ac_g_ex.fe_len == sbi->s_stripe)
2156 +                               ext3_mb_scan_aligned(ac, &e3b);
2157 +                       else
2158 +                               ext3_mb_complex_scan_group(ac, &e3b);
2159 +
2160 +                       ext3_unlock_group(sb, group);
2161 +                       ext3_mb_release_desc(&e3b);
2162 +
2163 +                       if (ac->ac_status != AC_STATUS_CONTINUE)
2164 +                               break;
2165 +               }
2166 +       }
2167 +
2168 +       if (ac->ac_b_ex.fe_len > 0 && ac->ac_status != AC_STATUS_FOUND &&
2169 +           !(ac->ac_flags & EXT3_MB_HINT_FIRST)) {
2170 +               /*
2171 +                * We've been searching too long. Let's try to allocate
2172 +                * the best chunk we've found so far
2173 +                */
2174 +
2175 +               ext3_mb_try_best_found(ac, &e3b);
2176 +               if (ac->ac_status != AC_STATUS_FOUND) {
2177 +                       /*
2178 +                        * Someone more lucky has already allocated it.
2179 +                        * The only thing we can do is just take first
2180 +                        * found block(s)
2181 +                       printk(KERN_DEBUG "EXT3-fs: someone won our chunk\n");
2182 +                        */
2183 +                       ac->ac_b_ex.fe_group = 0;
2184 +                       ac->ac_b_ex.fe_start = 0;
2185 +                       ac->ac_b_ex.fe_len = 0;
2186 +                       ac->ac_status = AC_STATUS_CONTINUE;
2187 +                       ac->ac_flags |= EXT3_MB_HINT_FIRST;
2188 +                       cr = 3;
2189 +                       atomic_inc(&sbi->s_mb_lost_chunks);
2190 +                       goto repeat;
2191 +               }
2192 +       }
2193 +out:
2194 +       return err;
2195 +}
2196 +
2197 +#ifdef EXT3_MB_HISTORY
2198 +struct ext3_mb_proc_session {
2199 +       struct ext3_mb_history *history;
2200 +       struct super_block *sb;
2201 +       int start;
2202 +       int max;
2203 +};
2204 +
2205 +static void *ext3_mb_history_skip_empty(struct ext3_mb_proc_session *s,
2206 +                                       struct ext3_mb_history *hs,
2207 +                                       int first)
2208 +{
2209 +       if (hs == s->history + s->max)
2210 +               hs = s->history;
2211 +       if (!first && hs == s->history + s->start)
2212 +               return NULL;
2213 +       while (hs->orig.fe_len == 0) {
2214 +               hs++;
2215 +               if (hs == s->history + s->max)
2216 +                       hs = s->history;
2217 +               if (hs == s->history + s->start)
2218 +                       return NULL;
2219 +       }
2220 +       return hs;
2221 +}
2222 +
2223 +static void *ext3_mb_seq_history_start(struct seq_file *seq, loff_t *pos)
2224 +{
2225 +       struct ext3_mb_proc_session *s = seq->private;
2226 +       struct ext3_mb_history *hs;
2227 +       int l = *pos;
2228 +
2229 +       if (l == 0)
2230 +               return SEQ_START_TOKEN;
2231 +       hs = ext3_mb_history_skip_empty(s, s->history + s->start, 1);
2232 +       if (!hs)
2233 +               return NULL;
2234 +       while (--l && (hs = ext3_mb_history_skip_empty(s, ++hs, 0)) != NULL);
2235 +       return hs;
2236 +}
2237 +
2238 +static void *ext3_mb_seq_history_next(struct seq_file *seq, void *v, loff_t *pos)
2239 +{
2240 +       struct ext3_mb_proc_session *s = seq->private;
2241 +       struct ext3_mb_history *hs = v;
2242 +
2243 +       ++*pos;
2244 +       if (v == SEQ_START_TOKEN)
2245 +               return ext3_mb_history_skip_empty(s, s->history + s->start, 1);
2246 +       else
2247 +               return ext3_mb_history_skip_empty(s, ++hs, 0);
2248 +}
2249 +
2250 +static int ext3_mb_seq_history_show(struct seq_file *seq, void *v)
2251 +{
2252 +       char buf[25], buf2[25], buf3[25], *fmt;
2253 +       struct ext3_mb_history *hs = v;
2254 +
2255 +       if (v == SEQ_START_TOKEN) {
2256 +               seq_printf(seq, "%-5s %-8s %-23s %-23s %-23s %-5s "
2257 +                               "%-5s %-2s %-5s %-5s %-5s %-6s\n",
2258 +                          "pid", "inode", "original", "goal", "result","found",
2259 +                          "grps", "cr", "flags", "merge", "tail", "broken");
2260 +               return 0;
2261 +       }
2262 +
2263 +       if (hs->op == EXT3_MB_HISTORY_ALLOC) {
2264 +               fmt = "%-5u %-8u %-23s %-23s %-23s %-5u %-5u %-2u "
2265 +                       "%-5u %-5s %-5u %-6u\n";
2266 +               sprintf(buf2, "%lu/%lu/%lu@%lu", hs->result.fe_group,
2267 +                       hs->result.fe_start, hs->result.fe_len,
2268 +                       hs->result.fe_logical);
2269 +               sprintf(buf, "%lu/%lu/%lu@%lu", hs->orig.fe_group,
2270 +                       hs->orig.fe_start, hs->orig.fe_len,
2271 +                       hs->orig.fe_logical);
2272 +               sprintf(buf3, "%lu/%lu/%lu@%lu", hs->goal.fe_group,
2273 +                       hs->goal.fe_start, hs->goal.fe_len,
2274 +                       hs->goal.fe_logical);
2275 +               seq_printf(seq, fmt, hs->pid, hs->ino, buf, buf3, buf2,
2276 +                               hs->found, hs->groups, hs->cr, hs->flags,
2277 +                               hs->merged ? "M" : "", hs->tail,
2278 +                               hs->buddy ? 1 << hs->buddy : 0);
2279 +       } else if (hs->op == EXT3_MB_HISTORY_PREALLOC) {
2280 +               fmt = "%-5u %-8u %-23s %-23s %-23s\n";
2281 +               sprintf(buf2, "%lu/%lu/%lu@%lu", hs->result.fe_group,
2282 +                       hs->result.fe_start, hs->result.fe_len,
2283 +                       hs->result.fe_logical);
2284 +               sprintf(buf, "%lu/%lu/%lu@%lu", hs->orig.fe_group,
2285 +                       hs->orig.fe_start, hs->orig.fe_len,
2286 +                       hs->orig.fe_logical);
2287 +               seq_printf(seq, fmt, hs->pid, hs->ino, buf, "", buf2);
2288 +       } else if (hs->op == EXT3_MB_HISTORY_DISCARD) {
2289 +               sprintf(buf2, "%lu/%lu/%lu", hs->result.fe_group,
2290 +                       hs->result.fe_start, hs->result.fe_len);
2291 +               seq_printf(seq, "%-5u %-8u %-23s discard\n",
2292 +                               hs->pid, hs->ino, buf2);
2293 +       } else if (hs->op == EXT3_MB_HISTORY_FREE) {
2294 +               sprintf(buf2, "%lu/%lu/%lu", hs->result.fe_group,
2295 +                       hs->result.fe_start, hs->result.fe_len);
2296 +               seq_printf(seq, "%-5u %-8u %-23s free\n",
2297 +                               hs->pid, hs->ino, buf2);
2298 +       } else {
2299 +               seq_printf(seq, "unknown op %d\n", hs->op);
2300 +       }
2301 +       return 0;
2302 +}
2303 +
2304 +static void ext3_mb_seq_history_stop(struct seq_file *seq, void *v)
2305 +{
2306 +}
2307 +
2308 +static struct seq_operations ext3_mb_seq_history_ops = {
2309 +       .start  = ext3_mb_seq_history_start,
2310 +       .next   = ext3_mb_seq_history_next,
2311 +       .stop   = ext3_mb_seq_history_stop,
2312 +       .show   = ext3_mb_seq_history_show,
2313 +};
2314 +
2315 +static int ext3_mb_seq_history_open(struct inode *inode, struct file *file)
2316 +{
2317 +       struct super_block *sb = PDE(inode)->data;
2318 +       struct ext3_sb_info *sbi = EXT3_SB(sb);
2319 +       struct ext3_mb_proc_session *s;
2320 +       int rc, size;
2321 +
2322 +       s = kmalloc(sizeof(*s), GFP_KERNEL);
2323 +       if (s == NULL)
2324 +               return -ENOMEM;
2325 +       s->sb = sb;
2326 +       size = sizeof(struct ext3_mb_history) * sbi->s_mb_history_max;
2327 +       s->history = kmalloc(size, GFP_KERNEL);
2328 +       if (s->history == NULL) {
2329 +               kfree(s);
2330 +               return -ENOMEM;
2331 +       }
2332 +
2333 +       spin_lock(&sbi->s_mb_history_lock);
2334 +       memcpy(s->history, sbi->s_mb_history, size);
2335 +       s->max = sbi->s_mb_history_max;
2336 +       s->start = sbi->s_mb_history_cur % s->max;
2337 +       spin_unlock(&sbi->s_mb_history_lock);
2338 +
2339 +       rc = seq_open(file, &ext3_mb_seq_history_ops);
2340 +       if (rc == 0) {
2341 +               struct seq_file *m = (struct seq_file *)file->private_data;
2342 +               m->private = s;
2343 +       } else {
2344 +               kfree(s->history);
2345 +               kfree(s);
2346 +       }
2347 +       return rc;
2348 +
2349 +}
2350 +
2351 +static int ext3_mb_seq_history_release(struct inode *inode, struct file *file)
2352 +{
2353 +       struct seq_file *seq = (struct seq_file *)file->private_data;
2354 +       struct ext3_mb_proc_session *s = seq->private;
2355 +       kfree(s->history);
2356 +       kfree(s);
2357 +       return seq_release(inode, file);
2358 +}
2359 +
2360 +static ssize_t ext3_mb_seq_history_write(struct file *file,
2361 +                               const char __user *buffer,
2362 +                               size_t count, loff_t *ppos)
2363 +{
2364 +       struct seq_file *seq = (struct seq_file *)file->private_data;
2365 +       struct ext3_mb_proc_session *s = seq->private;
2366 +       struct super_block *sb = s->sb;
2367 +       char str[32];
2368 +       int value;
2369 +
2370 +       if (count >= sizeof(str)) {
2371 +               printk(KERN_ERR "EXT3-fs: %s string too long, max %u bytes\n",
2372 +                               "mb_history", (int)sizeof(str));
2373 +               return -EOVERFLOW;
2374 +       }
2375 +
2376 +       if (copy_from_user(str, buffer, count))
2377 +               return -EFAULT;
2378 +
2379 +       value = simple_strtol(str, NULL, 0);
2380 +       if (value < 0)
2381 +               return -ERANGE;
2382 +       EXT3_SB(sb)->s_mb_history_filter = value;
2383 +
2384 +       return count;
2385 +}
2386 +
2387 +static struct file_operations ext3_mb_seq_history_fops = {
2388 +       .owner          = THIS_MODULE,
2389 +       .open           = ext3_mb_seq_history_open,
2390 +       .read           = seq_read,
2391 +       .write          = ext3_mb_seq_history_write,
2392 +       .llseek         = seq_lseek,
2393 +       .release        = ext3_mb_seq_history_release,
2394 +};
2395 +
2396 +static void *ext3_mb_seq_groups_start(struct seq_file *seq, loff_t *pos)
2397 +{
2398 +       struct super_block *sb = seq->private;
2399 +       struct ext3_sb_info *sbi = EXT3_SB(sb);
2400 +       long group;
2401 +
2402 +       if (*pos < 0 || *pos >= sbi->s_groups_count)
2403 +               return NULL;
2404 +
2405 +       group = *pos + 1;
2406 +       return (void *) group;
2407 +}
2408 +
2409 +static void *ext3_mb_seq_groups_next(struct seq_file *seq, void *v, loff_t *pos)
2410 +{
2411 +       struct super_block *sb = seq->private;
2412 +       struct ext3_sb_info *sbi = EXT3_SB(sb);
2413 +       long group;
2414 +
2415 +       ++*pos;
2416 +       if (*pos < 0 || *pos >= sbi->s_groups_count)
2417 +               return NULL;
2418 +       group = *pos + 1;
2419 +       return (void *) group;;
2420 +}
2421 +
2422 +static int ext3_mb_seq_groups_show(struct seq_file *seq, void *v)
2423 +{
2424 +       struct super_block *sb = seq->private;
2425 +       struct ext3_group_desc *gdp;
2426 +       long group = (long) v;
2427 +       int i, err, free = 0;
2428 +       struct ext3_buddy e3b;
2429 +       struct sg {
2430 +               struct ext3_group_info info;
2431 +               unsigned short counters[16];
2432 +       } sg;
2433 +
2434 +       group--;
2435 +       if (group == 0)
2436 +               seq_printf(seq, "#%-5s: %-5s %-5s %-5s %-5s %-5s "
2437 +                               "[ %-5s %-5s %-5s %-5s %-5s %-5s %-5s "
2438 +                                 "%-5s %-5s %-5s %-5s %-5s %-5s %-5s ]\n",
2439 +                          "group", "free", "ingd", "frags", "first", "pa",
2440 +                          "2^0", "2^1", "2^2", "2^3", "2^4", "2^5","2^6",
2441 +                          "2^7", "2^8", "2^9", "2^10", "2^11", "2^12", "2^13");
2442 +
2443 +       i = (sb->s_blocksize_bits + 2) * sizeof(sg.info.bb_counters[0]) +
2444 +               sizeof(struct ext3_group_info);
2445 +       err = ext3_mb_load_buddy(sb, group, &e3b);
2446 +       if (err) {
2447 +               seq_printf(seq, "#%-5lu: I/O error\n", group);
2448 +               return 0;
2449 +       }
2450 +
2451 +       gdp = ext3_get_group_desc(sb, group, NULL);
2452 +       if (gdp != NULL)
2453 +               free = le16_to_cpu(gdp->bg_free_blocks_count);
2454 +
2455 +       ext3_lock_group(sb, group);
2456 +       memcpy(&sg, EXT3_GROUP_INFO(sb, group), i);
2457 +       ext3_unlock_group(sb, group);
2458 +       ext3_mb_release_desc(&e3b);
2459 +
2460 +       seq_printf(seq, "#%-5lu: %-5u %-5u %-5u %-5u %-5lu [", group,
2461 +                       sg.info.bb_free, free,
2462 +                       sg.info.bb_fragments, sg.info.bb_first_free,
2463 +                       sg.info.bb_prealloc_nr);
2464 +       for (i = 0; i <= 13; i++)
2465 +               seq_printf(seq, " %-5u", i <= sb->s_blocksize_bits + 1 ?
2466 +                               sg.info.bb_counters[i] : 0);
2467 +       seq_printf(seq, " ]\n");
2468 +
2469 +       return 0;
2470 +}
2471 +
2472 +static void ext3_mb_seq_groups_stop(struct seq_file *seq, void *v)
2473 +{
2474 +}
2475 +
2476 +static struct seq_operations ext3_mb_seq_groups_ops = {
2477 +       .start  = ext3_mb_seq_groups_start,
2478 +       .next   = ext3_mb_seq_groups_next,
2479 +       .stop   = ext3_mb_seq_groups_stop,
2480 +       .show   = ext3_mb_seq_groups_show,
2481 +};
2482 +
2483 +static int ext3_mb_seq_groups_open(struct inode *inode, struct file *file)
2484 +{
2485 +       struct super_block *sb = PDE(inode)->data;
2486 +       int rc;
2487 +
2488 +       rc = seq_open(file, &ext3_mb_seq_groups_ops);
2489 +       if (rc == 0) {
2490 +               struct seq_file *m = (struct seq_file *)file->private_data;
2491 +               m->private = sb;
2492 +       }
2493 +       return rc;
2494 +
2495 +}
2496 +
2497 +static struct file_operations ext3_mb_seq_groups_fops = {
2498 +       .owner          = THIS_MODULE,
2499 +       .open           = ext3_mb_seq_groups_open,
2500 +       .read           = seq_read,
2501 +       .llseek         = seq_lseek,
2502 +       .release        = seq_release,
2503 +};
2504 +
2505 +static void ext3_mb_history_release(struct super_block *sb)
2506 +{
2507 +       struct ext3_sb_info *sbi = EXT3_SB(sb);
2508 +
2509 +       remove_proc_entry("mb_groups", sbi->s_dev_proc);
2510 +       remove_proc_entry("mb_history", sbi->s_dev_proc);
2511 +
2512 +       if (sbi->s_mb_history)
2513 +               kfree(sbi->s_mb_history);
2514 +}
2515 +
2516 +static void ext3_mb_history_init(struct super_block *sb)
2517 +{
2518 +       struct ext3_sb_info *sbi = EXT3_SB(sb);
2519 +       int i;
2520 +
2521 +       if (sbi->s_dev_proc != NULL) {
2522 +               struct proc_dir_entry *p;
2523 +               p = create_proc_entry("mb_history", S_IRUGO, sbi->s_dev_proc);
2524 +               if (p) {
2525 +                       p->proc_fops = &ext3_mb_seq_history_fops;
2526 +                       p->data = sb;
2527 +               }
2528 +               p = create_proc_entry("mb_groups", S_IRUGO, sbi->s_dev_proc);
2529 +               if (p) {
2530 +                       p->proc_fops = &ext3_mb_seq_groups_fops;
2531 +                       p->data = sb;
2532 +               }
2533 +       }
2534 +
2535 +       sbi->s_mb_history_max = 1000;
2536 +       sbi->s_mb_history_cur = 0;
2537 +       spin_lock_init(&sbi->s_mb_history_lock);
2538 +       i = sbi->s_mb_history_max * sizeof(struct ext3_mb_history);
2539 +       sbi->s_mb_history = kmalloc(i, GFP_KERNEL);
2540 +       if (likely(sbi->s_mb_history != NULL))
2541 +               memset(sbi->s_mb_history, 0, i);
2542 +       /* if we can't allocate history, then we simple won't use it */
2543 +}
2544 +
2545 +static void
2546 +ext3_mb_store_history(struct ext3_allocation_context *ac)
2547 +{
2548 +       struct ext3_sb_info *sbi = EXT3_SB(ac->ac_sb);
2549 +       struct ext3_mb_history h;
2550 +
2551 +       if (unlikely(sbi->s_mb_history == NULL))
2552 +               return;
2553 +
2554 +       if (!(ac->ac_op & sbi->s_mb_history_filter))
2555 +               return;
2556 +
2557 +       h.op = ac->ac_op;
2558 +       h.pid = current->pid;
2559 +       h.ino = ac->ac_inode ? ac->ac_inode->i_ino : 0;
2560 +       h.orig = ac->ac_o_ex;
2561 +       h.result = ac->ac_b_ex;
2562 +       h.flags = ac->ac_flags;
2563 +       h.found = ac->ac_found;
2564 +       h.groups = ac->ac_groups_scanned;
2565 +       h.cr = ac->ac_criteria;
2566 +       h.tail = ac->ac_tail;
2567 +       h.buddy = ac->ac_buddy;
2568 +       h.merged = 0;
2569 +       h.cr = ac->ac_criteria;
2570 +       if (ac->ac_op == EXT3_MB_HISTORY_ALLOC) {
2571 +               if (ac->ac_g_ex.fe_start == ac->ac_b_ex.fe_start &&
2572 +                               ac->ac_g_ex.fe_group == ac->ac_b_ex.fe_group)
2573 +                       h.merged = 1;
2574 +               h.goal = ac->ac_g_ex;
2575 +               h.result = ac->ac_f_ex;
2576 +       }
2577 +
2578 +       spin_lock(&sbi->s_mb_history_lock);
2579 +       memcpy(sbi->s_mb_history + sbi->s_mb_history_cur, &h, sizeof(h));
2580 +       if (++sbi->s_mb_history_cur >= sbi->s_mb_history_max)
2581 +               sbi->s_mb_history_cur = 0;
2582 +       spin_unlock(&sbi->s_mb_history_lock);
2583 +}
2584 +
2585 +#else
2586 +#define ext3_mb_history_release(sb)
2587 +#define ext3_mb_history_init(sb)
2588 +#endif
2589 +
2590 +int ext3_mb_init_backend(struct super_block *sb)
2591 +{
2592 +       struct ext3_sb_info *sbi = EXT3_SB(sb);
2593 +       int i, j, len, metalen;
2594 +       int num_meta_group_infos =
2595 +               (sbi->s_groups_count + EXT3_DESC_PER_BLOCK(sb) - 1) >>
2596 +                       EXT3_DESC_PER_BLOCK_BITS(sb);
2597 +       struct ext3_group_info **meta_group_info;
2598 +
2599 +       /* An 8TB filesystem with 64-bit pointers requires a 4096 byte
2600 +        * kmalloc. A 128kb malloc should suffice for a 256TB filesystem.
2601 +        * So a two level scheme suffices for now. */
2602 +       sbi->s_group_info = kmalloc(sizeof(*sbi->s_group_info) *
2603 +                                   num_meta_group_infos, GFP_KERNEL);
2604 +       if (sbi->s_group_info == NULL) {
2605 +               printk(KERN_ERR "EXT3-fs: can't allocate buddy meta group\n");
2606 +               return -ENOMEM;
2607 +       }
2608 +       sbi->s_buddy_cache = new_inode(sb);
2609 +       if (sbi->s_buddy_cache == NULL) {
2610 +               printk(KERN_ERR "EXT3-fs: can't get new inode\n");
2611 +               goto err_freesgi;
2612 +       }
2613 +       EXT3_I(sbi->s_buddy_cache)->i_disksize = 0;
2614 +
2615 +       metalen = sizeof(*meta_group_info) << EXT3_DESC_PER_BLOCK_BITS(sb);
2616 +       for (i = 0; i < num_meta_group_infos; i++) {
2617 +               if ((i + 1) == num_meta_group_infos)
2618 +                       metalen = sizeof(*meta_group_info) *
2619 +                               (sbi->s_groups_count -
2620 +                                       (i << EXT3_DESC_PER_BLOCK_BITS(sb)));
2621 +               meta_group_info = kmalloc(metalen, GFP_KERNEL);
2622 +               if (meta_group_info == NULL) {
2623 +                       printk(KERN_ERR "EXT3-fs: can't allocate mem for a "
2624 +                              "buddy group\n");
2625 +                       goto err_freemeta;
2626 +               }
2627 +               sbi->s_group_info[i] = meta_group_info;
2628 +       }
2629 +
2630 +       /*
2631 +        * calculate needed size. if change bb_counters size,
2632 +        * don't forget about ext3_mb_generate_buddy()
2633 +        */
2634 +       len = sizeof(struct ext3_group_info);
2635 +       len += sizeof(unsigned short) * (sb->s_blocksize_bits + 2);
2636 +       for (i = 0; i < sbi->s_groups_count; i++) {
2637 +               struct ext3_group_desc * desc;
2638 +
2639 +               meta_group_info =
2640 +                       sbi->s_group_info[i >> EXT3_DESC_PER_BLOCK_BITS(sb)];
2641 +               j = i & (EXT3_DESC_PER_BLOCK(sb) - 1);
2642 +
2643 +               meta_group_info[j] = kmalloc(len, GFP_KERNEL);
2644 +               if (meta_group_info[j] == NULL) {
2645 +                       printk(KERN_ERR "EXT3-fs: can't allocate buddy mem\n");
2646 +                       i--;
2647 +                       goto err_freebuddy;
2648 +               }
2649 +               desc = ext3_get_group_desc(sb, i, NULL);
2650 +               if (desc == NULL) {
2651 +                       printk(KERN_ERR"EXT3-fs: can't read descriptor %u\n",i);
2652 +                       goto err_freebuddy;
2653 +               }
2654 +               memset(meta_group_info[j], 0, len);
2655 +               set_bit(EXT3_GROUP_INFO_NEED_INIT_BIT,
2656 +                       &meta_group_info[j]->bb_state);
2657 +
2658 +               /* initialize bb_free to be able to skip
2659 +                * empty groups without initialization */
2660 +               meta_group_info[j]->bb_free =
2661 +                       le16_to_cpu(desc->bg_free_blocks_count);
2662 +
2663 +               INIT_LIST_HEAD(&meta_group_info[j]->bb_prealloc_list);
2664 +
2665 +#ifdef DOUBLE_CHECK
2666 +               {
2667 +                       struct buffer_head *bh;
2668 +                       meta_group_info[j]->bb_bitmap =
2669 +                               kmalloc(sb->s_blocksize, GFP_KERNEL);
2670 +                       BUG_ON(meta_group_info[j]->bb_bitmap == NULL);
2671 +                       bh = read_block_bitmap(sb, i);
2672 +                       BUG_ON(bh == NULL);
2673 +                       memcpy(meta_group_info[j]->bb_bitmap, bh->b_data,
2674 +                                       sb->s_blocksize);
2675 +                       brelse(bh);
2676 +               }
2677 +#endif
2678 +
2679 +       }
2680 +
2681 +       return 0;
2682 +
2683 +err_freebuddy:
2684 +       while (i >= 0) {
2685 +               kfree(EXT3_GROUP_INFO(sb, i));
2686 +               i--;
2687 +       }
2688 +       i = num_meta_group_infos;
2689 +err_freemeta:
2690 +       while (--i >= 0)
2691 +               kfree(sbi->s_group_info[i]);
2692 +       iput(sbi->s_buddy_cache);
2693 +err_freesgi:
2694 +       kfree(sbi->s_group_info);
2695 +       return -ENOMEM;
2696 +}
2697 +
2698 +static void ext3_mb_prealloc_table_add(struct ext3_sb_info *sbi, int value)
2699 +{
2700 +       int i;
2701 +
2702 +       if (value > (sbi->s_blocks_per_group - 1 - 1 - sbi->s_itb_per_group))
2703 +               return;
2704 +
2705 +       for (i = 0; i < sbi->s_mb_prealloc_table_size; i++) {
2706 +               if (sbi->s_mb_prealloc_table[i] == 0) {
2707 +                       sbi->s_mb_prealloc_table[i] = value;
2708 +                       return;
2709 +               }
2710 +
2711 +               /* they should add values in order */
2712 +               if (value <= sbi->s_mb_prealloc_table[i])
2713 +                       return;
2714 +       }
2715 +}
2716 +
2717 +int ext3_mb_init(struct super_block *sb, int needs_recovery)
2718 +{
2719 +       struct ext3_sb_info *sbi = EXT3_SB(sb);
2720 +       unsigned i, offset, max;
2721 +
2722 +       if (!test_opt(sb, MBALLOC))
2723 +               return 0;
2724 +
2725 +       i = (sb->s_blocksize_bits + 2) * sizeof(unsigned short);
2726 +
2727 +       sbi->s_mb_offsets = kmalloc(i, GFP_KERNEL);
2728 +       if (sbi->s_mb_offsets == NULL) {
2729 +               clear_opt(sbi->s_mount_opt, MBALLOC);
2730 +               return -ENOMEM;
2731 +       }
2732 +       sbi->s_mb_maxs = kmalloc(i, GFP_KERNEL);
2733 +       if (sbi->s_mb_maxs == NULL) {
2734 +               clear_opt(sbi->s_mount_opt, MBALLOC);
2735 +               kfree(sbi->s_mb_maxs);
2736 +               return -ENOMEM;
2737 +       }
2738 +
2739 +       /* order 0 is regular bitmap */
2740 +       sbi->s_mb_maxs[0] = sb->s_blocksize << 3;
2741 +       sbi->s_mb_offsets[0] = 0;
2742 +
2743 +       i = 1;
2744 +       offset = 0;
2745 +       max = sb->s_blocksize << 2;
2746 +       do {
2747 +               sbi->s_mb_offsets[i] = offset;
2748 +               sbi->s_mb_maxs[i] = max;
2749 +               offset += 1 << (sb->s_blocksize_bits - i);
2750 +               max = max >> 1;
2751 +               i++;
2752 +       } while (i <= sb->s_blocksize_bits + 1);
2753 +
2754 +       /* init file for buddy data */
2755 +       if ((i = ext3_mb_init_backend(sb))) {
2756 +               clear_opt(sbi->s_mount_opt, MBALLOC);
2757 +               kfree(sbi->s_mb_offsets);
2758 +               kfree(sbi->s_mb_maxs);
2759 +               return i;
2760 +       }
2761 +
2762 +       spin_lock_init(&sbi->s_md_lock);
2763 +       INIT_LIST_HEAD(&sbi->s_active_transaction);
2764 +       INIT_LIST_HEAD(&sbi->s_closed_transaction);
2765 +       INIT_LIST_HEAD(&sbi->s_committed_transaction);
2766 +       spin_lock_init(&sbi->s_bal_lock);
2767 +
2768 +       sbi->s_mb_max_to_scan = MB_DEFAULT_MAX_TO_SCAN;
2769 +       sbi->s_mb_min_to_scan = MB_DEFAULT_MIN_TO_SCAN;
2770 +       sbi->s_mb_max_groups_to_scan = MB_DEFAULT_MAX_GROUPS_TO_SCAN;
2771 +       sbi->s_mb_stats = MB_DEFAULT_STATS;
2772 +       sbi->s_mb_order2_reqs = MB_DEFAULT_ORDER2_REQS;
2773 +       sbi->s_mb_history_filter = EXT3_MB_HISTORY_DEFAULT;
2774 +
2775 +       if (sbi->s_stripe == 0) {
2776 +               sbi->s_mb_prealloc_table_size = 8;
2777 +               i = sbi->s_mb_prealloc_table_size * sizeof(unsigned long);
2778 +               sbi->s_mb_prealloc_table = kmalloc(i, GFP_NOFS);
2779 +               if (sbi->s_mb_prealloc_table == NULL) {
2780 +                       clear_opt(sbi->s_mount_opt, MBALLOC);
2781 +                       kfree(sbi->s_mb_offsets);
2782 +                       kfree(sbi->s_mb_maxs);
2783 +                       return -ENOMEM;
2784 +               }
2785 +               memset(sbi->s_mb_prealloc_table, 0, i);
2786 +
2787 +               ext3_mb_prealloc_table_add(sbi, 4);
2788 +               ext3_mb_prealloc_table_add(sbi, 8);
2789 +               ext3_mb_prealloc_table_add(sbi, 16);
2790 +               ext3_mb_prealloc_table_add(sbi, 32);
2791 +               ext3_mb_prealloc_table_add(sbi, 64);
2792 +               ext3_mb_prealloc_table_add(sbi, 128);
2793 +               ext3_mb_prealloc_table_add(sbi, 256);
2794 +               ext3_mb_prealloc_table_add(sbi, 512);
2795 +
2796 +               sbi->s_mb_small_req = 256;
2797 +               sbi->s_mb_large_req = 1024;
2798 +               sbi->s_mb_group_prealloc = 512;
2799 +       } else {
2800 +               sbi->s_mb_prealloc_table_size = 3;
2801 +               i = sbi->s_mb_prealloc_table_size * sizeof(unsigned long);
2802 +               sbi->s_mb_prealloc_table = kmalloc(i, GFP_NOFS);
2803 +               if (sbi->s_mb_prealloc_table == NULL) {
2804 +                       clear_opt(sbi->s_mount_opt, MBALLOC);
2805 +                       kfree(sbi->s_mb_offsets);
2806 +                       kfree(sbi->s_mb_maxs);
2807 +                       return -ENOMEM;
2808 +               }
2809 +               memset(sbi->s_mb_prealloc_table, 0, i);
2810 +
2811 +               ext3_mb_prealloc_table_add(sbi, sbi->s_stripe);
2812 +               ext3_mb_prealloc_table_add(sbi, sbi->s_stripe * 2);
2813 +               ext3_mb_prealloc_table_add(sbi, sbi->s_stripe * 4);
2814 +
2815 +               sbi->s_mb_small_req = sbi->s_stripe;
2816 +               sbi->s_mb_large_req = sbi->s_stripe * 8;
2817 +               sbi->s_mb_group_prealloc = sbi->s_stripe * 4;
2818 +       }
2819 +
2820 +       i = sizeof(struct ext3_locality_group) * num_possible_cpus();
2821 +       sbi->s_locality_groups = kmalloc(i, GFP_NOFS);
2822 +       if (sbi->s_locality_groups == NULL) {
2823 +               clear_opt(sbi->s_mount_opt, MBALLOC);
2824 +               kfree(sbi->s_mb_prealloc_table);
2825 +               kfree(sbi->s_mb_offsets);
2826 +               kfree(sbi->s_mb_maxs);
2827 +               return -ENOMEM;
2828 +       }
2829 +       for (i = 0; i < num_possible_cpus(); i++) {
2830 +               struct ext3_locality_group *lg;
2831 +               lg = &sbi->s_locality_groups[i];
2832 +               sema_init(&lg->lg_sem, 1);
2833 +               INIT_LIST_HEAD(&lg->lg_prealloc_list);
2834 +               spin_lock_init(&lg->lg_prealloc_lock);
2835 +       }
2836 +
2837 +       ext3_mb_init_per_dev_proc(sb);
2838 +       ext3_mb_history_init(sb);
2839 +
2840 +       printk("EXT3-fs: mballoc enabled\n");
2841 +       return 0;
2842 +}
2843 +
2844 +void ext3_mb_cleanup_pa(struct ext3_group_info *grp)
2845 +{
2846 +       struct ext3_prealloc_space *pa;
2847 +       struct list_head *cur, *tmp;
2848 +       int count = 0;
2849 +
2850 +       list_for_each_safe(cur, tmp, &grp->bb_prealloc_list) {
2851 +               pa = list_entry(cur, struct ext3_prealloc_space, pa_group_list);
2852 +               list_del_rcu(&pa->pa_group_list);
2853 +               count++;
2854 +               kfree(pa);
2855 +       }
2856 +       if (count)
2857 +               mb_debug("mballoc: %u PAs left\n", count);
2858 +
2859 +}
2860 +
2861 +int ext3_mb_release(struct super_block *sb)
2862 +{
2863 +       struct ext3_sb_info *sbi = EXT3_SB(sb);
2864 +       int i, num_meta_group_infos;
2865 +
2866 +       if (!test_opt(sb, MBALLOC))
2867 +               return 0;
2868 +
2869 +       /* release freed, non-committed blocks */
2870 +       spin_lock(&sbi->s_md_lock);
2871 +       list_splice_init(&sbi->s_closed_transaction,
2872 +                       &sbi->s_committed_transaction);
2873 +       list_splice_init(&sbi->s_active_transaction,
2874 +                       &sbi->s_committed_transaction);
2875 +       spin_unlock(&sbi->s_md_lock);
2876 +       ext3_mb_free_committed_blocks(sb);
2877 +
2878 +       if (sbi->s_group_info) {
2879 +               for (i = 0; i < sbi->s_groups_count; i++) {
2880 +#ifdef DOUBLE_CHECK
2881 +                       if (EXT3_GROUP_INFO(sb, i)->bb_bitmap)
2882 +                               kfree(EXT3_GROUP_INFO(sb, i)->bb_bitmap);
2883 +#endif
2884 +                       ext3_mb_cleanup_pa(EXT3_GROUP_INFO(sb, i));
2885 +                       kfree(EXT3_GROUP_INFO(sb, i));
2886 +               }
2887 +               num_meta_group_infos = (sbi->s_groups_count +
2888 +                               EXT3_DESC_PER_BLOCK(sb) - 1) >>
2889 +                       EXT3_DESC_PER_BLOCK_BITS(sb);
2890 +               for (i = 0; i < num_meta_group_infos; i++)
2891 +                       kfree(sbi->s_group_info[i]);
2892 +               kfree(sbi->s_group_info);
2893 +       }
2894 +       if (sbi->s_mb_offsets)
2895 +               kfree(sbi->s_mb_offsets);
2896 +       if (sbi->s_mb_maxs)
2897 +               kfree(sbi->s_mb_maxs);
2898 +       if (sbi->s_buddy_cache)
2899 +               iput(sbi->s_buddy_cache);
2900 +       if (sbi->s_mb_stats) {
2901 +               printk("EXT3-fs: mballoc: %u blocks %u reqs (%u success)\n",
2902 +                               atomic_read(&sbi->s_bal_allocated),
2903 +                               atomic_read(&sbi->s_bal_reqs),
2904 +                               atomic_read(&sbi->s_bal_success));
2905 +               printk("EXT3-fs: mballoc: %u extents scanned, %u goal hits, "
2906 +                               "%u 2^N hits, %u breaks, %u lost\n",
2907 +                               atomic_read(&sbi->s_bal_ex_scanned),
2908 +                               atomic_read(&sbi->s_bal_goals),
2909 +                               atomic_read(&sbi->s_bal_2orders),
2910 +                               atomic_read(&sbi->s_bal_breaks),
2911 +                               atomic_read(&sbi->s_mb_lost_chunks));
2912 +               printk("EXT3-fs: mballoc: %lu generated and it took %Lu\n",
2913 +                               sbi->s_mb_buddies_generated++,
2914 +                               sbi->s_mb_generation_time);
2915 +               printk("EXT3-fs: mballoc: %u preallocated, %u discarded\n",
2916 +                               atomic_read(&sbi->s_mb_preallocated),
2917 +                               atomic_read(&sbi->s_mb_discarded));
2918 +       }
2919 +
2920 +       if (sbi->s_locality_groups)
2921 +               kfree(sbi->s_locality_groups);
2922 +
2923 +       ext3_mb_history_release(sb);
2924 +       ext3_mb_destroy_per_dev_proc(sb);
2925 +
2926 +       return 0;
2927 +}
2928 +
2929 +void ext3_mb_free_committed_blocks(struct super_block *sb)
2930 +{
2931 +       struct ext3_sb_info *sbi = EXT3_SB(sb);
2932 +       int err, i, count = 0, count2 = 0;
2933 +       struct ext3_free_metadata *md;
2934 +       struct ext3_buddy e3b;
2935 +
2936 +       if (list_empty(&sbi->s_committed_transaction))
2937 +               return;
2938 +
2939 +       /* there is committed blocks to be freed yet */
2940 +       do {
2941 +               /* get next array of blocks */
2942 +               md = NULL;
2943 +               spin_lock(&sbi->s_md_lock);
2944 +               if (!list_empty(&sbi->s_committed_transaction)) {
2945 +                       md = list_entry(sbi->s_committed_transaction.next,
2946 +                                       struct ext3_free_metadata, list);
2947 +                       list_del(&md->list);
2948 +               }
2949 +               spin_unlock(&sbi->s_md_lock);
2950 +
2951 +               if (md == NULL)
2952 +                       break;
2953 +
2954 +               mb_debug("gonna free %u blocks in group %u (0x%p):",
2955 +                               md->num, md->group, md);
2956 +
2957 +               err = ext3_mb_load_buddy(sb, md->group, &e3b);
2958 +               /* we expect to find existing buddy because it's pinned */
2959 +               BUG_ON(err != 0);
2960 +
2961 +               /* there are blocks to put in buddy to make them really free */
2962 +               count += md->num;
2963 +               count2++;
2964 +               ext3_lock_group(sb, md->group);
2965 +               for (i = 0; i < md->num; i++) {
2966 +                       mb_debug(" %u", md->blocks[i]);
2967 +                       err = mb_free_blocks(NULL, &e3b, md->blocks[i], 1);
2968 +                       BUG_ON(err != 0);
2969 +               }
2970 +               mb_debug("\n");
2971 +               ext3_unlock_group(sb, md->group);
2972 +
2973 +               /* balance refcounts from ext3_mb_free_metadata() */
2974 +               page_cache_release(e3b.bd_buddy_page);
2975 +               page_cache_release(e3b.bd_bitmap_page);
2976 +
2977 +               kfree(md);
2978 +               ext3_mb_release_desc(&e3b);
2979 +
2980 +       } while (md);
2981 +
2982 +       mb_debug("freed %u blocks in %u structures\n", count, count2);
2983 +}
2984 +
2985 +#define EXT3_MB_STATS_NAME             "stats"
2986 +#define EXT3_MB_MAX_TO_SCAN_NAME       "max_to_scan"
2987 +#define EXT3_MB_MIN_TO_SCAN_NAME       "min_to_scan"
2988 +#define EXT3_MB_ORDER2_REQ             "order2_req"
2989 +#define EXT3_MB_SMALL_REQ              "small_req"
2990 +#define EXT3_MB_LARGE_REQ              "large_req"
2991 +#define EXT3_MB_PREALLOC_TABLE         "prealloc_table"
2992 +#define EXT3_MB_GROUP_PREALLOC         "group_prealloc"
2993 +
2994 +static int ext3_mb_read_prealloc_table(char *page, char **start, off_t off,
2995 +                                      int count, int *eof, void *data)
2996 +{
2997 +       struct ext3_sb_info *sbi = data;
2998 +       int len = 0;
2999 +       int i;
3000 +
3001 +       *eof = 1;
3002 +       if (off != 0)
3003 +               return 0;
3004 +
3005 +       for (i = 0; i < sbi->s_mb_prealloc_table_size; i++)
3006 +               len += sprintf(page + len, "%ld ",
3007 +                               sbi->s_mb_prealloc_table[i]);
3008 +       len += sprintf(page + len, "\n");
3009 +
3010 +       *start = page;
3011 +       return len;
3012 +}
3013 +
3014 +static int ext3_mb_write_prealloc_table(struct file *file,
3015 +                                       const char __user *buf,
3016 +                                       unsigned long cnt, void *data)
3017 +{
3018 +       struct ext3_sb_info *sbi = data;
3019 +       unsigned long value;
3020 +       unsigned long prev = 0;
3021 +       char str[128];
3022 +       char *cur;
3023 +       char *end;
3024 +       unsigned long *new_table;
3025 +       int num = 0;
3026 +       int i = 0;
3027 +
3028 +       if (cnt >= sizeof(str))
3029 +               return -EINVAL;
3030 +       if (copy_from_user(str, buf, cnt))
3031 +               return -EFAULT;
3032 +
3033 +       num = 0;
3034 +       cur = str;
3035 +       end = str + cnt;
3036 +       while (cur < end) {
3037 +               while ((cur < end) && (*cur == ' ')) cur++;
3038 +               value = simple_strtol(cur, &cur, 0);
3039 +               if (value == 0)
3040 +                       break;
3041 +               if (value <= prev)
3042 +                       return -EINVAL;
3043 +               prev = value;
3044 +               num++;
3045 +       }
3046 +
3047 +       new_table = kmalloc(num * sizeof(*new_table), GFP_KERNEL);
3048 +       if (new_table == NULL)
3049 +               return -ENOMEM;
3050 +       kfree(sbi->s_mb_prealloc_table);
3051 +       memset(new_table, 0, num * sizeof(*new_table));
3052 +       sbi->s_mb_prealloc_table = new_table;
3053 +       sbi->s_mb_prealloc_table_size = num;
3054 +       cur = str;
3055 +       end = str + cnt;
3056 +       while (cur < end && i < num) {
3057 +               while ((cur < end) && (*cur == ' ')) cur++;
3058 +               value = simple_strtol(cur, &cur, 0);
3059 +               ext3_mb_prealloc_table_add(sbi, value);
3060 +               i++;
3061 +       }
3062 +
3063 +       return cnt;
3064 +}
3065 +
3066 +#define MB_PROC_VALUE_READ(name)                               \
3067 +static int ext3_mb_read_##name(char *page, char **start,       \
3068 +               off_t off, int count, int *eof, void *data)     \
3069 +{                                                              \
3070 +       struct ext3_sb_info *sbi = data;                        \
3071 +       int len;                                                \
3072 +       *eof = 1;                                               \
3073 +       if (off != 0)                                           \
3074 +               return 0;                                       \
3075 +       len = sprintf(page, "%ld\n", sbi->s_mb_##name);         \
3076 +       *start = page;                                          \
3077 +       return len;                                             \
3078 +}
3079 +
3080 +#define MB_PROC_VALUE_WRITE(name)                              \
3081 +static int ext3_mb_write_##name(struct file *file,             \
3082 +               const char __user *buf, unsigned long cnt, void *data)  \
3083 +{                                                              \
3084 +       struct ext3_sb_info *sbi = data;                        \
3085 +       char str[32];                                           \
3086 +       long value;                                             \
3087 +       if (cnt >= sizeof(str))                                 \
3088 +               return -EINVAL;                                 \
3089 +       if (copy_from_user(str, buf, cnt))                      \
3090 +               return -EFAULT;                                 \
3091 +       value = simple_strtol(str, NULL, 0);                    \
3092 +       if (value <= 0)                                         \
3093 +               return -ERANGE;                                 \
3094 +       sbi->s_mb_##name = value;                               \
3095 +       return cnt;                                             \
3096 +}
3097 +
3098 +MB_PROC_VALUE_READ(stats);
3099 +MB_PROC_VALUE_WRITE(stats);
3100 +MB_PROC_VALUE_READ(max_to_scan);
3101 +MB_PROC_VALUE_WRITE(max_to_scan);
3102 +MB_PROC_VALUE_READ(min_to_scan);
3103 +MB_PROC_VALUE_WRITE(min_to_scan);
3104 +MB_PROC_VALUE_READ(order2_reqs);
3105 +MB_PROC_VALUE_WRITE(order2_reqs);
3106 +MB_PROC_VALUE_READ(small_req);
3107 +MB_PROC_VALUE_WRITE(small_req);
3108 +MB_PROC_VALUE_READ(large_req);
3109 +MB_PROC_VALUE_WRITE(large_req);
3110 +MB_PROC_VALUE_READ(group_prealloc);
3111 +MB_PROC_VALUE_WRITE(group_prealloc);
3112 +
3113 +#define        MB_PROC_HANDLER(name, var)                                      \
3114 +do {                                                                   \
3115 +       proc = create_proc_entry(name, mode, sbi->s_dev_proc);          \
3116 +       if (proc == NULL) {                                             \
3117 +               printk(KERN_ERR "EXT3-fs: can't to create %s\n", name); \
3118 +               goto err_out;                                           \
3119 +       }                                                               \
3120 +       proc->data = sbi;                                               \
3121 +       proc->read_proc  = ext3_mb_read_##var ;                         \
3122 +       proc->write_proc = ext3_mb_write_##var;                         \
3123 +} while (0)
3124 +
3125 +int ext3_mb_init_per_dev_proc(struct super_block *sb)
3126 +{
3127 +       struct ext3_sb_info *sbi = EXT3_SB(sb);
3128 +       mode_t mode = S_IFREG | S_IRUGO | S_IWUSR;
3129 +       struct proc_dir_entry *proc;
3130 +
3131 +       MB_PROC_HANDLER(EXT3_MB_STATS_NAME, stats);
3132 +       MB_PROC_HANDLER(EXT3_MB_MAX_TO_SCAN_NAME, max_to_scan);
3133 +       MB_PROC_HANDLER(EXT3_MB_MIN_TO_SCAN_NAME, min_to_scan);
3134 +       MB_PROC_HANDLER(EXT3_MB_ORDER2_REQ, order2_reqs);
3135 +       MB_PROC_HANDLER(EXT3_MB_SMALL_REQ, small_req);
3136 +       MB_PROC_HANDLER(EXT3_MB_LARGE_REQ, large_req);
3137 +       MB_PROC_HANDLER(EXT3_MB_PREALLOC_TABLE, prealloc_table);
3138 +       MB_PROC_HANDLER(EXT3_MB_GROUP_PREALLOC, group_prealloc);
3139 +
3140 +       return 0;
3141 +
3142 +err_out:
3143 +       remove_proc_entry(EXT3_MB_GROUP_PREALLOC, sbi->s_dev_proc);
3144 +       remove_proc_entry(EXT3_MB_PREALLOC_TABLE, sbi->s_dev_proc);
3145 +       remove_proc_entry(EXT3_MB_LARGE_REQ, sbi->s_dev_proc);
3146 +       remove_proc_entry(EXT3_MB_SMALL_REQ, sbi->s_dev_proc);
3147 +       remove_proc_entry(EXT3_MB_ORDER2_REQ, sbi->s_dev_proc);
3148 +       remove_proc_entry(EXT3_MB_MIN_TO_SCAN_NAME, sbi->s_dev_proc);
3149 +       remove_proc_entry(EXT3_MB_MAX_TO_SCAN_NAME, sbi->s_dev_proc);
3150 +       remove_proc_entry(EXT3_MB_STATS_NAME, sbi->s_dev_proc);
3151 +
3152 +       return -ENOMEM;
3153 +}
3154 +
3155 +int ext3_mb_destroy_per_dev_proc(struct super_block *sb)
3156 +{
3157 +       struct ext3_sb_info *sbi = EXT3_SB(sb);
3158 +
3159 +       if (sbi->s_dev_proc == NULL)
3160 +               return -EINVAL;
3161 +
3162 +       remove_proc_entry(EXT3_MB_GROUP_PREALLOC, sbi->s_dev_proc);
3163 +       remove_proc_entry(EXT3_MB_PREALLOC_TABLE, sbi->s_dev_proc);
3164 +       remove_proc_entry(EXT3_MB_SMALL_REQ, sbi->s_dev_proc);
3165 +       remove_proc_entry(EXT3_MB_LARGE_REQ, sbi->s_dev_proc);
3166 +       remove_proc_entry(EXT3_MB_ORDER2_REQ, sbi->s_dev_proc);
3167 +       remove_proc_entry(EXT3_MB_MIN_TO_SCAN_NAME, sbi->s_dev_proc);
3168 +       remove_proc_entry(EXT3_MB_MAX_TO_SCAN_NAME, sbi->s_dev_proc);
3169 +       remove_proc_entry(EXT3_MB_STATS_NAME, sbi->s_dev_proc);
3170 +
3171 +       return 0;
3172 +}
3173 +
3174 +int __init init_ext3_mb_proc(void)
3175 +{
3176 +       ext3_pspace_cachep =
3177 +               kmem_cache_create("ext3_prealloc_space",
3178 +                                    sizeof(struct ext3_prealloc_space),
3179 +                                    0, SLAB_RECLAIM_ACCOUNT, NULL, NULL);
3180 +       if (ext3_pspace_cachep == NULL)
3181 +               return -ENOMEM;
3182 +
3183 +       return 0;
3184 +}
3185 +
3186 +void exit_ext3_mb_proc(void)
3187 +{
3188 +       /* XXX: synchronize_rcu(); */
3189 +       kmem_cache_destroy(ext3_pspace_cachep);
3190 +}
3191 +
3192 +
3193 +/*
3194 + * Check quota and mark choosed space (ac->ac_b_ex) non-free in bitmaps
3195 + * Returns 0 if success or error code
3196 + */
3197 +int ext3_mb_mark_diskspace_used(struct ext3_allocation_context *ac, handle_t *handle)
3198 +{
3199 +       struct buffer_head *bitmap_bh = NULL;
3200 +       struct ext3_super_block *es;
3201 +       struct ext3_group_desc *gdp;
3202 +       struct buffer_head *gdp_bh;
3203 +       struct ext3_sb_info *sbi;
3204 +       struct super_block *sb;
3205 +       sector_t block;
3206 +       int err;
3207 +
3208 +       BUG_ON(ac->ac_status != AC_STATUS_FOUND);
3209 +       BUG_ON(ac->ac_b_ex.fe_len <= 0);
3210 +
3211 +       sb = ac->ac_sb;
3212 +       sbi = EXT3_SB(sb);
3213 +       es = sbi->s_es;
3214 +
3215 +       ext3_debug("using block group %d(%d)\n", ac->ac_b_group.group,
3216 +                       gdp->bg_free_blocks_count);
3217 +
3218 +       err = -EIO;
3219 +       bitmap_bh = read_block_bitmap(sb, ac->ac_b_ex.fe_group);
3220 +       if (!bitmap_bh)
3221 +               goto out_err;
3222 +
3223 +       err = ext3_journal_get_write_access(handle, bitmap_bh);
3224 +       if (err)
3225 +               goto out_err;
3226 +
3227 +       err = -EIO;
3228 +       gdp = ext3_get_group_desc(sb, ac->ac_b_ex.fe_group, &gdp_bh);
3229 +       if (!gdp)
3230 +               goto out_err;
3231 +
3232 +       err = ext3_journal_get_write_access(handle, gdp_bh);
3233 +       if (err)
3234 +               goto out_err;
3235 +
3236 +       block = ac->ac_b_ex.fe_group * EXT3_BLOCKS_PER_GROUP(sb)
3237 +               + ac->ac_b_ex.fe_start
3238 +               + le32_to_cpu(es->s_first_data_block);
3239 +
3240 +       if (block == le32_to_cpu(gdp->bg_block_bitmap) ||
3241 +                       block == le32_to_cpu(gdp->bg_inode_bitmap) ||
3242 +                       in_range(block, le32_to_cpu(gdp->bg_inode_table),
3243 +                               EXT3_SB(sb)->s_itb_per_group))
3244 +               ext3_error(sb, __FUNCTION__,
3245 +                          "Allocating block in system zone - block = %lu",
3246 +                          (unsigned long) block);
3247 +#ifdef AGGRESSIVE_CHECK
3248 +       {
3249 +               int i;
3250 +               for (i = 0; i < ac->ac_b_ex.fe_len; i++) {
3251 +                       BUG_ON(mb_test_bit(ac->ac_b_ex.fe_start + i,
3252 +                                               bitmap_bh->b_data));
3253 +               }
3254 +       }
3255 +#endif
3256 +       mb_set_bits(sb_bgl_lock(sbi, ac->ac_b_ex.fe_group), bitmap_bh->b_data,
3257 +                   ac->ac_b_ex.fe_start, ac->ac_b_ex.fe_len);
3258 +
3259 +       spin_lock(sb_bgl_lock(sbi, ac->ac_b_ex.fe_group));
3260 +       gdp->bg_free_blocks_count =
3261 +               cpu_to_le16(le16_to_cpu(gdp->bg_free_blocks_count)
3262 +                               - ac->ac_b_ex.fe_len);
3263 +       spin_unlock(sb_bgl_lock(sbi, ac->ac_b_ex.fe_group));
3264 +       percpu_counter_mod(&sbi->s_freeblocks_counter, - ac->ac_b_ex.fe_len);
3265 +
3266 +       err = ext3_journal_dirty_metadata(handle, bitmap_bh);
3267 +       if (err)
3268 +               goto out_err;
3269 +       err = ext3_journal_dirty_metadata(handle, gdp_bh);
3270 +
3271 +out_err:
3272 +       sb->s_dirt = 1;
3273 +       brelse(bitmap_bh);
3274 +       return err;
3275 +}
3276 +
3277 +/*
3278 + * here we normalize request for locality group
3279 + * XXX: should we try to preallocate more than the group has now?
3280 + */
3281 +void ext3_mb_normalize_group_request(struct ext3_allocation_context *ac)
3282 +{
3283 +       struct super_block *sb = ac->ac_sb;
3284 +       struct ext3_locality_group *lg = ac->ac_lg;
3285 +
3286 +       BUG_ON(lg == NULL);
3287 +       ac->ac_g_ex.fe_len = EXT3_SB(sb)->s_mb_group_prealloc;
3288 +
3289 +       mb_debug("#%u: goal %u blocks for locality group\n",
3290 +               current->pid, ac->ac_g_ex.fe_len);
3291 +}
3292 +
3293 +/*
3294 + * Normalization means making request better in terms of
3295 + * size and alignment
3296 + */
3297 +void ext3_mb_normalize_request(struct ext3_allocation_context *ac,
3298 +                               struct ext3_allocation_request *ar)
3299 +{
3300 +       struct ext3_inode_info *ei = EXT3_I(ac->ac_inode);
3301 +       struct ext3_sb_info *sbi = EXT3_SB(ac->ac_sb);
3302 +       loff_t start, end, size, orig_size, orig_start;
3303 +       struct list_head *cur;
3304 +       int bsbits, i, wind;
3305 +
3306 +       /* do normalize only data requests, metadata requests
3307 +          do not need preallocation */
3308 +       if (!(ac->ac_flags & EXT3_MB_HINT_DATA))
3309 +               return;
3310 +
3311 +       /* sometime caller may want exact blocks */
3312 +       if (unlikely(ac->ac_flags & EXT3_MB_HINT_GOAL_ONLY))
3313 +               return;
3314 +
3315 +       /* caller may indicate that preallocation isn't
3316 +        * required (it's a tail, for example) */
3317 +       if (ac->ac_flags & EXT3_MB_HINT_NOPREALLOC)
3318 +               return;
3319 +
3320 +       if (ac->ac_flags & EXT3_MB_HINT_GROUP_ALLOC)
3321 +               return ext3_mb_normalize_group_request(ac);
3322 +
3323 +       bsbits = ac->ac_sb->s_blocksize_bits;
3324 +
3325 +       /* first, let's learn actual file size
3326 +        * given current request is allocated */
3327 +       size = ac->ac_o_ex.fe_logical + ac->ac_o_ex.fe_len;
3328 +       size = size << bsbits;
3329 +       if (size < i_size_read(ac->ac_inode))
3330 +               size = i_size_read(ac->ac_inode);
3331 +       size = (size + ac->ac_sb->s_blocksize - 1) >> bsbits;
3332 +
3333 +       start = 0;
3334 +       wind = 0;
3335 +
3336 +       /* let's choose preallocation window depending on file size */
3337 +       for (i = 0; i < sbi->s_mb_prealloc_table_size; i++) {
3338 +               if (size <= sbi->s_mb_prealloc_table[i]) {
3339 +                       wind = sbi->s_mb_prealloc_table[i];
3340 +                       break;
3341 +               }
3342 +       }
3343 +       size = wind;
3344 +
3345 +       if (wind == 0) {
3346 +               __u64 tstart, tend;
3347 +               /* file is quite large, we now preallocate with
3348 +                * the biggest configured window with regart to
3349 +                * logical offset */
3350 +               wind = sbi->s_mb_prealloc_table[i - 1];
3351 +               tstart = ac->ac_o_ex.fe_logical;
3352 +               do_div(tstart, wind);
3353 +               start = tstart * wind;
3354 +               tend = ac->ac_o_ex.fe_logical + ac->ac_o_ex.fe_len - 1;
3355 +               do_div(tend, wind);
3356 +               tend = tend * wind + wind;
3357 +               size = tend - start;
3358 +       }
3359 +       orig_size = size;
3360 +       orig_start = start;
3361 +
3362 +       /* don't cover already allocated blocks in selected range */
3363 +       if (ar->pleft && start <= ar->lleft) {
3364 +               size -= ar->lleft + 1 - start;
3365 +               start = ar->lleft + 1;
3366 +       }
3367 +       if (ar->pright && start + size - 1 >= ar->lright)
3368 +               size -= start + size - ar->lright;
3369 +
3370 +       end = start + size;
3371 +
3372 +       /* check we don't cross already preallocated blocks */
3373 +       rcu_read_lock();
3374 +       list_for_each_rcu(cur, &ei->i_prealloc_list) {
3375 +               struct ext3_prealloc_space *pa;
3376 +               unsigned long pa_end;
3377 +
3378 +               pa = list_entry(cur, struct ext3_prealloc_space, pa_inode_list);
3379 +
3380 +               if (pa->pa_deleted)
3381 +                       continue;
3382 +               spin_lock(&pa->pa_lock);
3383 +               if (pa->pa_deleted) {
3384 +                       spin_unlock(&pa->pa_lock);
3385 +                       continue;
3386 +               }
3387 +
3388 +               pa_end = pa->pa_lstart + pa->pa_len;
3389 +
3390 +               /* PA must not overlap original request */
3391 +               BUG_ON(!(ac->ac_o_ex.fe_logical >= pa_end ||
3392 +                       ac->ac_o_ex.fe_logical < pa->pa_lstart));
3393 +
3394 +               /* skip PA normalized request doesn't overlap with */
3395 +               if (pa->pa_lstart >= end) {
3396 +                       spin_unlock(&pa->pa_lock);
3397 +                       continue;
3398 +               }
3399 +               if (pa_end <= start) {
3400 +                       spin_unlock(&pa->pa_lock);
3401 +                       continue;
3402 +               }
3403 +               BUG_ON(pa->pa_lstart <= start && pa_end >= end);
3404 +
3405 +               if (pa_end <= ac->ac_o_ex.fe_logical) {
3406 +                       BUG_ON(pa_end < start);
3407 +                       start = pa_end;
3408 +               }
3409 +
3410 +               if (pa->pa_lstart > ac->ac_o_ex.fe_logical) {
3411 +                       BUG_ON(pa->pa_lstart > end);
3412 +                       end = pa->pa_lstart;
3413 +               }
3414 +               spin_unlock(&pa->pa_lock);
3415 +       }
3416 +       rcu_read_unlock();
3417 +       size = end - start;
3418 +
3419 +       /* XXX: extra loop to check we really don't overlap preallocations */
3420 +       rcu_read_lock();
3421 +       list_for_each_rcu(cur, &ei->i_prealloc_list) {
3422 +               struct ext3_prealloc_space *pa;
3423 +               unsigned long pa_end;
3424 +               pa = list_entry(cur, struct ext3_prealloc_space, pa_inode_list);
3425 +               spin_lock(&pa->pa_lock);
3426 +               if (pa->pa_deleted == 0) {
3427 +                       pa_end = pa->pa_lstart + pa->pa_len;
3428 +                       BUG_ON(!(start >= pa_end || end <= pa->pa_lstart));
3429 +               }
3430 +               spin_unlock(&pa->pa_lock);
3431 +       }
3432 +       rcu_read_unlock();
3433 +
3434 +       if (start + size <= ac->ac_o_ex.fe_logical &&
3435 +                       start > ac->ac_o_ex.fe_logical) {
3436 +               printk("start %lu, size %lu, fe_logical %lu\n",
3437 +                       (unsigned long) start, (unsigned long) size,
3438 +                       (unsigned long) ac->ac_o_ex.fe_logical);
3439 +       }
3440 +       BUG_ON(start + size <= ac->ac_o_ex.fe_logical &&
3441 +                       start > ac->ac_o_ex.fe_logical);