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