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