Whamcloud - gitweb
70f4f8af288ea675294ff7c70bafa3c7cd74a272
[fs/lustre-release.git] / ldiskfs / kernel_patches / patches / ext3-mballoc2-2.6.12.patch
1 Index: linux-2.6.12.6/include/linux/ext3_fs.h
2 ===================================================================
3 --- linux-2.6.12.6.orig/include/linux/ext3_fs.h 2005-12-17 02:17:16.000000000 +0300
4 +++ linux-2.6.12.6/include/linux/ext3_fs.h      2005-12-17 02:21:21.000000000 +0300
5 @@ -57,6 +57,14 @@ struct statfs;
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
12 +#define EXT3_MB_HINT_RESERVED          2
13 +#define EXT3_MB_HINT_METADATA          4
14 +#define EXT3_MB_HINT_FIRST             8
15 +#define EXT3_MB_HINT_BEST              16
16 +
17  /*
18   * Special inodes numbers
19   */
20 @@ -366,6 +374,7 @@ struct ext3_inode {
21  #define EXT3_MOUNT_IOPEN_NOPRIV                0x100000/* Make iopen world-readable */
22  #define EXT3_MOUNT_EXTENTS             0x200000/* Extents support */
23  #define EXT3_MOUNT_EXTDEBUG            0x400000/* Extents debug */
24 +#define EXT3_MOUNT_MBALLOC             0x800000/* Buddy allocation support */
25  
26  /* Compatibility, for having both ext2_fs.h and ext3_fs.h included at once */
27  #ifndef clear_opt
28 @@ -727,7 +736,7 @@ extern int ext3_bg_has_super(struct supe
29  extern unsigned long ext3_bg_num_gdb(struct super_block *sb, int group);
30  extern int ext3_new_block (handle_t *, struct inode *, unsigned long, int *);
31  extern void ext3_free_blocks (handle_t *, struct inode *, unsigned long,
32 -                             unsigned long);
33 +                             unsigned long, int);
34  extern void ext3_free_blocks_sb (handle_t *, struct super_block *,
35                                  unsigned long, unsigned long, int *);
36  extern unsigned long ext3_count_free_blocks (struct super_block *);
37 @@ -848,6 +857,17 @@ extern void ext3_extents_initialize_bloc
38  extern int ext3_ext_ioctl(struct inode *inode, struct file *filp,
39                           unsigned int cmd, unsigned long arg);
40  
41 +/* mballoc.c */
42 +extern long ext3_mb_stats;
43 +extern long ext3_mb_max_to_scan;
44 +extern int ext3_mb_init(struct super_block *, int);
45 +extern int ext3_mb_release(struct super_block *);
46 +extern int ext3_mb_new_blocks(handle_t *, struct inode *, unsigned long, int *, int, int *);
47 +extern int ext3_mb_reserve_blocks(struct super_block *, int);
48 +extern void ext3_mb_release_blocks(struct super_block *, int);
49 +int __init init_ext3_proc(void);
50 +void exit_ext3_proc(void);
51 +
52  #endif /* __KERNEL__ */
53  
54  /* EXT3_IOC_CREATE_INUM at bottom of file (visible to kernel and user). */
55 Index: linux-2.6.12.6/include/linux/ext3_fs_sb.h
56 ===================================================================
57 --- linux-2.6.12.6.orig/include/linux/ext3_fs_sb.h      2005-08-29 20:55:27.000000000 +0400
58 +++ linux-2.6.12.6/include/linux/ext3_fs_sb.h   2005-12-17 02:21:21.000000000 +0300
59 @@ -21,8 +21,14 @@
60  #include <linux/wait.h>
61  #include <linux/blockgroup_lock.h>
62  #include <linux/percpu_counter.h>
63 +#include <linux/list.h>
64  #endif
65  #include <linux/rbtree.h>
66 +#include <linux/proc_fs.h>
67 +
68 +struct ext3_buddy_group_blocks;
69 +struct ext3_mb_history;
70 +#define EXT3_BB_MAX_BLOCKS
71  
72  /*
73   * third extended-fs super-block data in memory
74 @@ -78,6 +84,38 @@ struct ext3_sb_info {
75         char *s_qf_names[MAXQUOTAS];            /* Names of quota files with journalled quota */
76         int s_jquota_fmt;                       /* Format of quota to use */
77  #endif
78 +
79 +       /* for buddy allocator */
80 +       struct ext3_group_info **s_group_info;
81 +       struct inode *s_buddy_cache;
82 +       long s_blocks_reserved;
83 +       spinlock_t s_reserve_lock;
84 +       struct list_head s_active_transaction;
85 +       struct list_head s_closed_transaction;
86 +       struct list_head s_committed_transaction;
87 +       spinlock_t s_md_lock;
88 +       tid_t s_last_transaction;
89 +       int s_mb_factor;
90 +       unsigned short *s_mb_offsets, *s_mb_maxs;
91 +
92 +       /* history to debug policy */
93 +       struct ext3_mb_history *s_mb_history;
94 +       int s_mb_history_cur;
95 +       int s_mb_history_max;
96 +       struct proc_dir_entry *s_mb_proc;
97 +       spinlock_t s_mb_history_lock;
98 +
99 +       /* stats for buddy allocator */
100 +       atomic_t s_bal_reqs;    /* number of reqs with len > 1 */
101 +       atomic_t s_bal_success; /* we found long enough chunks */
102 +       atomic_t s_bal_allocated;       /* in blocks */
103 +       atomic_t s_bal_ex_scanned;      /* total extents scanned */
104 +       atomic_t s_bal_goals;   /* goal hits */
105 +       atomic_t s_bal_breaks;  /* too long searches */
106 +       atomic_t s_bal_2orders; /* 2^order hits */
107 +       spinlock_t s_bal_lock;
108 +       unsigned long s_mb_buddies_generated;
109 +       unsigned long long s_mb_generation_time;
110  };
111  
112  #endif /* _LINUX_EXT3_FS_SB */
113 Index: linux-2.6.12.6/fs/ext3/super.c
114 ===================================================================
115 --- linux-2.6.12.6.orig/fs/ext3/super.c 2005-12-17 02:17:16.000000000 +0300
116 +++ linux-2.6.12.6/fs/ext3/super.c      2005-12-17 02:21:21.000000000 +0300
117 @@ -387,6 +387,7 @@ static void ext3_put_super (struct super
118         struct ext3_super_block *es = sbi->s_es;
119         int i;
120  
121 +       ext3_mb_release(sb);
122         ext3_ext_release(sb);
123         ext3_xattr_put_super(sb);
124         journal_destroy(sbi->s_journal);
125 @@ -597,7 +598,7 @@ enum {
126         Opt_jqfmt_vfsold, Opt_jqfmt_vfsv0,
127         Opt_ignore, Opt_barrier, Opt_err, Opt_resize,
128         Opt_iopen, Opt_noiopen, Opt_iopen_nopriv,
129 -       Opt_extents, Opt_extdebug,
130 +       Opt_extents, Opt_extdebug, Opt_mballoc,
131  };
132  
133  static match_table_t tokens = {
134 @@ -649,6 +651,7 @@ static match_table_t tokens = {
135         {Opt_iopen_nopriv, "iopen_nopriv"},
136         {Opt_extents, "extents"},
137         {Opt_extdebug, "extdebug"},
138 +       {Opt_mballoc, "mballoc"},
139         {Opt_barrier, "barrier=%u"},
140         {Opt_err, NULL},
141         {Opt_resize, "resize"},
142 @@ -964,6 +967,9 @@ clear_qf_name:
143                 case Opt_extdebug:
144                         set_opt (sbi->s_mount_opt, EXTDEBUG);
145                         break;
146 +               case Opt_mballoc:
147 +                       set_opt (sbi->s_mount_opt, MBALLOC);
148 +                       break;
149                 default:
150                         printk (KERN_ERR
151                                 "EXT3-fs: Unrecognized mount option \"%s\" "
152 @@ -1669,6 +1675,7 @@ static int ext3_fill_super (struct super
153                 ext3_count_dirs(sb));
154  
155         ext3_ext_init(sb);
156 +       ext3_mb_init(sb, needs_recovery);
157         lock_kernel();
158         return 0;
159  
160 @@ -2548,7 +2555,13 @@ static struct file_system_type ext3_fs_t
161  
162  static int __init init_ext3_fs(void)
163  {
164 -       int err = init_ext3_xattr();
165 +       int err;
166 +
167 +       err = init_ext3_proc();
168 +       if (err)
169 +               return err;
170 +
171 +       err = init_ext3_xattr();
172         if (err)
173                 return err;
174         err = init_inodecache();
175 @@ -2570,6 +2583,7 @@ static void __exit exit_ext3_fs(void)
176         unregister_filesystem(&ext3_fs_type);
177         destroy_inodecache();
178         exit_ext3_xattr();
179 +       exit_ext3_proc();
180  }
181  
182  int ext3_prep_san_write(struct inode *inode, long *blocks,
183 Index: linux-2.6.12.6/fs/ext3/extents.c
184 ===================================================================
185 --- linux-2.6.12.6.orig/fs/ext3/extents.c       2005-12-17 02:17:16.000000000 +0300
186 +++ linux-2.6.12.6/fs/ext3/extents.c    2005-12-17 02:21:21.000000000 +0300
187 @@ -771,7 +771,7 @@ cleanup:
188                 for (i = 0; i < depth; i++) {
189                         if (!ablocks[i])
190                                 continue;
191 -                       ext3_free_blocks(handle, tree->inode, ablocks[i], 1);
192 +                       ext3_free_blocks(handle, tree->inode, ablocks[i], 1, 1);
193                 }
194         }
195         kfree(ablocks);
196 @@ -1428,7 +1428,7 @@ int ext3_ext_rm_idx(handle_t *handle, st
197                   path->p_idx->ei_leaf);
198         bh = sb_find_get_block(tree->inode->i_sb, path->p_idx->ei_leaf);
199         ext3_forget(handle, 1, tree->inode, bh, path->p_idx->ei_leaf);
200 -       ext3_free_blocks(handle, tree->inode, path->p_idx->ei_leaf, 1);
201 +       ext3_free_blocks(handle, tree->inode, path->p_idx->ei_leaf, 1, 1);
202         return err;
203  }
204  
205 @@ -1913,10 +1913,12 @@ ext3_remove_blocks(struct ext3_extents_t
206         int needed = ext3_remove_blocks_credits(tree, ex, from, to);
207         handle_t *handle = ext3_journal_start(tree->inode, needed);
208         struct buffer_head *bh;
209 -       int i;
210 +       int i, metadata = 0;
211  
212         if (IS_ERR(handle))
213                 return PTR_ERR(handle);
214 +       if (S_ISDIR(tree->inode->i_mode) || S_ISLNK(tree->inode->i_mode))
215 +               metadata = 1;
216         if (from >= ex->ee_block && to == ex->ee_block + ex->ee_len - 1) {
217                 /* tail removal */
218                 unsigned long num, start;
219 @@ -1928,7 +1930,7 @@ ext3_remove_blocks(struct ext3_extents_t
220                         bh = sb_find_get_block(tree->inode->i_sb, start + i);
221                         ext3_forget(handle, 0, tree->inode, bh, start + i);
222                 }
223 -               ext3_free_blocks(handle, tree->inode, start, num);
224 +               ext3_free_blocks(handle, tree->inode, start, num, metadata);
225         } else if (from == ex->ee_block && to <= ex->ee_block + ex->ee_len - 1) {
226                 printk("strange request: removal %lu-%lu from %u:%u\n",
227                        from, to, ex->ee_block, ex->ee_len);
228 Index: linux-2.6.12.6/fs/ext3/inode.c
229 ===================================================================
230 --- linux-2.6.12.6.orig/fs/ext3/inode.c 2005-12-17 02:17:16.000000000 +0300
231 +++ linux-2.6.12.6/fs/ext3/inode.c      2005-12-17 02:21:21.000000000 +0300
232 @@ -564,7 +564,7 @@ static int ext3_alloc_branch(handle_t *h
233                 ext3_journal_forget(handle, branch[i].bh);
234         }
235         for (i = 0; i < keys; i++)
236 -               ext3_free_blocks(handle, inode, le32_to_cpu(branch[i].key), 1);
237 +               ext3_free_blocks(handle, inode, le32_to_cpu(branch[i].key), 1, 1);
238         return err;
239  }
240  
241 @@ -1850,7 +1850,7 @@ ext3_clear_blocks(handle_t *handle, stru
242                 }
243         }
244  
245 -       ext3_free_blocks(handle, inode, block_to_free, count);
246 +       ext3_free_blocks(handle, inode, block_to_free, count, 1);
247  }
248  
249  /**
250 @@ -2023,7 +2023,7 @@ static void ext3_free_branches(handle_t 
251                                 ext3_journal_test_restart(handle, inode);
252                         }
253  
254 -                       ext3_free_blocks(handle, inode, nr, 1);
255 +                       ext3_free_blocks(handle, inode, nr, 1, 1);
256  
257                         if (parent_bh) {
258                                 /*
259 Index: linux-2.6.12.6/fs/ext3/balloc.c
260 ===================================================================
261 --- linux-2.6.12.6.orig/fs/ext3/balloc.c        2005-08-29 20:55:27.000000000 +0400
262 +++ linux-2.6.12.6/fs/ext3/balloc.c     2005-12-17 02:21:21.000000000 +0300
263 @@ -79,7 +79,7 @@ struct ext3_group_desc * ext3_get_group_
264   *
265   * Return buffer_head on success or NULL in case of failure.
266   */
267 -static struct buffer_head *
268 +struct buffer_head *
269  read_block_bitmap(struct super_block *sb, unsigned int block_group)
270  {
271         struct ext3_group_desc * desc;
272 @@ -490,24 +490,6 @@ error_return:
273         return;
274  }
275  
276 -/* Free given blocks, update quota and i_blocks field */
277 -void ext3_free_blocks(handle_t *handle, struct inode *inode,
278 -                       unsigned long block, unsigned long count)
279 -{
280 -       struct super_block * sb;
281 -       int dquot_freed_blocks;
282 -
283 -       sb = inode->i_sb;
284 -       if (!sb) {
285 -               printk ("ext3_free_blocks: nonexistent device");
286 -               return;
287 -       }
288 -       ext3_free_blocks_sb(handle, sb, block, count, &dquot_freed_blocks);
289 -       if (dquot_freed_blocks)
290 -               DQUOT_FREE_BLOCK(inode, dquot_freed_blocks);
291 -       return;
292 -}
293 -
294  /*
295   * For ext3 allocations, we must not reuse any blocks which are
296   * allocated in the bitmap buffer's "last committed data" copy.  This
297 @@ -1162,7 +1144,7 @@ int ext3_should_retry_alloc(struct super
298   * bitmap, and then for any free bit if that fails.
299   * This function also updates quota and i_blocks field.
300   */
301 -int ext3_new_block(handle_t *handle, struct inode *inode,
302 +int ext3_new_block_old(handle_t *handle, struct inode *inode,
303                         unsigned long goal, int *errp)
304  {
305         struct buffer_head *bitmap_bh = NULL;
306 Index: linux-2.6.12.6/fs/ext3/xattr.c
307 ===================================================================
308 --- linux-2.6.12.6.orig/fs/ext3/xattr.c 2005-08-29 20:55:27.000000000 +0400
309 +++ linux-2.6.12.6/fs/ext3/xattr.c      2005-12-17 02:21:33.000000000 +0300
310 @@ -484,7 +484,7 @@ ext3_xattr_release_block(handle_t *handl
311                 ea_bdebug(bh, "refcount now=0; freeing");
312                 if (ce)
313                         mb_cache_entry_free(ce);
314 -               ext3_free_blocks(handle, inode, bh->b_blocknr, 1);
315 +               ext3_free_blocks(handle, inode, bh->b_blocknr, 1, 1);
316                 get_bh(bh);
317                 ext3_forget(handle, 1, inode, bh, bh->b_blocknr);
318         } else {
319 @@ -804,7 +804,7 @@ inserted:
320                         new_bh = sb_getblk(sb, block);
321                         if (!new_bh) {
322  getblk_failed:
323 -                               ext3_free_blocks(handle, inode, block, 1);
324 +                               ext3_free_blocks(handle, inode, block, 1, 1);
325                                 error = -EIO;
326                                 goto cleanup;
327                         }
328 Index: linux-2.6.12.6/fs/ext3/mballoc.c
329 ===================================================================
330 --- linux-2.6.12.6.orig/fs/ext3/mballoc.c       2005-12-09 13:08:53.191437750 +0300
331 +++ linux-2.6.12.6/fs/ext3/mballoc.c    2005-12-17 02:21:21.000000000 +0300
332 @@ -0,0 +1,2429 @@
333 +/*
334 + * Copyright (c) 2003-2005, Cluster File Systems, Inc, info@clusterfs.com
335 + * Written by Alex Tomas <alex@clusterfs.com>
336 + *
337 + * This program is free software; you can redistribute it and/or modify
338 + * it under the terms of the GNU General Public License version 2 as
339 + * published by the Free Software Foundation.
340 + *
341 + * This program is distributed in the hope that it will be useful,
342 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
343 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
344 + * GNU General Public License for more details.
345 + *
346 + * You should have received a copy of the GNU General Public Licens
347 + * along with this program; if not, write to the Free Software
348 + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-
349 + */
350 +
351 +
352 +/*
353 + * mballoc.c contains the multiblocks allocation routines
354 + */
355 +
356 +#include <linux/config.h>
357 +#include <linux/time.h>
358 +#include <linux/fs.h>
359 +#include <linux/namei.h>
360 +#include <linux/jbd.h>
361 +#include <linux/ext3_fs.h>
362 +#include <linux/ext3_jbd.h>
363 +#include <linux/quotaops.h>
364 +#include <linux/buffer_head.h>
365 +#include <linux/module.h>
366 +#include <linux/swap.h>
367 +#include <linux/proc_fs.h>
368 +#include <linux/pagemap.h>
369 +#include <linux/seq_file.h>
370 +
371 +/*
372 + * TODO:
373 + *   - bitmap read-ahead (proposed by Oleg Drokin aka green)
374 + *   - track min/max extents in each group for better group selection
375 + *   - mb_mark_used() may allocate chunk right after splitting buddy
376 + *   - special flag to advice allocator to look for requested + N blocks
377 + *     this may improve interaction between extents and mballoc
378 + *   - tree of groups sorted by number of free blocks
379 + *   - percpu reservation code (hotpath)
380 + *   - error handling
381 + */
382 +
383 +/*
384 + * with AGRESSIVE_CHECK allocator runs consistency checks over
385 + * structures. these checks slow things down a lot
386 + */
387 +#define AGGRESSIVE_CHECK__
388 +
389 +/*
390 + */
391 +#define MB_DEBUG__
392 +#ifdef MB_DEBUG
393 +#define mb_debug(fmt,a...)     printk(fmt, ##a)
394 +#else
395 +#define mb_debug(fmt,a...)
396 +#endif
397 +
398 +/*
399 + * with EXT3_MB_HISTORY mballoc stores last N allocations in memory
400 + * and you can monitor it in /proc/fs/ext3/<dev>/mb_history
401 + */
402 +#define EXT3_MB_HISTORY
403 +
404 +/*
405 + * How long mballoc can look for a best extent (in found extents)
406 + */
407 +long ext3_mb_max_to_scan = 500;
408 +
409 +/*
410 + * How long mballoc must look for a best extent
411 + */
412 +long ext3_mb_min_to_scan = 30;
413 +
414 +/*
415 + * with 'ext3_mb_stats' allocator will collect stats that will be
416 + * shown at umount. The collecting costs though!
417 + */
418 +
419 +long ext3_mb_stats = 1;
420 +
421 +#ifdef EXT3_BB_MAX_BLOCKS
422 +#undef EXT3_BB_MAX_BLOCKS
423 +#endif
424 +#define EXT3_BB_MAX_BLOCKS     30
425 +
426 +struct ext3_free_metadata {
427 +       unsigned short group;
428 +       unsigned short num;
429 +       unsigned short blocks[EXT3_BB_MAX_BLOCKS];
430 +       struct list_head list;
431 +};
432 +
433 +struct ext3_group_info {
434 +       unsigned long   bb_state;
435 +       unsigned long   bb_tid;
436 +       struct ext3_free_metadata *bb_md_cur;
437 +       unsigned short  bb_first_free;
438 +       unsigned short  bb_free;
439 +       unsigned short  bb_fragments;
440 +       unsigned short  bb_counters[];
441 +};
442 +
443 +
444 +#define EXT3_GROUP_INFO_NEED_INIT_BIT  0
445 +#define EXT3_GROUP_INFO_LOCKED_BIT     1
446 +
447 +#define EXT3_MB_GRP_NEED_INIT(grp)     \
448 +       (test_bit(EXT3_GROUP_INFO_NEED_INIT_BIT, &(grp)->bb_state))
449 +
450 +struct ext3_free_extent {
451 +       __u16 fe_start;
452 +       __u16 fe_len;
453 +       __u16 fe_group;
454 +};
455 +
456 +struct ext3_allocation_context {
457 +       struct super_block *ac_sb;
458 +
459 +       /* search goals */
460 +       struct ext3_free_extent ac_g_ex;
461 +       
462 +       /* the best found extent */
463 +       struct ext3_free_extent ac_b_ex;
464 +       
465 +       /* number of iterations done. we have to track to limit searching */
466 +       unsigned long ac_ex_scanned;
467 +       __u16 ac_groups_scanned;
468 +       __u16 ac_found;
469 +       __u16 ac_tail;
470 +       __u16 ac_buddy;
471 +       __u8 ac_status; 
472 +       __u8 ac_flags;          /* allocation hints */
473 +       __u8 ac_criteria;
474 +       __u8 ac_repeats;
475 +       __u8 ac_2order;         /* if request is to allocate 2^N blocks and
476 +                                * N > 0, the field stores N, otherwise 0 */
477 +};
478 +
479 +#define AC_STATUS_CONTINUE     1
480 +#define AC_STATUS_FOUND                2
481 +#define AC_STATUS_BREAK                3
482 +
483 +struct ext3_mb_history {
484 +       struct ext3_free_extent goal;   /* goal allocation */
485 +       struct ext3_free_extent result; /* result allocation */
486 +       __u16 found;    /* how many extents have been found */
487 +       __u16 groups;   /* how many groups have been scanned */
488 +       __u16 tail;     /* what tail broke some buddy */
489 +       __u16 buddy;    /* buddy the tail ^^^ broke */
490 +       __u8 cr;        /* which phase the result extent was found at */
491 +       __u8 merged;
492 +};
493 +
494 +struct ext3_buddy {
495 +       struct page *bd_buddy_page;
496 +       void *bd_buddy;
497 +       struct page *bd_bitmap_page;
498 +       void *bd_bitmap;
499 +       struct ext3_group_info *bd_info;
500 +       struct super_block *bd_sb;
501 +       __u16 bd_blkbits;
502 +       __u16 bd_group;
503 +};
504 +#define EXT3_MB_BITMAP(e3b)    ((e3b)->bd_bitmap)
505 +#define EXT3_MB_BUDDY(e3b)     ((e3b)->bd_buddy)
506 +
507 +#ifndef EXT3_MB_HISTORY
508 +#define ext3_mb_store_history(sb,ac)
509 +#else
510 +static void ext3_mb_store_history(struct super_block *,
511 +                               struct ext3_allocation_context *ac);
512 +#endif
513 +
514 +#define in_range(b, first, len)        ((b) >= (first) && (b) <= (first) + (len) - 1)
515 +
516 +static struct proc_dir_entry *proc_root_ext3;
517 +
518 +int ext3_create (struct inode *, struct dentry *, int, struct nameidata *);
519 +struct buffer_head * read_block_bitmap(struct super_block *, unsigned int);
520 +int ext3_new_block_old(handle_t *, struct inode *, unsigned long, int *);
521 +int ext3_mb_reserve_blocks(struct super_block *, int);
522 +void ext3_mb_release_blocks(struct super_block *, int);
523 +void ext3_mb_poll_new_transaction(struct super_block *, handle_t *);
524 +void ext3_mb_free_committed_blocks(struct super_block *);
525 +
526 +#if BITS_PER_LONG == 64
527 +#define mb_correct_addr_and_bit(bit,addr)              \
528 +{                                                      \
529 +       bit += ((unsigned long) addr & 7UL) << 3;       \
530 +       addr = (void *) ((unsigned long) addr & ~7UL);  \
531 +}
532 +#elif BITS_PER_LONG == 32
533 +#define mb_correct_addr_and_bit(bit,addr)              \
534 +{                                                      \
535 +       bit += ((unsigned long) addr & 3UL) << 3;       \
536 +       addr = (void *) ((unsigned long) addr & ~3UL);  \
537 +}
538 +#else
539 +#error "how many bits you are?!"
540 +#endif
541 +
542 +static inline int mb_test_bit(int bit, void *addr)
543 +{
544 +       mb_correct_addr_and_bit(bit,addr);
545 +       return ext2_test_bit(bit, addr);
546 +}
547 +
548 +static inline void mb_set_bit(int bit, void *addr)
549 +{
550 +       mb_correct_addr_and_bit(bit,addr);
551 +       ext2_set_bit(bit, addr);
552 +}
553 +
554 +static inline void mb_set_bit_atomic(int bit, void *addr)
555 +{
556 +       mb_correct_addr_and_bit(bit,addr);
557 +       ext2_set_bit_atomic(NULL, bit, addr);
558 +}
559 +
560 +static inline void mb_clear_bit(int bit, void *addr)
561 +{
562 +       mb_correct_addr_and_bit(bit,addr);
563 +       ext2_clear_bit(bit, addr);
564 +}
565 +
566 +static inline void mb_clear_bit_atomic(int bit, void *addr)
567 +{
568 +       mb_correct_addr_and_bit(bit,addr);
569 +       ext2_clear_bit_atomic(NULL, bit, addr);
570 +}
571 +
572 +static inline int mb_find_next_zero_bit(void *addr, int max, int start)
573 +{
574 +       int fix;
575 +#if BITS_PER_LONG == 64
576 +       fix = ((unsigned long) addr & 7UL) << 3;
577 +       addr = (void *) ((unsigned long) addr & ~7UL);
578 +#elif BITS_PER_LONG == 32
579 +       fix = ((unsigned long) addr & 3UL) << 3;
580 +       addr = (void *) ((unsigned long) addr & ~3UL);
581 +#else
582 +#error "how many bits you are?!"
583 +#endif
584 +       max += fix;
585 +       start += fix;
586 +       return ext2_find_next_zero_bit(addr, max, start) - fix;
587 +}
588 +
589 +static inline void *mb_find_buddy(struct ext3_buddy *e3b, int order, int *max)
590 +{
591 +       char *bb;
592 +
593 +       J_ASSERT(EXT3_MB_BITMAP(e3b) != EXT3_MB_BUDDY(e3b));
594 +       J_ASSERT(max != NULL);
595 +
596 +       if (order > e3b->bd_blkbits + 1) {
597 +               *max = 0;
598 +               return NULL;
599 +       }
600 +
601 +       /* at order 0 we see each particular block */
602 +       *max = 1 << (e3b->bd_blkbits + 3);
603 +       if (order == 0)
604 +               return EXT3_MB_BITMAP(e3b);
605 +
606 +       bb = EXT3_MB_BUDDY(e3b) + EXT3_SB(e3b->bd_sb)->s_mb_offsets[order];
607 +       *max = EXT3_SB(e3b->bd_sb)->s_mb_maxs[order];
608 +
609 +       return bb;
610 +}
611 +
612 +#ifdef AGGRESSIVE_CHECK
613 +
614 +static void mb_check_buddy(struct ext3_buddy *e3b)
615 +{
616 +       int order = e3b->bd_blkbits + 1;
617 +       int max, max2, i, j, k, count;
618 +       int fragments = 0, fstart;
619 +       void *buddy, *buddy2;
620 +
621 +       if (!test_opt(e3b->bd_sb, MBALLOC))
622 +               return;
623 +
624 +       {
625 +               static int mb_check_counter = 0;
626 +               if (mb_check_counter++ % 300 != 0)
627 +                       return;
628 +       }
629 +       
630 +       while (order > 1) {
631 +               buddy = mb_find_buddy(e3b, order, &max);
632 +               J_ASSERT(buddy);
633 +               buddy2 = mb_find_buddy(e3b, order - 1, &max2);
634 +               J_ASSERT(buddy2);
635 +               J_ASSERT(buddy != buddy2);
636 +               J_ASSERT(max * 2 == max2);
637 +
638 +               count = 0;
639 +               for (i = 0; i < max; i++) {
640 +
641 +                       if (mb_test_bit(i, buddy)) {
642 +                               /* only single bit in buddy2 may be 1 */
643 +                               if (!mb_test_bit(i << 1, buddy2))
644 +                                       J_ASSERT(mb_test_bit((i<<1)+1, buddy2));
645 +                               else if (!mb_test_bit((i << 1) + 1, buddy2))
646 +                                       J_ASSERT(mb_test_bit(i << 1, buddy2));
647 +                               continue;
648 +                       }
649 +
650 +                       /* both bits in buddy2 must be 0 */
651 +                       J_ASSERT(mb_test_bit(i << 1, buddy2));
652 +                       J_ASSERT(mb_test_bit((i << 1) + 1, buddy2));
653 +
654 +                       for (j = 0; j < (1 << order); j++) {
655 +                               k = (i * (1 << order)) + j;
656 +                               J_ASSERT(!mb_test_bit(k, EXT3_MB_BITMAP(e3b)));
657 +                       }
658 +                       count++;
659 +               }
660 +               J_ASSERT(e3b->bd_info->bb_counters[order] == count);
661 +               order--;
662 +       }
663 +
664 +       fstart = -1;
665 +       buddy = mb_find_buddy(e3b, 0, &max);
666 +       for (i = 0; i < max; i++) {
667 +               if (!mb_test_bit(i, buddy)) {
668 +                       J_ASSERT(i >= e3b->bd_info->bb_first_free);
669 +                       if (fstart == -1) {
670 +                               fragments++;
671 +                               fstart = i;
672 +                       }
673 +                       continue;
674 +               }
675 +               fstart = -1;
676 +               /* check used bits only */
677 +               for (j = 0; j < e3b->bd_blkbits + 1; j++) {
678 +                       buddy2 = mb_find_buddy(e3b, j, &max2);
679 +                       k = i >> j;
680 +                       J_ASSERT(k < max2);
681 +                       J_ASSERT(mb_test_bit(k, buddy2));
682 +               }
683 +       }
684 +       J_ASSERT(!EXT3_MB_GRP_NEED_INIT(e3b->bd_info));
685 +       J_ASSERT(e3b->bd_info->bb_fragments == fragments);
686 +}
687 +
688 +#else
689 +#define mb_check_buddy(e3b)
690 +#endif
691 +
692 +/* find most significant bit */
693 +static int inline fmsb(unsigned short word)
694 +{
695 +       int order;
696 +
697 +       if (word > 255) {
698 +               order = 7;
699 +               word >>= 8;
700 +       } else {
701 +               order = -1;
702 +       }
703 +
704 +       do {
705 +               order++;
706 +               word >>= 1;
707 +       } while (word != 0);
708 +
709 +       return order;
710 +}
711 +
712 +static void inline
713 +ext3_mb_mark_free_simple(struct super_block *sb, void *buddy, unsigned first,
714 +                               int len, struct ext3_group_info *grp)
715 +{
716 +       struct ext3_sb_info *sbi = EXT3_SB(sb);
717 +       unsigned short min, max, chunk, border;
718 +
719 +       mb_debug("mark %u/%u free\n", first, len);
720 +       J_ASSERT(len < EXT3_BLOCKS_PER_GROUP(sb));
721 +
722 +       border = 2 << sb->s_blocksize_bits;
723 +
724 +       while (len > 0) {
725 +               /* find how many blocks can be covered since this position */
726 +               max = ffs(first | border) - 1;
727 +
728 +               /* find how many blocks of power 2 we need to mark */
729 +               min = fmsb(len);
730 +
731 +               mb_debug("  %u/%u -> max %u, min %u\n",
732 +                       first & ((2 << sb->s_blocksize_bits) - 1),
733 +                       len, max, min);
734 +
735 +               if (max < min)
736 +                       min = max;
737 +               chunk = 1 << min;
738 +
739 +               /* mark multiblock chunks only */
740 +               grp->bb_counters[min]++;
741 +               if (min > 0) {
742 +                       mb_debug("    set %u at %u \n", first >> min,
743 +                               sbi->s_mb_offsets[min]);
744 +                       mb_clear_bit(first >> min, buddy + sbi->s_mb_offsets[min]);
745 +               }
746 +
747 +               len -= chunk;
748 +               first += chunk;
749 +       }
750 +}
751 +
752 +static void
753 +ext3_mb_generate_buddy(struct super_block *sb, void *buddy, void *bitmap,
754 +                       struct ext3_group_info *grp)
755 +{
756 +       unsigned short max = EXT3_BLOCKS_PER_GROUP(sb);
757 +       unsigned short i = 0, first, len;
758 +       unsigned free = 0, fragments = 0;
759 +       unsigned long long period = get_cycles();
760 +
761 +       i = mb_find_next_zero_bit(bitmap, max, 0);
762 +       grp->bb_first_free = i;
763 +       while (i < max) {
764 +               fragments++;
765 +               first = i;
766 +               i = find_next_bit(bitmap, max, i);
767 +               len = i - first;
768 +               free += len;
769 +               if (len > 1) 
770 +                       ext3_mb_mark_free_simple(sb, buddy, first, len, grp);
771 +               else
772 +                       grp->bb_counters[0]++;
773 +               if (i < max)
774 +                       i = mb_find_next_zero_bit(bitmap, max, i);
775 +       }
776 +       grp->bb_fragments = fragments;
777 +
778 +       /* bb_state shouldn't being modified because all
779 +        * others waits for init completion on page lock */
780 +       clear_bit(EXT3_GROUP_INFO_NEED_INIT_BIT, &grp->bb_state);
781 +       if (free != grp->bb_free) {
782 +               printk("EXT3-fs: %u blocks in bitmap, %u in group descriptor\n",
783 +                       free, grp->bb_free);
784 +               grp->bb_free = free;
785 +       }
786 +
787 +       period = get_cycles() - period;
788 +       spin_lock(&EXT3_SB(sb)->s_bal_lock);
789 +       EXT3_SB(sb)->s_mb_buddies_generated++;
790 +       EXT3_SB(sb)->s_mb_generation_time += period;
791 +       spin_unlock(&EXT3_SB(sb)->s_bal_lock);
792 +}
793 +
794 +static int ext3_mb_init_cache(struct page *page)
795 +{
796 +       int blocksize, blocks_per_page, groups_per_page;
797 +       int err = 0, i, first_group, first_block;
798 +       struct super_block *sb;
799 +       struct buffer_head *bhs;
800 +       struct buffer_head **bh;
801 +       struct inode *inode;
802 +       char *data, *bitmap;
803 +
804 +       mb_debug("init page %lu\n", page->index);
805 +
806 +       inode = page->mapping->host;
807 +       sb = inode->i_sb;
808 +       blocksize = 1 << inode->i_blkbits;
809 +       blocks_per_page = PAGE_CACHE_SIZE / blocksize;
810 +       
811 +       groups_per_page = blocks_per_page >> 1;
812 +       if (groups_per_page == 0)
813 +               groups_per_page = 1;
814 +
815 +       /* allocate buffer_heads to read bitmaps */
816 +       if (groups_per_page > 1) {
817 +               err = -ENOMEM;
818 +               i = sizeof(struct buffer_head *) * groups_per_page;
819 +               bh = kmalloc(i, GFP_NOFS);
820 +               if (bh == NULL)
821 +                       goto out;
822 +               memset(bh, 0, i);
823 +       } else
824 +               bh = &bhs;
825 +       
826 +       first_group = page->index * blocks_per_page / 2;
827 +       
828 +       /* read all groups the page covers into the cache */
829 +       for (i = 0; i < groups_per_page; i++) {
830 +               struct ext3_group_desc * desc;
831 +
832 +               if (first_group + i >= EXT3_SB(sb)->s_groups_count)
833 +                       break;
834 +
835 +               err = -EIO;
836 +               desc = ext3_get_group_desc(sb, first_group + i, NULL);
837 +               if (desc == NULL)
838 +                       goto out;
839 +
840 +               err = -ENOMEM;
841 +               bh[i] = sb_getblk(sb, le32_to_cpu(desc->bg_block_bitmap));
842 +               if (bh[i] == NULL)
843 +                       goto out;
844 +
845 +               if (buffer_uptodate(bh[i]))
846 +                       continue;
847 +
848 +               lock_buffer(bh[i]);
849 +               if (buffer_uptodate(bh[i])) {
850 +                       unlock_buffer(bh[i]);
851 +                       continue;
852 +               }
853 +
854 +               get_bh(bh[i]);
855 +               bh[i]->b_end_io = end_buffer_read_sync;
856 +               submit_bh(READ, bh[i]);
857 +               mb_debug("read bitmap for group %u\n", first_group + i);
858 +       }
859 +
860 +       /* wait for I/O completion */
861 +       for (i = 0; i < groups_per_page && bh[i]; i++)
862 +               wait_on_buffer(bh[i]);
863 +
864 +       /* XXX: I/O error handling here */
865 +
866 +       first_block = page->index * blocks_per_page;
867 +       for (i = 0; i < blocks_per_page; i++) {
868 +               int group;
869 +
870 +               group = (first_block + i) >> 1;
871 +               if (group >= EXT3_SB(sb)->s_groups_count)
872 +                       break;
873 +
874 +               data = page_address(page) + (i * blocksize);
875 +               bitmap = bh[group - first_group]->b_data;
876 +
877 +               if ((first_block + i) & 1) {
878 +                       /* this is block of buddy */
879 +                       mb_debug("put buddy for group %u in page %lu/%x\n",
880 +                               group, page->index, i * blocksize);
881 +                       memset(data, 0xff, blocksize);
882 +                       EXT3_SB(sb)->s_group_info[group]->bb_fragments = 0;
883 +                       memset(EXT3_SB(sb)->s_group_info[group]->bb_counters, 0,
884 +                               sizeof(unsigned short)*(sb->s_blocksize_bits+2));
885 +                       ext3_mb_generate_buddy(sb, data, bitmap,
886 +                                               EXT3_SB(sb)->s_group_info[group]);
887 +               } else {
888 +                       /* this is block of bitmap */
889 +                       mb_debug("put bitmap for group %u in page %lu/%x\n",
890 +                               group, page->index, i * blocksize);
891 +                       memcpy(data, bitmap, blocksize);
892 +               }
893 +       }
894 +       SetPageUptodate(page);
895 +
896 +out:
897 +       if (bh) {
898 +               for (i = 0; bh && i < groups_per_page && bh[i]; i++)
899 +                       brelse(bh[i]);
900 +               if (bh != &bhs)
901 +                       kfree(bh);
902 +       }
903 +       return err;
904 +}
905 +
906 +static int ext3_mb_load_buddy(struct super_block *sb, int group,
907 +               struct ext3_buddy *e3b)
908 +{
909 +       struct ext3_sb_info *sbi = EXT3_SB(sb);
910 +       struct inode *inode = sbi->s_buddy_cache;
911 +       int blocks_per_page, block, pnum, poff;
912 +       struct page *page;
913 +
914 +       mb_debug("load group %u\n", group);
915 +
916 +       blocks_per_page = PAGE_CACHE_SIZE / sb->s_blocksize;
917 +
918 +       e3b->bd_blkbits = sb->s_blocksize_bits;
919 +       e3b->bd_info = sbi->s_group_info[group];
920 +       e3b->bd_sb = sb;
921 +       e3b->bd_group = group;
922 +       e3b->bd_buddy_page = NULL;
923 +       e3b->bd_bitmap_page = NULL;
924 +
925 +       block = group * 2;
926 +       pnum = block / blocks_per_page;
927 +       poff = block % blocks_per_page;
928 +
929 +       page = find_get_page(inode->i_mapping, pnum);
930 +       if (page == NULL || !PageUptodate(page)) {
931 +               if (page)
932 +                       page_cache_release(page);
933 +               page = find_or_create_page(inode->i_mapping, pnum, GFP_NOFS);
934 +               if (page) {
935 +                       if (!PageUptodate(page))
936 +                               ext3_mb_init_cache(page);
937 +                       unlock_page(page);
938 +               }
939 +       }
940 +       if (page == NULL || !PageUptodate(page))
941 +               goto err;
942 +       e3b->bd_bitmap_page = page;
943 +       e3b->bd_bitmap = page_address(page) + (poff * sb->s_blocksize);
944 +       mark_page_accessed(page);
945 +
946 +       block++;
947 +       pnum = block / blocks_per_page;
948 +       poff = block % blocks_per_page;
949 +
950 +       page = find_get_page(inode->i_mapping, pnum);
951 +       if (page == NULL || !PageUptodate(page)) {
952 +               if (page)
953 +                       page_cache_release(page);
954 +               page = find_or_create_page(inode->i_mapping, pnum, GFP_NOFS);
955 +               if (page) {
956 +                       if (!PageUptodate(page))
957 +                               ext3_mb_init_cache(page);
958 +                       unlock_page(page);
959 +               }
960 +       }
961 +       if (page == NULL || !PageUptodate(page))
962 +               goto err;
963 +       e3b->bd_buddy_page = page;
964 +       e3b->bd_buddy = page_address(page) + (poff * sb->s_blocksize);
965 +       mark_page_accessed(page);
966 +
967 +       J_ASSERT(e3b->bd_bitmap_page != NULL);
968 +       J_ASSERT(e3b->bd_buddy_page != NULL);
969 +
970 +       return 0;
971 +
972 +err:
973 +       if (e3b->bd_bitmap_page)
974 +               page_cache_release(e3b->bd_bitmap_page);
975 +       if (e3b->bd_buddy_page)
976 +               page_cache_release(e3b->bd_buddy_page);
977 +       e3b->bd_buddy = NULL;
978 +       e3b->bd_bitmap = NULL;
979 +       return -EIO;
980 +}
981 +
982 +static void ext3_mb_release_desc(struct ext3_buddy *e3b)
983 +{
984 +       if (e3b->bd_bitmap_page)
985 +               page_cache_release(e3b->bd_bitmap_page);
986 +       if (e3b->bd_buddy_page)
987 +               page_cache_release(e3b->bd_buddy_page);
988 +}
989 +
990 +
991 +static inline void
992 +ext3_lock_group(struct super_block *sb, int group)
993 +{
994 +       bit_spin_lock(EXT3_GROUP_INFO_LOCKED_BIT,
995 +                       &EXT3_SB(sb)->s_group_info[group]->bb_state);
996 +}
997 +
998 +static inline void
999 +ext3_unlock_group(struct super_block *sb, int group)
1000 +{
1001 +       bit_spin_unlock(EXT3_GROUP_INFO_LOCKED_BIT,
1002 +                       &EXT3_SB(sb)->s_group_info[group]->bb_state);
1003 +}
1004 +
1005 +static int mb_find_order_for_block(struct ext3_buddy *e3b, int block)
1006 +{
1007 +       int order = 1;
1008 +       void *bb;
1009 +
1010 +       J_ASSERT(EXT3_MB_BITMAP(e3b) != EXT3_MB_BUDDY(e3b));
1011 +       J_ASSERT(block < (1 << (e3b->bd_blkbits + 3)));
1012 +
1013 +       bb = EXT3_MB_BUDDY(e3b);
1014 +       while (order <= e3b->bd_blkbits + 1) {
1015 +               block = block >> 1;
1016 +               if (!mb_test_bit(block, bb)) {
1017 +                       /* this block is part of buddy of order 'order' */
1018 +                       return order;
1019 +               }
1020 +               bb += 1 << (e3b->bd_blkbits - order);
1021 +               order++;
1022 +       }
1023 +       return 0;
1024 +}
1025 +
1026 +static inline void mb_clear_bits(void *bm, int cur, int len)
1027 +{
1028 +       __u32 *addr;
1029 +
1030 +       len = cur + len;
1031 +       while (cur < len) {
1032 +               if ((cur & 31) == 0 && (len - cur) >= 32) {
1033 +                       /* fast path: clear whole word at once */
1034 +                       addr = bm + (cur >> 3);
1035 +                       *addr = 0;
1036 +                       cur += 32;
1037 +                       continue;
1038 +               }
1039 +               mb_clear_bit_atomic(cur, bm);
1040 +               cur++;
1041 +       }
1042 +}
1043 +
1044 +static inline void mb_set_bits(void *bm, int cur, int len)
1045 +{
1046 +       __u32 *addr;
1047 +
1048 +       len = cur + len;
1049 +       while (cur < len) {
1050 +               if ((cur & 31) == 0 && (len - cur) >= 32) {
1051 +                       /* fast path: clear whole word at once */
1052 +                       addr = bm + (cur >> 3);
1053 +                       *addr = 0xffffffff;
1054 +                       cur += 32;
1055 +                       continue;
1056 +               }
1057 +               mb_set_bit_atomic(cur, bm);
1058 +               cur++;
1059 +       }
1060 +}
1061 +
1062 +static int mb_free_blocks(struct ext3_buddy *e3b, int first, int count)
1063 +{
1064 +       int block = 0, max = 0, order;
1065 +       void *buddy, *buddy2;
1066 +
1067 +       mb_check_buddy(e3b);
1068 +
1069 +       e3b->bd_info->bb_free += count;
1070 +       if (first < e3b->bd_info->bb_first_free)
1071 +               e3b->bd_info->bb_first_free = first;
1072 +
1073 +       /* let's maintain fragments counter */
1074 +       if (first != 0)
1075 +               block = !mb_test_bit(first - 1, EXT3_MB_BITMAP(e3b));
1076 +       if (first + count < EXT3_SB(e3b->bd_sb)->s_mb_maxs[0])
1077 +               max = !mb_test_bit(first + count, EXT3_MB_BITMAP(e3b));
1078 +       if (block && max)
1079 +               e3b->bd_info->bb_fragments--;
1080 +       else if (!block && !max)
1081 +               e3b->bd_info->bb_fragments++;
1082 +
1083 +       /* let's maintain buddy itself */
1084 +       while (count-- > 0) {
1085 +               block = first++;
1086 +               order = 0;
1087 +
1088 +               J_ASSERT(mb_test_bit(block, EXT3_MB_BITMAP(e3b)));
1089 +               mb_clear_bit(block, EXT3_MB_BITMAP(e3b));
1090 +               e3b->bd_info->bb_counters[order]++;
1091 +
1092 +               /* start of the buddy */
1093 +               buddy = mb_find_buddy(e3b, order, &max);
1094 +
1095 +               do {
1096 +                       block &= ~1UL;
1097 +                       if (mb_test_bit(block, buddy) ||
1098 +                                       mb_test_bit(block + 1, buddy))
1099 +                               break;
1100 +
1101 +                       /* both the buddies are free, try to coalesce them */
1102 +                       buddy2 = mb_find_buddy(e3b, order + 1, &max);
1103 +
1104 +                       if (!buddy2)
1105 +                               break;
1106 +
1107 +                       if (order > 0) {
1108 +                               /* for special purposes, we don't set
1109 +                                * free bits in bitmap */
1110 +                               mb_set_bit(block, buddy);
1111 +                               mb_set_bit(block + 1, buddy);
1112 +                       }
1113 +                       e3b->bd_info->bb_counters[order]--;
1114 +                       e3b->bd_info->bb_counters[order]--;
1115 +
1116 +                       block = block >> 1;
1117 +                       order++;
1118 +                       e3b->bd_info->bb_counters[order]++;
1119 +
1120 +                       mb_clear_bit(block, buddy2);
1121 +                       buddy = buddy2;
1122 +               } while (1);
1123 +       }
1124 +       mb_check_buddy(e3b);
1125 +
1126 +       return 0;
1127 +}
1128 +
1129 +static int mb_find_extent(struct ext3_buddy *e3b, int order, int block,
1130 +                               int needed, struct ext3_free_extent *ex)
1131 +{
1132 +       int next, max, ord;
1133 +       void *buddy;
1134 +
1135 +       J_ASSERT(ex != NULL);
1136 +
1137 +       buddy = mb_find_buddy(e3b, order, &max);
1138 +       J_ASSERT(buddy);
1139 +       J_ASSERT(block < max);
1140 +       if (mb_test_bit(block, buddy)) {
1141 +               ex->fe_len = 0;
1142 +               ex->fe_start = 0;
1143 +               ex->fe_group = 0;
1144 +               return 0;
1145 +       }
1146 +
1147 +       if (likely(order == 0)) {
1148 +               /* find actual order */
1149 +               order = mb_find_order_for_block(e3b, block);
1150 +               block = block >> order;
1151 +       }
1152 +
1153 +       ex->fe_len = 1 << order;
1154 +       ex->fe_start = block << order;
1155 +       ex->fe_group = e3b->bd_group;
1156 +
1157 +       while (needed > ex->fe_len && (buddy = mb_find_buddy(e3b, order, &max))) {
1158 +
1159 +               if (block + 1 >= max)
1160 +                       break;
1161 +
1162 +               next = (block + 1) * (1 << order);
1163 +               if (mb_test_bit(next, EXT3_MB_BITMAP(e3b)))
1164 +                       break;
1165 +
1166 +               ord = mb_find_order_for_block(e3b, next);
1167 +
1168 +               order = ord;
1169 +               block = next >> order;
1170 +               ex->fe_len += 1 << order;
1171 +       }
1172 +
1173 +       J_ASSERT(ex->fe_start + ex->fe_len <= (1 << (e3b->bd_blkbits + 3)));
1174 +       return ex->fe_len;
1175 +}
1176 +
1177 +static int mb_mark_used(struct ext3_buddy *e3b, struct ext3_free_extent *ex)
1178 +{
1179 +       int ord, mlen = 0, max = 0, cur;
1180 +       int start = ex->fe_start;
1181 +       int len = ex->fe_len;
1182 +       unsigned ret = 0;
1183 +       int len0 = len;
1184 +       void *buddy;
1185 +
1186 +       mb_check_buddy(e3b);
1187 +
1188 +       e3b->bd_info->bb_free -= len;
1189 +       if (e3b->bd_info->bb_first_free == start)
1190 +               e3b->bd_info->bb_first_free += len;
1191 +
1192 +       /* let's maintain fragments counter */
1193 +       if (start != 0)
1194 +               mlen = !mb_test_bit(start - 1, EXT3_MB_BITMAP(e3b));
1195 +       if (start + len < EXT3_SB(e3b->bd_sb)->s_mb_maxs[0])
1196 +               max = !mb_test_bit(start + len, EXT3_MB_BITMAP(e3b));
1197 +       if (mlen && max)
1198 +               e3b->bd_info->bb_fragments++;
1199 +       else if (!mlen && !max)
1200 +               e3b->bd_info->bb_fragments--;
1201 +
1202 +       /* let's maintain buddy itself */
1203 +       while (len) {
1204 +               ord = mb_find_order_for_block(e3b, start);
1205 +
1206 +               if (((start >> ord) << ord) == start && len >= (1 << ord)) {
1207 +                       /* the whole chunk may be allocated at once! */
1208 +                       mlen = 1 << ord;
1209 +                       buddy = mb_find_buddy(e3b, ord, &max);
1210 +                       J_ASSERT((start >> ord) < max);
1211 +                       mb_set_bit(start >> ord, buddy);
1212 +                       e3b->bd_info->bb_counters[ord]--;
1213 +                       start += mlen;
1214 +                       len -= mlen;
1215 +                       J_ASSERT(len >= 0);
1216 +                       continue;
1217 +               }
1218 +
1219 +               /* store for history */
1220 +               if (ret == 0)
1221 +                       ret = len | (ord << 16);
1222 +
1223 +               /* we have to split large buddy */
1224 +               J_ASSERT(ord > 0);
1225 +               buddy = mb_find_buddy(e3b, ord, &max);
1226 +               mb_set_bit(start >> ord, buddy);
1227 +               e3b->bd_info->bb_counters[ord]--;
1228 +
1229 +               ord--;
1230 +               cur = (start >> ord) & ~1U;
1231 +               buddy = mb_find_buddy(e3b, ord, &max);
1232 +               mb_clear_bit(cur, buddy);
1233 +               mb_clear_bit(cur + 1, buddy);
1234 +               e3b->bd_info->bb_counters[ord]++;
1235 +               e3b->bd_info->bb_counters[ord]++;
1236 +       }
1237 +
1238 +       /* now drop all the bits in bitmap */
1239 +       mb_set_bits(EXT3_MB_BITMAP(e3b), ex->fe_start, len0);
1240 +
1241 +       mb_check_buddy(e3b);
1242 +
1243 +       return ret;
1244 +}
1245 +
1246 +/*
1247 + * Must be called under group lock!
1248 + */
1249 +static void ext3_mb_use_best_found(struct ext3_allocation_context *ac,
1250 +                                       struct ext3_buddy *e3b)
1251 +{
1252 +       unsigned long ret;
1253 +
1254 +       ac->ac_b_ex.fe_len = min(ac->ac_b_ex.fe_len, ac->ac_g_ex.fe_len);
1255 +       ret = mb_mark_used(e3b, &ac->ac_b_ex);
1256 +
1257 +       ac->ac_status = AC_STATUS_FOUND;
1258 +       ac->ac_tail = ret & 0xffff;
1259 +       ac->ac_buddy = ret >> 16;
1260 +}
1261 +
1262 +/*
1263 + * The routine checks whether found extent is good enough. If it is,
1264 + * then the extent gets marked used and flag is set to the context
1265 + * to stop scanning. Otherwise, the extent is compared with the
1266 + * previous found extent and if new one is better, then it's stored
1267 + * in the context. Later, the best found extent will be used, if
1268 + * mballoc can't find good enough extent.
1269 + *
1270 + * FIXME: real allocation policy is to be designed yet!
1271 + */
1272 +static void ext3_mb_measure_extent(struct ext3_allocation_context *ac,
1273 +                                       struct ext3_free_extent *ex,
1274 +                                       struct ext3_buddy *e3b)
1275 +{
1276 +       struct ext3_free_extent *bex = &ac->ac_b_ex;
1277 +       struct ext3_free_extent *gex = &ac->ac_g_ex;
1278 +
1279 +       J_ASSERT(ex->fe_len > 0);
1280 +       J_ASSERT(ex->fe_len < (1 << ac->ac_sb->s_blocksize_bits) * 8);
1281 +       J_ASSERT(ex->fe_start < (1 << ac->ac_sb->s_blocksize_bits) * 8);
1282 +
1283 +       ac->ac_found++;
1284 +
1285 +       /*
1286 +        * The special case - take what you catch first
1287 +        */
1288 +       if (unlikely(ac->ac_flags & EXT3_MB_HINT_FIRST)) {
1289 +               *bex = *ex;
1290 +               ext3_mb_use_best_found(ac, e3b);
1291 +               return;
1292 +       }
1293 +
1294 +       /*
1295 +        * Let's check whether the chuck is good enough
1296 +        */
1297 +       if (ex->fe_len == gex->fe_len) {
1298 +               *bex = *ex;
1299 +               ext3_mb_use_best_found(ac, e3b);
1300 +               return;
1301 +       }
1302 +
1303 +       /*
1304 +        * If this is first found extent, just store it in the context
1305 +        */
1306 +       if (bex->fe_len == 0) {
1307 +               *bex = *ex;
1308 +               return;
1309 +       }
1310 +
1311 +       /*
1312 +        * If new found extent is better, store it in the context
1313 +        */
1314 +       if (bex->fe_len < gex->fe_len) {
1315 +               /* if the request isn't satisfied, any found extent
1316 +                * larger than previous best one is better */
1317 +               if (ex->fe_len > bex->fe_len)
1318 +                       *bex = *ex;
1319 +       } else if (ex->fe_len > gex->fe_len) {
1320 +               /* if the request is satisfied, then we try to find
1321 +                * an extent that still satisfy the request, but is
1322 +                * smaller than previous one */
1323 +               *bex = *ex;
1324 +       }
1325 +
1326 +       /*
1327 +        * Let's scan at least few extents and don't pick up a first one
1328 +        */
1329 +       if (bex->fe_len > gex->fe_len && ac->ac_found > ext3_mb_min_to_scan)
1330 +               ac->ac_status = AC_STATUS_BREAK;
1331 +
1332 +       /*
1333 +        * We don't want to scan for a whole year
1334 +        */
1335 +       if (ac->ac_found > ext3_mb_max_to_scan)
1336 +               ac->ac_status = AC_STATUS_BREAK;
1337 +}
1338 +
1339 +static int ext3_mb_try_best_found(struct ext3_allocation_context *ac,
1340 +                                       struct ext3_buddy *e3b)
1341 +{
1342 +       struct ext3_free_extent ex = ac->ac_b_ex;
1343 +       int group = ex.fe_group, max, err;
1344 +
1345 +       J_ASSERT(ex.fe_len > 0);
1346 +       err = ext3_mb_load_buddy(ac->ac_sb, group, e3b);
1347 +       if (err)
1348 +               return err;
1349 +
1350 +       ext3_lock_group(ac->ac_sb, group);
1351 +       max = mb_find_extent(e3b, 0, ex.fe_start, ex.fe_len, &ex);
1352 +       
1353 +       if (max > 0) {
1354 +               ac->ac_b_ex = ex;
1355 +               ext3_mb_use_best_found(ac, e3b);
1356 +       }
1357 +
1358 +       ext3_unlock_group(ac->ac_sb, group);
1359 +
1360 +       ext3_mb_release_desc(e3b);
1361 +
1362 +       return 0;
1363 +}
1364 +
1365 +static int ext3_mb_find_by_goal(struct ext3_allocation_context *ac,
1366 +                               struct ext3_buddy *e3b)
1367 +{
1368 +       int group = ac->ac_g_ex.fe_group, max, err;
1369 +       struct ext3_free_extent ex;
1370 +
1371 +       err = ext3_mb_load_buddy(ac->ac_sb, group, e3b);
1372 +       if (err)
1373 +               return err;
1374 +
1375 +       ext3_lock_group(ac->ac_sb, group);
1376 +       max = mb_find_extent(e3b, 0, ac->ac_g_ex.fe_start,
1377 +                               ac->ac_g_ex.fe_len, &ex);
1378 +       
1379 +       if (max > 0) {
1380 +               J_ASSERT(ex.fe_len > 0);
1381 +               J_ASSERT(ex.fe_group == ac->ac_g_ex.fe_group);
1382 +               J_ASSERT(ex.fe_start == ac->ac_g_ex.fe_start);
1383 +               ac->ac_found++;
1384 +               ac->ac_b_ex = ex;
1385 +               ext3_mb_use_best_found(ac, e3b);
1386 +       }
1387 +       ext3_unlock_group(ac->ac_sb, group);
1388 +
1389 +       ext3_mb_release_desc(e3b);
1390 +
1391 +       return 0;
1392 +}
1393 +
1394 +/*
1395 + * The routine scans buddy structures (not bitmap!) from given order
1396 + * to max order and tries to find big enough chunk to satisfy the req
1397 + */
1398 +static void ext3_mb_simple_scan_group(struct ext3_allocation_context *ac,
1399 +                                       struct ext3_buddy *e3b)
1400 +{
1401 +       struct super_block *sb = ac->ac_sb;
1402 +       struct ext3_group_info *grp = e3b->bd_info;
1403 +       void *buddy;
1404 +       int i, k, max;
1405 +
1406 +       J_ASSERT(ac->ac_2order > 0);
1407 +       for (i = ac->ac_2order; i < sb->s_blocksize_bits + 1; i++) {
1408 +               if (grp->bb_counters[i] == 0)
1409 +                       continue;
1410 +
1411 +               buddy = mb_find_buddy(e3b, i, &max);
1412 +               if (buddy == NULL) {
1413 +                       printk(KERN_ALERT "looking for wrong order?\n");
1414 +                       break;
1415 +               }
1416 +
1417 +               k = mb_find_next_zero_bit(buddy, max, 0);
1418 +               J_ASSERT(k < max);
1419 +
1420 +               ac->ac_found++;
1421 +
1422 +               ac->ac_b_ex.fe_len = 1 << i;
1423 +               ac->ac_b_ex.fe_start = k << i;
1424 +               ac->ac_b_ex.fe_group = e3b->bd_group;
1425 +               
1426 +               ext3_mb_use_best_found(ac, e3b);
1427 +               J_ASSERT(ac->ac_b_ex.fe_len == ac->ac_g_ex.fe_len);
1428 +
1429 +               if (unlikely(ext3_mb_stats))
1430 +                       atomic_inc(&EXT3_SB(sb)->s_bal_2orders);
1431 +
1432 +               break;
1433 +       }
1434 +}
1435 +
1436 +/*
1437 + * The routine scans the group and measures all found extents.
1438 + * In order to optimize scanning, caller must pass number of
1439 + * free blocks in the group, so the routine can know upper limit.
1440 + */
1441 +static void ext3_mb_complex_scan_group(struct ext3_allocation_context *ac,
1442 +                                       struct ext3_buddy *e3b)
1443 +{
1444 +       struct super_block *sb = ac->ac_sb;
1445 +       void *bitmap = EXT3_MB_BITMAP(e3b);
1446 +       struct ext3_free_extent ex;
1447 +       int i, free;
1448 +
1449 +       free = e3b->bd_info->bb_free;
1450 +       J_ASSERT(free > 0);
1451 +
1452 +       i = e3b->bd_info->bb_first_free;
1453 +
1454 +       while (free && ac->ac_status == AC_STATUS_CONTINUE) {
1455 +               i = mb_find_next_zero_bit(bitmap, sb->s_blocksize * 8, i);
1456 +               if (i >= sb->s_blocksize * 8) {
1457 +                       J_ASSERT(free == 0);
1458 +                       break;
1459 +               }
1460 +
1461 +               mb_find_extent(e3b, 0, i, ac->ac_g_ex.fe_len, &ex);
1462 +               J_ASSERT(ex.fe_len > 0);
1463 +               J_ASSERT(free >= ex.fe_len);
1464 +
1465 +               ext3_mb_measure_extent(ac, &ex, e3b);
1466 +
1467 +               i += ex.fe_len;
1468 +               free -= ex.fe_len;
1469 +       }
1470 +}
1471 +
1472 +static int ext3_mb_good_group(struct ext3_allocation_context *ac,
1473 +                               int group, int cr)
1474 +{
1475 +       struct ext3_sb_info *sbi = EXT3_SB(ac->ac_sb);
1476 +       struct ext3_group_info *grp = sbi->s_group_info[group];
1477 +       unsigned free, fragments, i, bits;
1478 +
1479 +       J_ASSERT(cr >= 0 && cr < 4);
1480 +       J_ASSERT(!EXT3_MB_GRP_NEED_INIT(grp));
1481 +
1482 +       free = grp->bb_free;
1483 +       fragments = grp->bb_fragments;
1484 +       if (free == 0)
1485 +               return 0;
1486 +       if (fragments == 0)
1487 +               return 0;
1488 +
1489 +       switch (cr) {
1490 +               case 0:
1491 +                       J_ASSERT(ac->ac_2order != 0);
1492 +                       bits = ac->ac_sb->s_blocksize_bits + 1;
1493 +                       for (i = ac->ac_2order; i < bits; i++)
1494 +                               if (grp->bb_counters[i] > 0)
1495 +                                       return 1;
1496 +               case 1:
1497 +                       if ((free / fragments) >= ac->ac_g_ex.fe_len)
1498 +                               return 1;
1499 +               case 2:
1500 +                       if (free >= ac->ac_g_ex.fe_len)
1501 +                               return 1;
1502 +               case 3:
1503 +                       return 1;
1504 +               default:
1505 +                       BUG();
1506 +       }
1507 +
1508 +       return 0;
1509 +}
1510 +
1511 +int ext3_mb_new_blocks(handle_t *handle, struct inode *inode,
1512 +                      unsigned long goal, int *len, int flags, int *errp)
1513 +{
1514 +       struct buffer_head *bitmap_bh = NULL;
1515 +       struct ext3_allocation_context ac;
1516 +       int i, group, block, cr, err = 0;
1517 +       struct ext3_group_desc *gdp;
1518 +       struct ext3_super_block *es;
1519 +       struct buffer_head *gdp_bh;
1520 +       struct ext3_sb_info *sbi;
1521 +       struct super_block *sb;
1522 +       struct ext3_buddy e3b;
1523 +
1524 +       J_ASSERT(len != NULL);
1525 +       J_ASSERT(*len > 0);
1526 +
1527 +       sb = inode->i_sb;
1528 +       if (!sb) {
1529 +               printk("ext3_mb_new_nblocks: nonexistent device");
1530 +               return 0;
1531 +       }
1532 +
1533 +       if (!test_opt(sb, MBALLOC)) {
1534 +               static int ext3_mballoc_warning = 0;
1535 +               if (ext3_mballoc_warning == 0) {
1536 +                       printk(KERN_ERR "EXT3-fs: multiblock request with "
1537 +                               "mballoc disabled!\n");
1538 +                       ext3_mballoc_warning++;
1539 +               }
1540 +               *len = 1;
1541 +               err = ext3_new_block_old(handle, inode, goal, errp);
1542 +               return err;
1543 +       }
1544 +
1545 +       ext3_mb_poll_new_transaction(sb, handle);
1546 +
1547 +       sbi = EXT3_SB(sb);
1548 +       es = EXT3_SB(sb)->s_es;
1549 +
1550 +       /*
1551 +        * We can't allocate > group size
1552 +        */
1553 +       if (*len >= EXT3_BLOCKS_PER_GROUP(sb) - 10)
1554 +               *len = EXT3_BLOCKS_PER_GROUP(sb) - 10;
1555 +
1556 +       if (!(flags & EXT3_MB_HINT_RESERVED)) {
1557 +               /* someone asks for non-reserved blocks */
1558 +               BUG_ON(*len > 1);
1559 +               err = ext3_mb_reserve_blocks(sb, 1);
1560 +               if (err) {
1561 +                       *errp = err;
1562 +                       return 0;
1563 +               }
1564 +       }
1565 +
1566 +       /*
1567 +        * Check quota for allocation of this blocks.
1568 +        */
1569 +       while (*len && DQUOT_ALLOC_BLOCK(inode, *len))
1570 +               *len -= 1;
1571 +       if (*len == 0) {
1572 +               *errp = -EDQUOT;
1573 +               block = 0;
1574 +               goto out;
1575 +       }
1576 +
1577 +       /* start searching from the goal */
1578 +       if (goal < le32_to_cpu(es->s_first_data_block) ||
1579 +           goal >= le32_to_cpu(es->s_blocks_count))
1580 +               goal = le32_to_cpu(es->s_first_data_block);
1581 +       group = (goal - le32_to_cpu(es->s_first_data_block)) /
1582 +                       EXT3_BLOCKS_PER_GROUP(sb);
1583 +       block = ((goal - le32_to_cpu(es->s_first_data_block)) %
1584 +                       EXT3_BLOCKS_PER_GROUP(sb));
1585 +
1586 +       /* set up allocation goals */
1587 +       ac.ac_b_ex.fe_group = 0;
1588 +       ac.ac_b_ex.fe_start = 0;
1589 +       ac.ac_b_ex.fe_len = 0;
1590 +       ac.ac_status = AC_STATUS_CONTINUE;
1591 +       ac.ac_groups_scanned = 0;
1592 +       ac.ac_ex_scanned = 0;
1593 +       ac.ac_found = 0;
1594 +       ac.ac_sb = inode->i_sb;
1595 +       ac.ac_g_ex.fe_group = group;
1596 +       ac.ac_g_ex.fe_start = block;
1597 +       ac.ac_g_ex.fe_len = *len;
1598 +       ac.ac_flags = flags;
1599 +       ac.ac_2order = 0;
1600 +       ac.ac_criteria = 0;
1601 +
1602 +       /* probably, the request is for 2^8+ blocks (1/2/3/... MB) */
1603 +       i = ffs(*len);
1604 +       if (i >= 8) {
1605 +               i--;
1606 +               if ((*len & (~(1 << i))) == 0)
1607 +                       ac.ac_2order = i;
1608 +       }
1609 +
1610 +       /* Sometimes, caller may want to merge even small
1611 +        * number of blocks to an existing extent */
1612 +       if (ac.ac_flags & EXT3_MB_HINT_MERGE) {
1613 +               err = ext3_mb_find_by_goal(&ac, &e3b);
1614 +               if (err)
1615 +                       goto out_err;
1616 +               if (ac.ac_status == AC_STATUS_FOUND)
1617 +                       goto found;
1618 +       }
1619 +
1620 +       /* Let's just scan groups to find more-less suitable blocks */
1621 +       cr = ac.ac_2order ? 0 : 1;
1622 +repeat:
1623 +       for (; cr < 4 && ac.ac_status == AC_STATUS_CONTINUE; cr++) {
1624 +               ac.ac_criteria = cr;
1625 +               for (i = 0; i < EXT3_SB(sb)->s_groups_count; group++, i++) {
1626 +                       if (group == EXT3_SB(sb)->s_groups_count)
1627 +                               group = 0;
1628 +
1629 +                       if (EXT3_MB_GRP_NEED_INIT(sbi->s_group_info[group])) {
1630 +                               /* we need full data about the group
1631 +                                * to make a good selection */
1632 +                               err = ext3_mb_load_buddy(ac.ac_sb, group, &e3b);
1633 +                               if (err)
1634 +                                       goto out_err;
1635 +                               ext3_mb_release_desc(&e3b);
1636 +                       }
1637 +                               
1638 +                       /* check is group good for our criteries */
1639 +                       if (!ext3_mb_good_group(&ac, group, cr))
1640 +                               continue;
1641 +
1642 +                       err = ext3_mb_load_buddy(ac.ac_sb, group, &e3b);
1643 +                       if (err)
1644 +                               goto out_err;
1645 +
1646 +                       ext3_lock_group(sb, group);
1647 +                       if (!ext3_mb_good_group(&ac, group, cr)) {
1648 +                               /* someone did allocation from this group */
1649 +                               ext3_unlock_group(sb, group);
1650 +                               ext3_mb_release_desc(&e3b);
1651 +                               continue;
1652 +                       }
1653 +
1654 +                       ac.ac_groups_scanned++;
1655 +                       if (cr == 0)
1656 +                               ext3_mb_simple_scan_group(&ac, &e3b);
1657 +                       else
1658 +                               ext3_mb_complex_scan_group(&ac, &e3b);
1659 +
1660 +                       ext3_unlock_group(sb, group);
1661 +
1662 +                       ext3_mb_release_desc(&e3b);
1663 +
1664 +                       if (ac.ac_status != AC_STATUS_CONTINUE)
1665 +                               break;
1666 +               }
1667 +       }
1668 +
1669 +       if (ac.ac_b_ex.fe_len > 0 && ac.ac_status != AC_STATUS_FOUND &&
1670 +                       !(ac.ac_flags & EXT3_MB_HINT_FIRST)) {
1671 +               /*
1672 +                * We've been searching too long. Let's try to allocate
1673 +                * the best chunk we've found so far
1674 +                */
1675 +
1676 +               /*if (ac.ac_found > ext3_mb_max_to_scan)
1677 +                       printk(KERN_DEBUG "EXT3-fs: too long searching at "
1678 +                               "%u (%d/%d)\n", cr, ac.ac_b_ex.fe_len,
1679 +                               ac.ac_g_ex.fe_len);*/
1680 +               ext3_mb_try_best_found(&ac, &e3b);
1681 +               if (ac.ac_status != AC_STATUS_FOUND) {
1682 +                       /*
1683 +                        * Someone more lucky has already allocated it.
1684 +                        * The only thing we can do is just take first
1685 +                        * found block(s)
1686 +                       printk(KERN_DEBUG "EXT3-fs: someone won our chunk\n");
1687 +                        */
1688 +                       ac.ac_b_ex.fe_group = 0;
1689 +                       ac.ac_b_ex.fe_start = 0;
1690 +                       ac.ac_b_ex.fe_len = 0;
1691 +                       ac.ac_status = AC_STATUS_CONTINUE;
1692 +                       ac.ac_flags |= EXT3_MB_HINT_FIRST;
1693 +                       cr = 3;
1694 +                       goto repeat;
1695 +               }
1696 +       }
1697 +
1698 +       if (ac.ac_status != AC_STATUS_FOUND) {
1699 +               /*
1700 +                * We aren't lucky definitely
1701 +                */
1702 +               DQUOT_FREE_BLOCK(inode, *len);
1703 +               *errp = -ENOSPC;
1704 +               block = 0;
1705 +#if 1
1706 +               printk(KERN_ERR "EXT3-fs: can't allocate: status %d flags %d\n",
1707 +                       ac.ac_status, ac.ac_flags);
1708 +               printk(KERN_ERR "EXT3-fs: goal %d, best found %d/%d/%d cr %d\n",
1709 +                       ac.ac_g_ex.fe_len, ac.ac_b_ex.fe_group,
1710 +                       ac.ac_b_ex.fe_start, ac.ac_b_ex.fe_len, cr);
1711 +               printk(KERN_ERR "EXT3-fs: %lu block reserved, %d found\n",
1712 +                       sbi->s_blocks_reserved, ac.ac_found);
1713 +               printk("EXT3-fs: groups: ");
1714 +               for (i = 0; i < EXT3_SB(sb)->s_groups_count; i++)
1715 +                       printk("%d: %d ", i,
1716 +                               sbi->s_group_info[i]->bb_free);
1717 +               printk("\n");
1718 +#endif
1719 +               goto out;
1720 +       }
1721 +
1722 +found:
1723 +       J_ASSERT(ac.ac_b_ex.fe_len > 0);
1724 +
1725 +       /* good news - free block(s) have been found. now it's time
1726 +        * to mark block(s) in good old journaled bitmap */
1727 +       block = ac.ac_b_ex.fe_group * EXT3_BLOCKS_PER_GROUP(sb)
1728 +                       + ac.ac_b_ex.fe_start
1729 +                       + le32_to_cpu(es->s_first_data_block);
1730 +
1731 +       /* we made a desicion, now mark found blocks in good old
1732 +        * bitmap to be journaled */
1733 +
1734 +       ext3_debug("using block group %d(%d)\n",
1735 +                       ac.ac_b_group.group, gdp->bg_free_blocks_count);
1736 +
1737 +       bitmap_bh = read_block_bitmap(sb, ac.ac_b_ex.fe_group);
1738 +       if (!bitmap_bh) {
1739 +               *errp = -EIO;
1740 +               goto out_err;
1741 +       }
1742 +
1743 +       err = ext3_journal_get_write_access(handle, bitmap_bh);
1744 +       if (err) {
1745 +               *errp = err;
1746 +               goto out_err;
1747 +       }
1748 +
1749 +       gdp = ext3_get_group_desc(sb, ac.ac_b_ex.fe_group, &gdp_bh);
1750 +       if (!gdp) {
1751 +               *errp = -EIO;
1752 +               goto out_err;
1753 +       }
1754 +       
1755 +       err = ext3_journal_get_write_access(handle, gdp_bh);
1756 +       if (err)
1757 +               goto out_err;
1758 +
1759 +       block = ac.ac_b_ex.fe_group * EXT3_BLOCKS_PER_GROUP(sb)
1760 +                       + ac.ac_b_ex.fe_start
1761 +                       + le32_to_cpu(es->s_first_data_block);
1762 +
1763 +       if (block == le32_to_cpu(gdp->bg_block_bitmap) ||
1764 +           block == le32_to_cpu(gdp->bg_inode_bitmap) ||
1765 +           in_range(block, le32_to_cpu(gdp->bg_inode_table),
1766 +                     EXT3_SB(sb)->s_itb_per_group))
1767 +               ext3_error(sb, "ext3_new_block",
1768 +                           "Allocating block in system zone - "
1769 +                           "block = %u", block);
1770 +#ifdef AGGRESSIVE_CHECK
1771 +       for (i = 0; i < ac.ac_b_ex.fe_len; i++)
1772 +               J_ASSERT(!mb_test_bit(ac.ac_b_ex.fe_start + i, bitmap_bh->b_data));
1773 +#endif
1774 +       mb_set_bits(bitmap_bh->b_data, ac.ac_b_ex.fe_start, ac.ac_b_ex.fe_len);
1775 +
1776 +       spin_lock(sb_bgl_lock(sbi, ac.ac_b_ex.fe_group));
1777 +       gdp->bg_free_blocks_count =
1778 +                       cpu_to_le16(le16_to_cpu(gdp->bg_free_blocks_count)
1779 +                                       - ac.ac_b_ex.fe_len);
1780 +       spin_unlock(sb_bgl_lock(sbi, ac.ac_b_ex.fe_group));
1781 +       percpu_counter_mod(&sbi->s_freeblocks_counter, - ac.ac_b_ex.fe_len);
1782 +
1783 +       err = ext3_journal_dirty_metadata(handle, bitmap_bh);
1784 +       if (err)
1785 +               goto out_err;
1786 +       err = ext3_journal_dirty_metadata(handle, gdp_bh);
1787 +       if (err)
1788 +               goto out_err;
1789 +
1790 +       sb->s_dirt = 1;
1791 +       *errp = 0;
1792 +       brelse(bitmap_bh);
1793 +
1794 +       /* drop non-allocated, but dquote'd blocks */
1795 +       J_ASSERT(*len >= ac.ac_b_ex.fe_len);
1796 +       DQUOT_FREE_BLOCK(inode, *len - ac.ac_b_ex.fe_len);
1797 +
1798 +       *len = ac.ac_b_ex.fe_len;
1799 +       J_ASSERT(*len > 0);
1800 +       J_ASSERT(block != 0);
1801 +       goto out;
1802 +
1803 +out_err:
1804 +       /* if we've already allocated something, roll it back */
1805 +       if (ac.ac_status == AC_STATUS_FOUND) {
1806 +               /* FIXME: free blocks here */
1807 +       }
1808 +
1809 +       DQUOT_FREE_BLOCK(inode, *len);
1810 +       brelse(bitmap_bh);
1811 +       *errp = err;
1812 +       block = 0;
1813 +out:
1814 +       if (!(flags & EXT3_MB_HINT_RESERVED)) {
1815 +               /* block wasn't reserved before and we reserved it
1816 +                * at the beginning of allocation. it doesn't matter
1817 +                * whether we allocated anything or we failed: time
1818 +                * to release reservation. NOTE: because I expect
1819 +                * any multiblock request from delayed allocation
1820 +                * path only, here is single block always */
1821 +               ext3_mb_release_blocks(sb, 1);
1822 +       }
1823 +       
1824 +       if (unlikely(ext3_mb_stats) && ac.ac_g_ex.fe_len > 1) {
1825 +               atomic_inc(&sbi->s_bal_reqs);
1826 +               atomic_add(*len, &sbi->s_bal_allocated);
1827 +               if (*len >= ac.ac_g_ex.fe_len)
1828 +                       atomic_inc(&sbi->s_bal_success);
1829 +               atomic_add(ac.ac_found, &sbi->s_bal_ex_scanned);
1830 +               if (ac.ac_g_ex.fe_start == ac.ac_b_ex.fe_start &&
1831 +                               ac.ac_g_ex.fe_group == ac.ac_b_ex.fe_group)
1832 +                       atomic_inc(&sbi->s_bal_goals);
1833 +               if (ac.ac_found > ext3_mb_max_to_scan)
1834 +                       atomic_inc(&sbi->s_bal_breaks);
1835 +       }
1836 +
1837 +       ext3_mb_store_history(sb, &ac);
1838 +
1839 +       return block;
1840 +}
1841 +EXPORT_SYMBOL(ext3_mb_new_blocks);
1842 +
1843 +#ifdef EXT3_MB_HISTORY
1844 +struct ext3_mb_proc_session {
1845 +       struct ext3_mb_history *history;
1846 +       struct super_block *sb;
1847 +       int start;
1848 +       int max;
1849 +};
1850 +
1851 +static void *ext3_mb_history_skip_empty(struct ext3_mb_proc_session *s,
1852 +                                       struct ext3_mb_history *hs,
1853 +                                       int first)
1854 +{
1855 +       if (hs == s->history + s->max)
1856 +               hs = s->history;
1857 +       if (!first && hs == s->history + s->start)
1858 +               return NULL;
1859 +       while (hs->goal.fe_len == 0) {
1860 +               hs++;
1861 +               if (hs == s->history + s->max)
1862 +                       hs = s->history;
1863 +               if (hs == s->history + s->start)
1864 +                       return NULL;
1865 +       }
1866 +       return hs;
1867 +}
1868 +
1869 +static void *ext3_mb_seq_history_start(struct seq_file *seq, loff_t *pos)
1870 +{
1871 +       struct ext3_mb_proc_session *s = seq->private;
1872 +       struct ext3_mb_history *hs;
1873 +       int l = *pos;
1874 +
1875 +       if (l == 0)
1876 +               return SEQ_START_TOKEN;
1877 +       hs = ext3_mb_history_skip_empty(s, s->history + s->start, 1);
1878 +       if (!hs)
1879 +               return NULL;
1880 +       while (--l && (hs = ext3_mb_history_skip_empty(s, ++hs, 0)) != NULL);
1881 +       return hs;
1882 +}
1883 +
1884 +static void *ext3_mb_seq_history_next(struct seq_file *seq, void *v, loff_t *pos)
1885 +{
1886 +       struct ext3_mb_proc_session *s = seq->private;
1887 +       struct ext3_mb_history *hs = v;
1888 +
1889 +       ++*pos;
1890 +       if (v == SEQ_START_TOKEN)
1891 +               return ext3_mb_history_skip_empty(s, s->history + s->start, 1);
1892 +       else
1893 +               return ext3_mb_history_skip_empty(s, ++hs, 0);
1894 +}
1895 +
1896 +static int ext3_mb_seq_history_show(struct seq_file *seq, void *v)
1897 +{
1898 +       struct ext3_mb_history *hs = v;
1899 +       char buf[20], buf2[20];
1900 +
1901 +       if (v == SEQ_START_TOKEN) {
1902 +               seq_printf(seq, "%-17s %-17s %-5s %-5s %-2s %-5s %-5s %-6s\n",
1903 +                        "goal", "result", "found", "grps", "cr", "merge",
1904 +                        "tail", "broken");
1905 +               return 0;
1906 +       }
1907 +
1908 +       sprintf(buf, "%u/%u/%u", hs->goal.fe_group,
1909 +               hs->goal.fe_start, hs->goal.fe_len);
1910 +       sprintf(buf2, "%u/%u/%u", hs->result.fe_group,
1911 +               hs->result.fe_start, hs->result.fe_len);
1912 +       seq_printf(seq, "%-17s %-17s %-5u %-5u %-2u %-5s %-5u %-6u\n", buf,
1913 +                       buf2, hs->found, hs->groups, hs->cr, 
1914 +                       hs->merged ? "M" : "", hs->tail,
1915 +                       hs->buddy ? 1 << hs->buddy : 0);
1916 +       return 0;
1917 +}
1918 +
1919 +static void ext3_mb_seq_history_stop(struct seq_file *seq, void *v)
1920 +{
1921 +}
1922 +
1923 +static struct seq_operations ext3_mb_seq_history_ops = {
1924 +       .start  = ext3_mb_seq_history_start,
1925 +       .next   = ext3_mb_seq_history_next,
1926 +       .stop   = ext3_mb_seq_history_stop,
1927 +       .show   = ext3_mb_seq_history_show,
1928 +};
1929 +
1930 +static int ext3_mb_seq_history_open(struct inode *inode, struct file *file)
1931 +{
1932 +       struct super_block *sb = PDE(inode)->data;
1933 +       struct ext3_sb_info *sbi = EXT3_SB(sb);
1934 +       struct ext3_mb_proc_session *s;
1935 +       int rc, size;
1936 +
1937 +       s = kmalloc(sizeof(*s), GFP_KERNEL);
1938 +       if (s == NULL)
1939 +               return -EIO;
1940 +       size = sizeof(struct ext3_mb_history) * sbi->s_mb_history_max;
1941 +       s->history = kmalloc(size, GFP_KERNEL);
1942 +
1943 +       spin_lock(&sbi->s_mb_history_lock);
1944 +       memcpy(s->history, sbi->s_mb_history, size);
1945 +       s->max = sbi->s_mb_history_max;
1946 +       s->start = sbi->s_mb_history_cur % s->max;
1947 +       spin_unlock(&sbi->s_mb_history_lock);
1948 +       
1949 +       rc = seq_open(file, &ext3_mb_seq_history_ops);
1950 +       if (rc == 0) {
1951 +               struct seq_file *m = (struct seq_file *)file->private_data;
1952 +               m->private = s;
1953 +       } else {
1954 +               kfree(s->history);
1955 +               kfree(s);
1956 +       }
1957 +       return rc;
1958 +
1959 +}
1960 +
1961 +static int ext3_mb_seq_history_release(struct inode *inode, struct file *file)
1962 +{
1963 +       struct seq_file *seq = (struct seq_file *)file->private_data;
1964 +       struct ext3_mb_proc_session *s = seq->private;
1965 +       kfree(s->history);
1966 +       kfree(s);
1967 +       return seq_release(inode, file);
1968 +}
1969 +
1970 +static struct file_operations ext3_mb_seq_history_fops = {
1971 +       .owner          = THIS_MODULE,
1972 +       .open           = ext3_mb_seq_history_open,
1973 +       .read           = seq_read,
1974 +       .llseek         = seq_lseek,
1975 +       .release        = ext3_mb_seq_history_release,
1976 +};
1977 +
1978 +static void ext3_mb_history_release(struct super_block *sb)
1979 +{
1980 +       struct ext3_sb_info *sbi = EXT3_SB(sb);
1981 +       char name[64];
1982 +
1983 +       snprintf(name, sizeof(name) - 1, "%s", bdevname(sb->s_bdev, name));
1984 +       remove_proc_entry("mb_history", sbi->s_mb_proc);
1985 +       remove_proc_entry(name, proc_root_ext3);
1986 +
1987 +       if (sbi->s_mb_history)
1988 +               kfree(sbi->s_mb_history);
1989 +}
1990 +
1991 +static void ext3_mb_history_init(struct super_block *sb)
1992 +{
1993 +       struct ext3_sb_info *sbi = EXT3_SB(sb);
1994 +       char name[64];
1995 +       int i;
1996 +
1997 +       snprintf(name, sizeof(name) - 1, "%s", bdevname(sb->s_bdev, name));
1998 +       sbi->s_mb_proc = proc_mkdir(name, proc_root_ext3);
1999 +       if (sbi->s_mb_proc != NULL) {
2000 +               struct proc_dir_entry *p;
2001 +               p = create_proc_entry("mb_history", S_IRUGO, sbi->s_mb_proc);
2002 +               if (p) {
2003 +                       p->proc_fops = &ext3_mb_seq_history_fops;
2004 +                       p->data = sb;
2005 +               }
2006 +       }
2007 +
2008 +       sbi->s_mb_history_max = 1000;
2009 +       sbi->s_mb_history_cur = 0;
2010 +       spin_lock_init(&sbi->s_mb_history_lock);
2011 +       i = sbi->s_mb_history_max * sizeof(struct ext3_mb_history);
2012 +       sbi->s_mb_history = kmalloc(i, GFP_KERNEL);
2013 +       memset(sbi->s_mb_history, 0, i);
2014 +       /* if we can't allocate history, then we simple won't use it */
2015 +}
2016 +
2017 +static void
2018 +ext3_mb_store_history(struct super_block *sb, struct ext3_allocation_context *ac)
2019 +{
2020 +       struct ext3_sb_info *sbi = EXT3_SB(sb);
2021 +       struct ext3_mb_history h;
2022 +
2023 +       if (likely(sbi->s_mb_history == NULL))
2024 +               return;
2025 +
2026 +       h.goal = ac->ac_g_ex;
2027 +       h.result = ac->ac_b_ex;
2028 +       h.found = ac->ac_found;
2029 +       h.cr = ac->ac_criteria;
2030 +       h.groups = ac->ac_groups_scanned;
2031 +       h.tail = ac->ac_tail;
2032 +       h.buddy = ac->ac_buddy;
2033 +       h.merged = 0;
2034 +       if (ac->ac_g_ex.fe_start == ac->ac_b_ex.fe_start &&
2035 +                       ac->ac_g_ex.fe_group == ac->ac_b_ex.fe_group)
2036 +               h.merged = 1;
2037 +
2038 +       spin_lock(&sbi->s_mb_history_lock);
2039 +       memcpy(sbi->s_mb_history + sbi->s_mb_history_cur, &h, sizeof(h));
2040 +       if (++sbi->s_mb_history_cur >= sbi->s_mb_history_max)
2041 +               sbi->s_mb_history_cur = 0;
2042 +       spin_unlock(&sbi->s_mb_history_lock);
2043 +}
2044 +
2045 +#else
2046 +#define ext3_mb_history_release(sb)
2047 +#define ext3_mb_history_init(sb)
2048 +#endif
2049 +
2050 +int ext3_mb_init_backend(struct super_block *sb)
2051 +{
2052 +       struct ext3_sb_info *sbi = EXT3_SB(sb);
2053 +       int i, len;
2054 +
2055 +       len = sizeof(struct ext3_buddy_group_blocks *) * sbi->s_groups_count;
2056 +       sbi->s_group_info = kmalloc(len, GFP_KERNEL);
2057 +       if (sbi->s_group_info == NULL) {
2058 +               printk(KERN_ERR "EXT3-fs: can't allocate mem for buddy\n");
2059 +               return -ENOMEM;
2060 +       }
2061 +       memset(sbi->s_group_info, 0, len);
2062 +
2063 +       sbi->s_buddy_cache = new_inode(sb);
2064 +       if (sbi->s_buddy_cache == NULL) {
2065 +               printk(KERN_ERR "EXT3-fs: can't get new inode\n");
2066 +               kfree(sbi->s_group_info);
2067 +               return -ENOMEM;
2068 +       }
2069 +
2070 +       /* 
2071 +        * calculate needed size. if change bb_counters size,
2072 +        * don't forget about ext3_mb_generate_buddy()
2073 +        */
2074 +       len = sizeof(struct ext3_group_info);
2075 +       len += sizeof(unsigned short) * (sb->s_blocksize_bits + 2);
2076 +       for (i = 0; i < sbi->s_groups_count; i++) {
2077 +               struct ext3_group_desc * desc;
2078 +
2079 +               sbi->s_group_info[i] = kmalloc(len, GFP_KERNEL);
2080 +               if (sbi->s_group_info[i] == NULL) {
2081 +                       printk(KERN_ERR "EXT3-fs: can't allocate buddy mem\n");
2082 +                       goto err_out;
2083 +               }
2084 +               desc = ext3_get_group_desc(sb, i, NULL);
2085 +               if (desc == NULL) {
2086 +                       printk(KERN_ERR"EXT3-fs: can't read descriptor %u\n",i);
2087 +                       goto err_out;
2088 +               }
2089 +               memset(sbi->s_group_info[i], 0, len);
2090 +               set_bit(EXT3_GROUP_INFO_NEED_INIT_BIT,
2091 +                       &sbi->s_group_info[i]->bb_state);
2092 +               sbi->s_group_info[i]->bb_free =
2093 +                       le16_to_cpu(desc->bg_free_blocks_count);
2094 +       }
2095 +
2096 +       return 0;
2097 +
2098 +err_out:
2099 +       while (--i >= 0)
2100 +               kfree(sbi->s_group_info[i]);
2101 +       iput(sbi->s_buddy_cache);
2102 +
2103 +       return -ENOMEM;
2104 +}
2105 +
2106 +int ext3_mb_init(struct super_block *sb, int needs_recovery)
2107 +{
2108 +       struct ext3_sb_info *sbi = EXT3_SB(sb);
2109 +       struct inode *root = sb->s_root->d_inode;
2110 +       unsigned i, offset, max;
2111 +       struct dentry *dentry;
2112 +
2113 +       if (!test_opt(sb, MBALLOC))
2114 +               return 0;
2115 +
2116 +       i = (sb->s_blocksize_bits + 2) * sizeof(unsigned short);
2117 +
2118 +       sbi->s_mb_offsets = kmalloc(i, GFP_KERNEL);
2119 +       if (sbi->s_mb_offsets == NULL) {
2120 +               clear_opt(sbi->s_mount_opt, MBALLOC);
2121 +               return -ENOMEM;
2122 +       }
2123 +       sbi->s_mb_maxs = kmalloc(i, GFP_KERNEL);
2124 +       if (sbi->s_mb_maxs == NULL) {
2125 +               clear_opt(sbi->s_mount_opt, MBALLOC);
2126 +               kfree(sbi->s_mb_maxs);
2127 +               return -ENOMEM;
2128 +       }
2129 +
2130 +        /* order 0 is regular bitmap */
2131 +       sbi->s_mb_maxs[0] = sb->s_blocksize << 3;
2132 +       sbi->s_mb_offsets[0] = 0;
2133 +
2134 +       i = 1;
2135 +       offset = 0;
2136 +       max = sb->s_blocksize << 2;
2137 +       do {
2138 +               sbi->s_mb_offsets[i] = offset;
2139 +               sbi->s_mb_maxs[i] = max;
2140 +               offset += 1 << (sb->s_blocksize_bits - i);
2141 +               max = max >> 1;
2142 +               i++;
2143 +       } while (i <= sb->s_blocksize_bits + 1);
2144 +       
2145 +
2146 +       /* init file for buddy data */
2147 +       if ((i = ext3_mb_init_backend(sb))) {
2148 +               clear_opt(sbi->s_mount_opt, MBALLOC);
2149 +               kfree(sbi->s_mb_offsets);
2150 +               kfree(sbi->s_mb_maxs);
2151 +               return i;
2152 +       }
2153 +
2154 +       spin_lock_init(&sbi->s_reserve_lock);
2155 +       spin_lock_init(&sbi->s_md_lock);
2156 +       INIT_LIST_HEAD(&sbi->s_active_transaction);
2157 +       INIT_LIST_HEAD(&sbi->s_closed_transaction);
2158 +       INIT_LIST_HEAD(&sbi->s_committed_transaction);
2159 +       spin_lock_init(&sbi->s_bal_lock);
2160 +
2161 +       /* remove old on-disk buddy file */
2162 +       down(&root->i_sem);
2163 +       dentry = lookup_one_len(".buddy", sb->s_root, strlen(".buddy"));
2164 +       if (dentry->d_inode != NULL) {
2165 +               i = vfs_unlink(root, dentry);
2166 +               if (i != 0)
2167 +                       printk("EXT3-fs: can't remove .buddy file: %d\n", i);
2168 +       }
2169 +       dput(dentry);
2170 +       up(&root->i_sem);
2171 +
2172 +       ext3_mb_history_init(sb);
2173 +
2174 +       printk("EXT3-fs: mballoc enabled\n");
2175 +       return 0;
2176 +}
2177 +
2178 +int ext3_mb_release(struct super_block *sb)
2179 +{
2180 +       struct ext3_sb_info *sbi = EXT3_SB(sb);
2181 +       int i;
2182 +       
2183 +       if (!test_opt(sb, MBALLOC))
2184 +               return 0;
2185 +
2186 +       /* release freed, non-committed blocks */
2187 +       spin_lock(&sbi->s_md_lock);
2188 +       list_splice_init(&sbi->s_closed_transaction,
2189 +                       &sbi->s_committed_transaction);
2190 +       list_splice_init(&sbi->s_active_transaction,
2191 +                       &sbi->s_committed_transaction);
2192 +       spin_unlock(&sbi->s_md_lock);
2193 +       ext3_mb_free_committed_blocks(sb);
2194 +
2195 +       if (sbi->s_group_info) {
2196 +               for (i = 0; i < sbi->s_groups_count; i++) {
2197 +                       if (sbi->s_group_info[i] == NULL)
2198 +                               continue;
2199 +                       kfree(sbi->s_group_info[i]);
2200 +               }
2201 +               kfree(sbi->s_group_info);
2202 +       }
2203 +       if (sbi->s_mb_offsets)
2204 +               kfree(sbi->s_mb_offsets);
2205 +       if (sbi->s_mb_maxs)
2206 +               kfree(sbi->s_mb_maxs);
2207 +       if (sbi->s_buddy_cache)
2208 +               iput(sbi->s_buddy_cache);
2209 +       if (sbi->s_blocks_reserved)
2210 +               printk("ext3-fs: %ld blocks being reserved at umount!\n",
2211 +                               sbi->s_blocks_reserved);
2212 +       if (ext3_mb_stats) {
2213 +               printk("EXT3-fs: mballoc: %u blocks %u reqs (%u success)\n",
2214 +                       atomic_read(&sbi->s_bal_allocated),
2215 +                       atomic_read(&sbi->s_bal_reqs),
2216 +                       atomic_read(&sbi->s_bal_success));
2217 +               printk("EXT3-fs: mballoc: %u extents scanned, %u goal hits, "
2218 +                       "%u 2^N hits, %u breaks\n",
2219 +                       atomic_read(&sbi->s_bal_ex_scanned),
2220 +                       atomic_read(&sbi->s_bal_goals),
2221 +                       atomic_read(&sbi->s_bal_2orders),
2222 +                       atomic_read(&sbi->s_bal_breaks));
2223 +               printk("EXT3-fs: mballoc: %lu generated and it took %Lu\n",
2224 +                       sbi->s_mb_buddies_generated++,
2225 +                       sbi->s_mb_generation_time);
2226 +       }
2227 +
2228 +       ext3_mb_history_release(sb);
2229 +
2230 +       return 0;
2231 +}
2232 +
2233 +void ext3_mb_free_committed_blocks(struct super_block *sb)
2234 +{
2235 +       struct ext3_sb_info *sbi = EXT3_SB(sb);
2236 +       int err, i, count = 0, count2 = 0;
2237 +       struct ext3_free_metadata *md;
2238 +       struct ext3_buddy e3b;
2239 +
2240 +       if (list_empty(&sbi->s_committed_transaction))
2241 +               return;
2242 +
2243 +       /* there is committed blocks to be freed yet */
2244 +       do {
2245 +               /* get next array of blocks */
2246 +               md = NULL;
2247 +               spin_lock(&sbi->s_md_lock);
2248 +               if (!list_empty(&sbi->s_committed_transaction)) {
2249 +                       md = list_entry(sbi->s_committed_transaction.next,
2250 +                                       struct ext3_free_metadata, list);
2251 +                       list_del(&md->list);
2252 +               }
2253 +               spin_unlock(&sbi->s_md_lock);
2254 +
2255 +               if (md == NULL)
2256 +                       break;
2257 +
2258 +               mb_debug("gonna free %u blocks in group %u (0x%p):",
2259 +                               md->num, md->group, md);
2260 +
2261 +               err = ext3_mb_load_buddy(sb, md->group, &e3b);
2262 +               BUG_ON(err != 0);
2263 +
2264 +               /* there are blocks to put in buddy to make them really free */
2265 +               count += md->num;
2266 +               count2++;
2267 +               ext3_lock_group(sb, md->group);
2268 +               for (i = 0; i < md->num; i++) {
2269 +                       mb_debug(" %u", md->blocks[i]);
2270 +                       mb_free_blocks(&e3b, md->blocks[i], 1);
2271 +               }
2272 +               mb_debug("\n");
2273 +               ext3_unlock_group(sb, md->group);
2274 +
2275 +               /* balance refcounts from ext3_mb_free_metadata() */
2276 +               page_cache_release(e3b.bd_buddy_page);
2277 +               page_cache_release(e3b.bd_bitmap_page);
2278 +
2279 +               kfree(md);
2280 +               ext3_mb_release_desc(&e3b);
2281 +
2282 +       } while (md);
2283 +       mb_debug("freed %u blocks in %u structures\n", count, count2);
2284 +}
2285 +
2286 +void ext3_mb_poll_new_transaction(struct super_block *sb, handle_t *handle)
2287 +{
2288 +       struct ext3_sb_info *sbi = EXT3_SB(sb);
2289 +
2290 +       if (sbi->s_last_transaction == handle->h_transaction->t_tid)
2291 +               return;
2292 +
2293 +       /* new transaction! time to close last one and free blocks for
2294 +        * committed transaction. we know that only transaction can be
2295 +        * active, so previos transaction can be being logged and we
2296 +        * know that transaction before previous is known to be already
2297 +        * logged. this means that now we may free blocks freed in all
2298 +        * transactions before previous one. hope I'm clear enough ... */
2299 +
2300 +       spin_lock(&sbi->s_md_lock);
2301 +       if (sbi->s_last_transaction != handle->h_transaction->t_tid) {
2302 +               mb_debug("new transaction %lu, old %lu\n",
2303 +                               (unsigned long) handle->h_transaction->t_tid,
2304 +                               (unsigned long) sbi->s_last_transaction);
2305 +               list_splice_init(&sbi->s_closed_transaction,
2306 +                                       &sbi->s_committed_transaction);
2307 +               list_splice_init(&sbi->s_active_transaction,
2308 +                                       &sbi->s_closed_transaction);
2309 +               sbi->s_last_transaction = handle->h_transaction->t_tid;
2310 +       }
2311 +       spin_unlock(&sbi->s_md_lock);
2312 +
2313 +       ext3_mb_free_committed_blocks(sb);
2314 +}
2315 +
2316 +int ext3_mb_free_metadata(handle_t *handle, struct ext3_buddy *e3b,
2317 +                               int group, int block, int count)
2318 +{
2319 +       struct ext3_group_info *db = e3b->bd_info;
2320 +       struct super_block *sb = e3b->bd_sb;
2321 +       struct ext3_sb_info *sbi = EXT3_SB(sb);
2322 +       struct ext3_free_metadata *md;
2323 +       int i;
2324 +
2325 +       J_ASSERT(e3b->bd_bitmap_page != NULL);
2326 +       J_ASSERT(e3b->bd_buddy_page != NULL);
2327 +
2328 +       ext3_lock_group(sb, group);
2329 +       for (i = 0; i < count; i++) {
2330 +               md = db->bb_md_cur;
2331 +               if (md && db->bb_tid != handle->h_transaction->t_tid) {
2332 +                       db->bb_md_cur = NULL;
2333 +                       md = NULL;
2334 +               }
2335 +
2336 +               if (md == NULL) {
2337 +                       ext3_unlock_group(sb, group);
2338 +                       md = kmalloc(sizeof(*md), GFP_KERNEL);
2339 +                       if (md == NULL)
2340 +                               return -ENOMEM;
2341 +                       md->num = 0;
2342 +                       md->group = group;
2343 +
2344 +                       ext3_lock_group(sb, group);
2345 +                       if (db->bb_md_cur == NULL) {
2346 +                               spin_lock(&sbi->s_md_lock);
2347 +                               list_add(&md->list, &sbi->s_active_transaction);
2348 +                               spin_unlock(&sbi->s_md_lock);
2349 +                               /* protect buddy cache from being freed,
2350 +                                * otherwise we'll refresh it from
2351 +                                * on-disk bitmap and lose not-yet-available
2352 +                                * blocks */
2353 +                               page_cache_get(e3b->bd_buddy_page);
2354 +                               page_cache_get(e3b->bd_bitmap_page);
2355 +                               db->bb_md_cur = md;
2356 +                               db->bb_tid = handle->h_transaction->t_tid;
2357 +                               mb_debug("new md 0x%p for group %u\n",
2358 +                                                       md, md->group);
2359 +                       } else {
2360 +                               kfree(md);
2361 +                               md = db->bb_md_cur;
2362 +                       }
2363 +               }
2364 +
2365 +               BUG_ON(md->num >= EXT3_BB_MAX_BLOCKS);
2366 +               md->blocks[md->num] = block + i;
2367 +               md->num++;
2368 +               if (md->num == EXT3_BB_MAX_BLOCKS) {
2369 +                       /* no more space, put full container on a sb's list */
2370 +                       db->bb_md_cur = NULL;
2371 +               }
2372 +       }
2373 +       ext3_unlock_group(sb, group);
2374 +       return 0;
2375 +}
2376 +
2377 +void ext3_mb_free_blocks(handle_t *handle, struct inode *inode,
2378 +                       unsigned long block, unsigned long count,
2379 +                       int metadata, int *freed)
2380 +{
2381 +       struct buffer_head *bitmap_bh = NULL;
2382 +       struct ext3_group_desc *gdp;
2383 +       struct ext3_super_block *es;
2384 +       unsigned long bit, overflow;
2385 +       struct buffer_head *gd_bh;
2386 +       unsigned long block_group;
2387 +       struct ext3_sb_info *sbi;
2388 +       struct super_block *sb;
2389 +       struct ext3_buddy e3b;
2390 +       int err = 0, ret;
2391 +
2392 +       *freed = 0;
2393 +       sb = inode->i_sb;
2394 +       if (!sb) {
2395 +               printk ("ext3_free_blocks: nonexistent device");
2396 +               return;
2397 +       }
2398 +
2399 +       ext3_mb_poll_new_transaction(sb, handle);
2400 +
2401 +       sbi = EXT3_SB(sb);
2402 +       es = EXT3_SB(sb)->s_es;
2403 +       if (block < le32_to_cpu(es->s_first_data_block) ||
2404 +           block + count < block ||
2405 +           block + count > le32_to_cpu(es->s_blocks_count)) {
2406 +               ext3_error (sb, "ext3_free_blocks",
2407 +                           "Freeing blocks not in datazone - "
2408 +                           "block = %lu, count = %lu", block, count);
2409 +               goto error_return;
2410 +       }
2411 +
2412 +       ext3_debug("freeing block %lu\n", block);
2413 +
2414 +do_more:
2415 +       overflow = 0;
2416 +       block_group = (block - le32_to_cpu(es->s_first_data_block)) /
2417 +                     EXT3_BLOCKS_PER_GROUP(sb);
2418 +       bit = (block - le32_to_cpu(es->s_first_data_block)) %
2419 +                     EXT3_BLOCKS_PER_GROUP(sb);
2420 +       /*
2421 +        * Check to see if we are freeing blocks across a group
2422 +        * boundary.
2423 +        */
2424 +       if (bit + count > EXT3_BLOCKS_PER_GROUP(sb)) {
2425 +               overflow = bit + count - EXT3_BLOCKS_PER_GROUP(sb);
2426 +               count -= overflow;
2427 +       }
2428 +       brelse(bitmap_bh);
2429 +       bitmap_bh = read_block_bitmap(sb, block_group);
2430 +       if (!bitmap_bh)
2431 +               goto error_return;
2432 +       gdp = ext3_get_group_desc (sb, block_group, &gd_bh);
2433 +       if (!gdp)
2434 +               goto error_return;
2435 +
2436 +       if (in_range (le32_to_cpu(gdp->bg_block_bitmap), block, count) ||
2437 +           in_range (le32_to_cpu(gdp->bg_inode_bitmap), block, count) ||
2438 +           in_range (block, le32_to_cpu(gdp->bg_inode_table),
2439 +                     EXT3_SB(sb)->s_itb_per_group) ||
2440 +           in_range (block + count - 1, le32_to_cpu(gdp->bg_inode_table),
2441 +                     EXT3_SB(sb)->s_itb_per_group))
2442 +               ext3_error (sb, "ext3_free_blocks",
2443 +                           "Freeing blocks in system zones - "
2444 +                           "Block = %lu, count = %lu",
2445 +                           block, count);
2446 +
2447 +       BUFFER_TRACE(bitmap_bh, "getting write access");
2448 +       err = ext3_journal_get_write_access(handle, bitmap_bh);
2449 +       if (err)
2450 +               goto error_return;
2451 +
2452 +       /*
2453 +        * We are about to modify some metadata.  Call the journal APIs
2454 +        * to unshare ->b_data if a currently-committing transaction is
2455 +        * using it
2456 +        */
2457 +       BUFFER_TRACE(gd_bh, "get_write_access");
2458 +       err = ext3_journal_get_write_access(handle, gd_bh);
2459 +       if (err)
2460 +               goto error_return;
2461 +
2462 +       err = ext3_mb_load_buddy(sb, block_group, &e3b);
2463 +       if (err)
2464 +               goto error_return;
2465 +
2466 +#ifdef AGGRESSIVE_CHECK
2467 +       {
2468 +               int i;
2469 +               for (i = 0; i < count; i++)
2470 +                       J_ASSERT(mb_test_bit(bit + i, bitmap_bh->b_data));
2471 +       }
2472 +#endif
2473 +       mb_clear_bits(bitmap_bh->b_data, bit, count);
2474 +
2475 +       /* We dirtied the bitmap block */
2476 +       BUFFER_TRACE(bitmap_bh, "dirtied bitmap block");
2477 +       err = ext3_journal_dirty_metadata(handle, bitmap_bh);
2478 +
2479 +       if (metadata) {
2480 +               /* blocks being freed are metadata. these blocks shouldn't
2481 +                * be used until this transaction is committed */
2482 +               ext3_mb_free_metadata(handle, &e3b, block_group, bit, count);
2483 +       } else { 
2484 +               ext3_lock_group(sb, block_group);
2485 +               mb_free_blocks(&e3b, bit, count);
2486 +               ext3_unlock_group(sb, block_group);
2487 +       }
2488 +
2489 +       spin_lock(sb_bgl_lock(sbi, block_group));
2490 +       gdp->bg_free_blocks_count =
2491 +               cpu_to_le16(le16_to_cpu(gdp->bg_free_blocks_count) + count);
2492 +       spin_unlock(sb_bgl_lock(sbi, block_group));
2493 +       percpu_counter_mod(&sbi->s_freeblocks_counter, count);
2494 +       
2495 +       ext3_mb_release_desc(&e3b);
2496 +
2497 +       *freed = count;
2498 +
2499 +       /* And the group descriptor block */
2500 +       BUFFER_TRACE(gd_bh, "dirtied group descriptor block");
2501 +       ret = ext3_journal_dirty_metadata(handle, gd_bh);
2502 +       if (!err) err = ret;
2503 +
2504 +       if (overflow && !err) {
2505 +               block += count;
2506 +               count = overflow;
2507 +               goto do_more;
2508 +       }
2509 +       sb->s_dirt = 1;
2510 +error_return:
2511 +       brelse(bitmap_bh);
2512 +       ext3_std_error(sb, err);
2513 +       return;
2514 +}
2515 +
2516 +int ext3_mb_reserve_blocks(struct super_block *sb, int blocks)
2517 +{
2518 +       struct ext3_sb_info *sbi = EXT3_SB(sb);
2519 +       int free, ret = -ENOSPC;
2520 +
2521 +       BUG_ON(blocks < 0);
2522 +       spin_lock(&sbi->s_reserve_lock);
2523 +       free = percpu_counter_read_positive(&sbi->s_freeblocks_counter);
2524 +       if (blocks <= free - sbi->s_blocks_reserved) {
2525 +               sbi->s_blocks_reserved += blocks;
2526 +               ret = 0;
2527 +       }
2528 +       spin_unlock(&sbi->s_reserve_lock);
2529 +       return ret;
2530 +}
2531 +
2532 +void ext3_mb_release_blocks(struct super_block *sb, int blocks)
2533 +{
2534 +       struct ext3_sb_info *sbi = EXT3_SB(sb);
2535 +
2536 +       BUG_ON(blocks < 0);
2537 +       spin_lock(&sbi->s_reserve_lock);
2538 +       sbi->s_blocks_reserved -= blocks;
2539 +       WARN_ON(sbi->s_blocks_reserved < 0);
2540 +       if (sbi->s_blocks_reserved < 0)
2541 +               sbi->s_blocks_reserved = 0;
2542 +       spin_unlock(&sbi->s_reserve_lock);
2543 +}
2544 +
2545 +int ext3_new_block(handle_t *handle, struct inode *inode,
2546 +               unsigned long goal, int *errp)
2547 +{
2548 +       int ret, len;
2549 +
2550 +       if (!test_opt(inode->i_sb, MBALLOC)) {
2551 +               ret = ext3_new_block_old(handle, inode, goal, errp);
2552 +               goto out;
2553 +       }
2554 +       len = 1;
2555 +       ret = ext3_mb_new_blocks(handle, inode, goal, &len, 0, errp);
2556 +out:
2557 +       return ret;
2558 +}
2559 +
2560 +
2561 +void ext3_free_blocks(handle_t *handle, struct inode * inode,
2562 +                       unsigned long block, unsigned long count, int metadata)
2563 +{
2564 +       struct super_block *sb;
2565 +       int freed;
2566 +
2567 +       sb = inode->i_sb;
2568 +       if (!test_opt(sb, MBALLOC) || !EXT3_SB(sb)->s_group_info)
2569 +               ext3_free_blocks_sb(handle, sb, block, count, &freed);
2570 +       else
2571 +               ext3_mb_free_blocks(handle, inode, block, count, metadata, &freed);
2572 +       if (freed)
2573 +               DQUOT_FREE_BLOCK(inode, freed);
2574 +       return;
2575 +}
2576 +
2577 +#define EXT3_ROOT                 "ext3"
2578 +#define EXT3_MB_STATS_NAME        "mb_stats"
2579 +#define EXT3_MB_MAX_TO_SCAN_NAME  "mb_max_to_scan"
2580 +#define EXT3_MB_MIN_TO_SCAN_NAME  "mb_min_to_scan"
2581 +
2582 +static int ext3_mb_stats_read(char *page, char **start, off_t off,
2583 +               int count, int *eof, void *data)
2584 +{
2585 +       int len;
2586 +
2587 +       *eof = 1;
2588 +       if (off != 0)
2589 +               return 0;
2590 +
2591 +       len = sprintf(page, "%ld\n", ext3_mb_stats);
2592 +       *start = page;
2593 +       return len;
2594 +}
2595 +
2596 +static int ext3_mb_stats_write(struct file *file, const char *buffer,
2597 +               unsigned long count, void *data)
2598 +{
2599 +       char str[32];
2600 +
2601 +       if (count >= sizeof(str)) {
2602 +               printk(KERN_ERR "EXT3-fs: %s string too long, max %u bytes\n",
2603 +                      EXT3_MB_STATS_NAME, (int)sizeof(str));
2604 +               return -EOVERFLOW;
2605 +       }
2606 +
2607 +       if (copy_from_user(str, buffer, count))
2608 +               return -EFAULT;
2609 +
2610 +       /* Only set to 0 or 1 respectively; zero->0; non-zero->1 */
2611 +       ext3_mb_stats = (simple_strtol(str, NULL, 0) != 0);
2612 +       return count;
2613 +}
2614 +
2615 +static int ext3_mb_max_to_scan_read(char *page, char **start, off_t off,
2616 +               int count, int *eof, void *data)
2617 +{
2618 +       int len;
2619 +
2620 +       *eof = 1;
2621 +       if (off != 0)
2622 +               return 0;
2623 +
2624 +       len = sprintf(page, "%ld\n", ext3_mb_max_to_scan);
2625 +       *start = page;
2626 +       return len;
2627 +}
2628 +
2629 +static int ext3_mb_max_to_scan_write(struct file *file, const char *buffer,
2630 +               unsigned long count, void *data)
2631 +{
2632 +       char str[32];
2633 +       long value;
2634 +
2635 +       if (count >= sizeof(str)) {
2636 +               printk(KERN_ERR "EXT3-fs: %s string too long, max %u bytes\n",
2637 +                      EXT3_MB_MAX_TO_SCAN_NAME, (int)sizeof(str));
2638 +               return -EOVERFLOW;
2639 +       }
2640 +
2641 +       if (copy_from_user(str, buffer, count))
2642 +               return -EFAULT;
2643 +
2644 +       /* Only set to 0 or 1 respectively; zero->0; non-zero->1 */
2645 +       value = simple_strtol(str, NULL, 0);
2646 +       if (value <= 0)
2647 +               return -ERANGE;
2648 +
2649 +       ext3_mb_max_to_scan = value;    
2650 +
2651 +       return count;
2652 +}
2653 +
2654 +static int ext3_mb_min_to_scan_read(char *page, char **start, off_t off,
2655 +               int count, int *eof, void *data)
2656 +{
2657 +       int len;
2658 +
2659 +       *eof = 1;
2660 +       if (off != 0)
2661 +               return 0;
2662 +
2663 +       len = sprintf(page, "%ld\n", ext3_mb_min_to_scan);
2664 +       *start = page;
2665 +       return len;
2666 +}
2667 +
2668 +static int ext3_mb_min_to_scan_write(struct file *file, const char *buffer,
2669 +               unsigned long count, void *data)
2670 +{
2671 +       char str[32];
2672 +       long value;
2673 +
2674 +       if (count >= sizeof(str)) {
2675 +               printk(KERN_ERR "EXT3-fs: %s string too long, max %u bytes\n",
2676 +                      EXT3_MB_MIN_TO_SCAN_NAME, (int)sizeof(str));
2677 +               return -EOVERFLOW;
2678 +       }
2679 +
2680 +       if (copy_from_user(str, buffer, count))
2681 +               return -EFAULT;
2682 +
2683 +       /* Only set to 0 or 1 respectively; zero->0; non-zero->1 */
2684 +       value = simple_strtol(str, NULL, 0);
2685 +       if (value <= 0)
2686 +               return -ERANGE;
2687 +
2688 +       ext3_mb_min_to_scan = value;    
2689 +
2690 +       return count;
2691 +}
2692 +
2693 +int __init init_ext3_proc(void)
2694 +{
2695 +       struct proc_dir_entry *proc_ext3_mb_stats;
2696 +       struct proc_dir_entry *proc_ext3_mb_max_to_scan;
2697 +       struct proc_dir_entry *proc_ext3_mb_min_to_scan;
2698 +
2699 +       proc_root_ext3 = proc_mkdir(EXT3_ROOT, proc_root_fs);
2700 +       if (proc_root_ext3 == NULL) {
2701 +               printk(KERN_ERR "EXT3-fs: Unable to create %s\n", EXT3_ROOT);
2702 +               return -EIO;
2703 +       }
2704 +
2705 +       /* Initialize EXT3_MB_STATS_NAME */
2706 +       proc_ext3_mb_stats = create_proc_entry(EXT3_MB_STATS_NAME,
2707 +                       S_IFREG | S_IRUGO | S_IWUSR, proc_root_ext3);
2708 +       if (proc_ext3_mb_stats == NULL) {
2709 +               printk(KERN_ERR "EXT3-fs: Unable to create %s\n",
2710 +                               EXT3_MB_STATS_NAME);
2711 +               remove_proc_entry(EXT3_ROOT, proc_root_fs);
2712 +               return -EIO;
2713 +       }
2714 +
2715 +       proc_ext3_mb_stats->data = NULL;
2716 +       proc_ext3_mb_stats->read_proc  = ext3_mb_stats_read;
2717 +       proc_ext3_mb_stats->write_proc = ext3_mb_stats_write;
2718 +
2719 +       /* Initialize EXT3_MAX_TO_SCAN_NAME */
2720 +       proc_ext3_mb_max_to_scan = create_proc_entry(
2721 +                       EXT3_MB_MAX_TO_SCAN_NAME,
2722 +                       S_IFREG | S_IRUGO | S_IWUSR, proc_root_ext3);
2723 +       if (proc_ext3_mb_max_to_scan == NULL) {
2724 +               printk(KERN_ERR "EXT3-fs: Unable to create %s\n",
2725 +                               EXT3_MB_MAX_TO_SCAN_NAME);
2726 +               remove_proc_entry(EXT3_MB_STATS_NAME, proc_root_ext3);
2727 +               remove_proc_entry(EXT3_ROOT, proc_root_fs);
2728 +               return -EIO;
2729 +       }
2730 +
2731 +       proc_ext3_mb_max_to_scan->data = NULL;
2732 +       proc_ext3_mb_max_to_scan->read_proc  = ext3_mb_max_to_scan_read;
2733 +       proc_ext3_mb_max_to_scan->write_proc = ext3_mb_max_to_scan_write;
2734 +
2735 +       /* Initialize EXT3_MIN_TO_SCAN_NAME */
2736 +       proc_ext3_mb_min_to_scan = create_proc_entry(
2737 +                       EXT3_MB_MIN_TO_SCAN_NAME,
2738 +                       S_IFREG | S_IRUGO | S_IWUSR, proc_root_ext3);
2739 +       if (proc_ext3_mb_min_to_scan == NULL) {
2740 +               printk(KERN_ERR "EXT3-fs: Unable to create %s\n",
2741 +                               EXT3_MB_MIN_TO_SCAN_NAME);
2742 +               remove_proc_entry(EXT3_MB_MAX_TO_SCAN_NAME, proc_root_ext3);
2743 +               remove_proc_entry(EXT3_MB_STATS_NAME, proc_root_ext3);
2744 +               remove_proc_entry(EXT3_ROOT, proc_root_fs);
2745 +               return -EIO;
2746 +       }
2747 +
2748 +       proc_ext3_mb_min_to_scan->data = NULL;
2749 +       proc_ext3_mb_min_to_scan->read_proc  = ext3_mb_min_to_scan_read;
2750 +       proc_ext3_mb_min_to_scan->write_proc = ext3_mb_min_to_scan_write;
2751 +
2752 +       return 0;
2753 +}
2754 +
2755 +void exit_ext3_proc(void)
2756 +{
2757 +       remove_proc_entry(EXT3_MB_STATS_NAME, proc_root_ext3);
2758 +       remove_proc_entry(EXT3_MB_MAX_TO_SCAN_NAME, proc_root_ext3);
2759 +       remove_proc_entry(EXT3_MB_MIN_TO_SCAN_NAME, proc_root_ext3);
2760 +       remove_proc_entry(EXT3_ROOT, proc_root_fs);
2761 +}
2762 Index: linux-2.6.12.6/fs/ext3/Makefile
2763 ===================================================================
2764 --- linux-2.6.12.6.orig/fs/ext3/Makefile        2005-12-17 02:17:16.000000000 +0300
2765 +++ linux-2.6.12.6/fs/ext3/Makefile     2005-12-17 02:21:21.000000000 +0300
2766 @@ -6,7 +6,7 @@
2767  
2768  ext3-y := balloc.o bitmap.o dir.o file.o fsync.o ialloc.o inode.o iopen.o \
2769            ioctl.o namei.o super.o symlink.o hash.o resize.o \
2770 -          extents.o
2771 +          extents.o mballoc.o
2772  
2773  ext3-$(CONFIG_EXT3_FS_XATTR)    += xattr.o xattr_user.o xattr_trusted.o
2774  ext3-$(CONFIG_EXT3_FS_POSIX_ACL) += acl.o