fallocate support in ext4
[linux-2.6] / fs / ext4 / extents.c
1 /*
2  * Copyright (c) 2003-2006, Cluster File Systems, Inc, info@clusterfs.com
3  * Written by Alex Tomas <alex@clusterfs.com>
4  *
5  * Architecture independence:
6  *   Copyright (c) 2005, Bull S.A.
7  *   Written by Pierre Peiffer <pierre.peiffer@bull.net>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License version 2 as
11  * published by the Free Software Foundation.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public Licens
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-
21  */
22
23 /*
24  * Extents support for EXT4
25  *
26  * TODO:
27  *   - ext4*_error() should be used in some situations
28  *   - analyze all BUG()/BUG_ON(), use -EIO where appropriate
29  *   - smart tree reduction
30  */
31
32 #include <linux/module.h>
33 #include <linux/fs.h>
34 #include <linux/time.h>
35 #include <linux/ext4_jbd2.h>
36 #include <linux/jbd.h>
37 #include <linux/highuid.h>
38 #include <linux/pagemap.h>
39 #include <linux/quotaops.h>
40 #include <linux/string.h>
41 #include <linux/slab.h>
42 #include <linux/falloc.h>
43 #include <linux/ext4_fs_extents.h>
44 #include <asm/uaccess.h>
45
46
47 /*
48  * ext_pblock:
49  * combine low and high parts of physical block number into ext4_fsblk_t
50  */
51 static ext4_fsblk_t ext_pblock(struct ext4_extent *ex)
52 {
53         ext4_fsblk_t block;
54
55         block = le32_to_cpu(ex->ee_start);
56         block |= ((ext4_fsblk_t) le16_to_cpu(ex->ee_start_hi) << 31) << 1;
57         return block;
58 }
59
60 /*
61  * idx_pblock:
62  * combine low and high parts of a leaf physical block number into ext4_fsblk_t
63  */
64 static ext4_fsblk_t idx_pblock(struct ext4_extent_idx *ix)
65 {
66         ext4_fsblk_t block;
67
68         block = le32_to_cpu(ix->ei_leaf);
69         block |= ((ext4_fsblk_t) le16_to_cpu(ix->ei_leaf_hi) << 31) << 1;
70         return block;
71 }
72
73 /*
74  * ext4_ext_store_pblock:
75  * stores a large physical block number into an extent struct,
76  * breaking it into parts
77  */
78 static void ext4_ext_store_pblock(struct ext4_extent *ex, ext4_fsblk_t pb)
79 {
80         ex->ee_start = cpu_to_le32((unsigned long) (pb & 0xffffffff));
81         ex->ee_start_hi = cpu_to_le16((unsigned long) ((pb >> 31) >> 1) & 0xffff);
82 }
83
84 /*
85  * ext4_idx_store_pblock:
86  * stores a large physical block number into an index struct,
87  * breaking it into parts
88  */
89 static void ext4_idx_store_pblock(struct ext4_extent_idx *ix, ext4_fsblk_t pb)
90 {
91         ix->ei_leaf = cpu_to_le32((unsigned long) (pb & 0xffffffff));
92         ix->ei_leaf_hi = cpu_to_le16((unsigned long) ((pb >> 31) >> 1) & 0xffff);
93 }
94
95 static int ext4_ext_check_header(const char *function, struct inode *inode,
96                                 struct ext4_extent_header *eh)
97 {
98         const char *error_msg = NULL;
99
100         if (unlikely(eh->eh_magic != EXT4_EXT_MAGIC)) {
101                 error_msg = "invalid magic";
102                 goto corrupted;
103         }
104         if (unlikely(eh->eh_max == 0)) {
105                 error_msg = "invalid eh_max";
106                 goto corrupted;
107         }
108         if (unlikely(le16_to_cpu(eh->eh_entries) > le16_to_cpu(eh->eh_max))) {
109                 error_msg = "invalid eh_entries";
110                 goto corrupted;
111         }
112         return 0;
113
114 corrupted:
115         ext4_error(inode->i_sb, function,
116                         "bad header in inode #%lu: %s - magic %x, "
117                         "entries %u, max %u, depth %u",
118                         inode->i_ino, error_msg, le16_to_cpu(eh->eh_magic),
119                         le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max),
120                         le16_to_cpu(eh->eh_depth));
121
122         return -EIO;
123 }
124
125 static handle_t *ext4_ext_journal_restart(handle_t *handle, int needed)
126 {
127         int err;
128
129         if (handle->h_buffer_credits > needed)
130                 return handle;
131         if (!ext4_journal_extend(handle, needed))
132                 return handle;
133         err = ext4_journal_restart(handle, needed);
134
135         return handle;
136 }
137
138 /*
139  * could return:
140  *  - EROFS
141  *  - ENOMEM
142  */
143 static int ext4_ext_get_access(handle_t *handle, struct inode *inode,
144                                 struct ext4_ext_path *path)
145 {
146         if (path->p_bh) {
147                 /* path points to block */
148                 return ext4_journal_get_write_access(handle, path->p_bh);
149         }
150         /* path points to leaf/index in inode body */
151         /* we use in-core data, no need to protect them */
152         return 0;
153 }
154
155 /*
156  * could return:
157  *  - EROFS
158  *  - ENOMEM
159  *  - EIO
160  */
161 static int ext4_ext_dirty(handle_t *handle, struct inode *inode,
162                                 struct ext4_ext_path *path)
163 {
164         int err;
165         if (path->p_bh) {
166                 /* path points to block */
167                 err = ext4_journal_dirty_metadata(handle, path->p_bh);
168         } else {
169                 /* path points to leaf/index in inode body */
170                 err = ext4_mark_inode_dirty(handle, inode);
171         }
172         return err;
173 }
174
175 static ext4_fsblk_t ext4_ext_find_goal(struct inode *inode,
176                               struct ext4_ext_path *path,
177                               ext4_fsblk_t block)
178 {
179         struct ext4_inode_info *ei = EXT4_I(inode);
180         ext4_fsblk_t bg_start;
181         ext4_grpblk_t colour;
182         int depth;
183
184         if (path) {
185                 struct ext4_extent *ex;
186                 depth = path->p_depth;
187
188                 /* try to predict block placement */
189                 ex = path[depth].p_ext;
190                 if (ex)
191                         return ext_pblock(ex)+(block-le32_to_cpu(ex->ee_block));
192
193                 /* it looks like index is empty;
194                  * try to find starting block from index itself */
195                 if (path[depth].p_bh)
196                         return path[depth].p_bh->b_blocknr;
197         }
198
199         /* OK. use inode's group */
200         bg_start = (ei->i_block_group * EXT4_BLOCKS_PER_GROUP(inode->i_sb)) +
201                 le32_to_cpu(EXT4_SB(inode->i_sb)->s_es->s_first_data_block);
202         colour = (current->pid % 16) *
203                         (EXT4_BLOCKS_PER_GROUP(inode->i_sb) / 16);
204         return bg_start + colour + block;
205 }
206
207 static ext4_fsblk_t
208 ext4_ext_new_block(handle_t *handle, struct inode *inode,
209                         struct ext4_ext_path *path,
210                         struct ext4_extent *ex, int *err)
211 {
212         ext4_fsblk_t goal, newblock;
213
214         goal = ext4_ext_find_goal(inode, path, le32_to_cpu(ex->ee_block));
215         newblock = ext4_new_block(handle, inode, goal, err);
216         return newblock;
217 }
218
219 static int ext4_ext_space_block(struct inode *inode)
220 {
221         int size;
222
223         size = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
224                         / sizeof(struct ext4_extent);
225 #ifdef AGGRESSIVE_TEST
226         if (size > 6)
227                 size = 6;
228 #endif
229         return size;
230 }
231
232 static int ext4_ext_space_block_idx(struct inode *inode)
233 {
234         int size;
235
236         size = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
237                         / sizeof(struct ext4_extent_idx);
238 #ifdef AGGRESSIVE_TEST
239         if (size > 5)
240                 size = 5;
241 #endif
242         return size;
243 }
244
245 static int ext4_ext_space_root(struct inode *inode)
246 {
247         int size;
248
249         size = sizeof(EXT4_I(inode)->i_data);
250         size -= sizeof(struct ext4_extent_header);
251         size /= sizeof(struct ext4_extent);
252 #ifdef AGGRESSIVE_TEST
253         if (size > 3)
254                 size = 3;
255 #endif
256         return size;
257 }
258
259 static int ext4_ext_space_root_idx(struct inode *inode)
260 {
261         int size;
262
263         size = sizeof(EXT4_I(inode)->i_data);
264         size -= sizeof(struct ext4_extent_header);
265         size /= sizeof(struct ext4_extent_idx);
266 #ifdef AGGRESSIVE_TEST
267         if (size > 4)
268                 size = 4;
269 #endif
270         return size;
271 }
272
273 #ifdef EXT_DEBUG
274 static void ext4_ext_show_path(struct inode *inode, struct ext4_ext_path *path)
275 {
276         int k, l = path->p_depth;
277
278         ext_debug("path:");
279         for (k = 0; k <= l; k++, path++) {
280                 if (path->p_idx) {
281                   ext_debug("  %d->%llu", le32_to_cpu(path->p_idx->ei_block),
282                             idx_pblock(path->p_idx));
283                 } else if (path->p_ext) {
284                         ext_debug("  %d:%d:%llu ",
285                                   le32_to_cpu(path->p_ext->ee_block),
286                                   ext4_ext_get_actual_len(path->p_ext),
287                                   ext_pblock(path->p_ext));
288                 } else
289                         ext_debug("  []");
290         }
291         ext_debug("\n");
292 }
293
294 static void ext4_ext_show_leaf(struct inode *inode, struct ext4_ext_path *path)
295 {
296         int depth = ext_depth(inode);
297         struct ext4_extent_header *eh;
298         struct ext4_extent *ex;
299         int i;
300
301         if (!path)
302                 return;
303
304         eh = path[depth].p_hdr;
305         ex = EXT_FIRST_EXTENT(eh);
306
307         for (i = 0; i < le16_to_cpu(eh->eh_entries); i++, ex++) {
308                 ext_debug("%d:%d:%llu ", le32_to_cpu(ex->ee_block),
309                           ext4_ext_get_actual_len(ex), ext_pblock(ex));
310         }
311         ext_debug("\n");
312 }
313 #else
314 #define ext4_ext_show_path(inode,path)
315 #define ext4_ext_show_leaf(inode,path)
316 #endif
317
318 static void ext4_ext_drop_refs(struct ext4_ext_path *path)
319 {
320         int depth = path->p_depth;
321         int i;
322
323         for (i = 0; i <= depth; i++, path++)
324                 if (path->p_bh) {
325                         brelse(path->p_bh);
326                         path->p_bh = NULL;
327                 }
328 }
329
330 /*
331  * ext4_ext_binsearch_idx:
332  * binary search for the closest index of the given block
333  */
334 static void
335 ext4_ext_binsearch_idx(struct inode *inode, struct ext4_ext_path *path, int block)
336 {
337         struct ext4_extent_header *eh = path->p_hdr;
338         struct ext4_extent_idx *r, *l, *m;
339
340         BUG_ON(eh->eh_magic != EXT4_EXT_MAGIC);
341         BUG_ON(le16_to_cpu(eh->eh_entries) > le16_to_cpu(eh->eh_max));
342         BUG_ON(le16_to_cpu(eh->eh_entries) <= 0);
343
344         ext_debug("binsearch for %d(idx):  ", block);
345
346         l = EXT_FIRST_INDEX(eh) + 1;
347         r = EXT_FIRST_INDEX(eh) + le16_to_cpu(eh->eh_entries) - 1;
348         while (l <= r) {
349                 m = l + (r - l) / 2;
350                 if (block < le32_to_cpu(m->ei_block))
351                         r = m - 1;
352                 else
353                         l = m + 1;
354                 ext_debug("%p(%u):%p(%u):%p(%u) ", l, l->ei_block,
355                                 m, m->ei_block, r, r->ei_block);
356         }
357
358         path->p_idx = l - 1;
359         ext_debug("  -> %d->%lld ", le32_to_cpu(path->p_idx->ei_block),
360                   idx_block(path->p_idx));
361
362 #ifdef CHECK_BINSEARCH
363         {
364                 struct ext4_extent_idx *chix, *ix;
365                 int k;
366
367                 chix = ix = EXT_FIRST_INDEX(eh);
368                 for (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ix++) {
369                   if (k != 0 &&
370                       le32_to_cpu(ix->ei_block) <= le32_to_cpu(ix[-1].ei_block)) {
371                                 printk("k=%d, ix=0x%p, first=0x%p\n", k,
372                                         ix, EXT_FIRST_INDEX(eh));
373                                 printk("%u <= %u\n",
374                                        le32_to_cpu(ix->ei_block),
375                                        le32_to_cpu(ix[-1].ei_block));
376                         }
377                         BUG_ON(k && le32_to_cpu(ix->ei_block)
378                                            <= le32_to_cpu(ix[-1].ei_block));
379                         if (block < le32_to_cpu(ix->ei_block))
380                                 break;
381                         chix = ix;
382                 }
383                 BUG_ON(chix != path->p_idx);
384         }
385 #endif
386
387 }
388
389 /*
390  * ext4_ext_binsearch:
391  * binary search for closest extent of the given block
392  */
393 static void
394 ext4_ext_binsearch(struct inode *inode, struct ext4_ext_path *path, int block)
395 {
396         struct ext4_extent_header *eh = path->p_hdr;
397         struct ext4_extent *r, *l, *m;
398
399         BUG_ON(eh->eh_magic != EXT4_EXT_MAGIC);
400         BUG_ON(le16_to_cpu(eh->eh_entries) > le16_to_cpu(eh->eh_max));
401
402         if (eh->eh_entries == 0) {
403                 /*
404                  * this leaf is empty:
405                  * we get such a leaf in split/add case
406                  */
407                 return;
408         }
409
410         ext_debug("binsearch for %d:  ", block);
411
412         l = EXT_FIRST_EXTENT(eh) + 1;
413         r = EXT_FIRST_EXTENT(eh) + le16_to_cpu(eh->eh_entries) - 1;
414
415         while (l <= r) {
416                 m = l + (r - l) / 2;
417                 if (block < le32_to_cpu(m->ee_block))
418                         r = m - 1;
419                 else
420                         l = m + 1;
421                 ext_debug("%p(%u):%p(%u):%p(%u) ", l, l->ee_block,
422                                 m, m->ee_block, r, r->ee_block);
423         }
424
425         path->p_ext = l - 1;
426         ext_debug("  -> %d:%llu:%d ",
427                         le32_to_cpu(path->p_ext->ee_block),
428                         ext_pblock(path->p_ext),
429                         ext4_ext_get_actual_len(path->p_ext));
430
431 #ifdef CHECK_BINSEARCH
432         {
433                 struct ext4_extent *chex, *ex;
434                 int k;
435
436                 chex = ex = EXT_FIRST_EXTENT(eh);
437                 for (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ex++) {
438                         BUG_ON(k && le32_to_cpu(ex->ee_block)
439                                           <= le32_to_cpu(ex[-1].ee_block));
440                         if (block < le32_to_cpu(ex->ee_block))
441                                 break;
442                         chex = ex;
443                 }
444                 BUG_ON(chex != path->p_ext);
445         }
446 #endif
447
448 }
449
450 int ext4_ext_tree_init(handle_t *handle, struct inode *inode)
451 {
452         struct ext4_extent_header *eh;
453
454         eh = ext_inode_hdr(inode);
455         eh->eh_depth = 0;
456         eh->eh_entries = 0;
457         eh->eh_magic = EXT4_EXT_MAGIC;
458         eh->eh_max = cpu_to_le16(ext4_ext_space_root(inode));
459         ext4_mark_inode_dirty(handle, inode);
460         ext4_ext_invalidate_cache(inode);
461         return 0;
462 }
463
464 struct ext4_ext_path *
465 ext4_ext_find_extent(struct inode *inode, int block, struct ext4_ext_path *path)
466 {
467         struct ext4_extent_header *eh;
468         struct buffer_head *bh;
469         short int depth, i, ppos = 0, alloc = 0;
470
471         eh = ext_inode_hdr(inode);
472         BUG_ON(eh == NULL);
473         if (ext4_ext_check_header(__FUNCTION__, inode, eh))
474                 return ERR_PTR(-EIO);
475
476         i = depth = ext_depth(inode);
477
478         /* account possible depth increase */
479         if (!path) {
480                 path = kzalloc(sizeof(struct ext4_ext_path) * (depth + 2),
481                                 GFP_NOFS);
482                 if (!path)
483                         return ERR_PTR(-ENOMEM);
484                 alloc = 1;
485         }
486         path[0].p_hdr = eh;
487
488         /* walk through the tree */
489         while (i) {
490                 ext_debug("depth %d: num %d, max %d\n",
491                           ppos, le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
492                 ext4_ext_binsearch_idx(inode, path + ppos, block);
493                 path[ppos].p_block = idx_pblock(path[ppos].p_idx);
494                 path[ppos].p_depth = i;
495                 path[ppos].p_ext = NULL;
496
497                 bh = sb_bread(inode->i_sb, path[ppos].p_block);
498                 if (!bh)
499                         goto err;
500
501                 eh = ext_block_hdr(bh);
502                 ppos++;
503                 BUG_ON(ppos > depth);
504                 path[ppos].p_bh = bh;
505                 path[ppos].p_hdr = eh;
506                 i--;
507
508                 if (ext4_ext_check_header(__FUNCTION__, inode, eh))
509                         goto err;
510         }
511
512         path[ppos].p_depth = i;
513         path[ppos].p_hdr = eh;
514         path[ppos].p_ext = NULL;
515         path[ppos].p_idx = NULL;
516
517         if (ext4_ext_check_header(__FUNCTION__, inode, eh))
518                 goto err;
519
520         /* find extent */
521         ext4_ext_binsearch(inode, path + ppos, block);
522
523         ext4_ext_show_path(inode, path);
524
525         return path;
526
527 err:
528         ext4_ext_drop_refs(path);
529         if (alloc)
530                 kfree(path);
531         return ERR_PTR(-EIO);
532 }
533
534 /*
535  * ext4_ext_insert_index:
536  * insert new index [@logical;@ptr] into the block at @curp;
537  * check where to insert: before @curp or after @curp
538  */
539 static int ext4_ext_insert_index(handle_t *handle, struct inode *inode,
540                                 struct ext4_ext_path *curp,
541                                 int logical, ext4_fsblk_t ptr)
542 {
543         struct ext4_extent_idx *ix;
544         int len, err;
545
546         err = ext4_ext_get_access(handle, inode, curp);
547         if (err)
548                 return err;
549
550         BUG_ON(logical == le32_to_cpu(curp->p_idx->ei_block));
551         len = EXT_MAX_INDEX(curp->p_hdr) - curp->p_idx;
552         if (logical > le32_to_cpu(curp->p_idx->ei_block)) {
553                 /* insert after */
554                 if (curp->p_idx != EXT_LAST_INDEX(curp->p_hdr)) {
555                         len = (len - 1) * sizeof(struct ext4_extent_idx);
556                         len = len < 0 ? 0 : len;
557                         ext_debug("insert new index %d after: %d. "
558                                         "move %d from 0x%p to 0x%p\n",
559                                         logical, ptr, len,
560                                         (curp->p_idx + 1), (curp->p_idx + 2));
561                         memmove(curp->p_idx + 2, curp->p_idx + 1, len);
562                 }
563                 ix = curp->p_idx + 1;
564         } else {
565                 /* insert before */
566                 len = len * sizeof(struct ext4_extent_idx);
567                 len = len < 0 ? 0 : len;
568                 ext_debug("insert new index %d before: %d. "
569                                 "move %d from 0x%p to 0x%p\n",
570                                 logical, ptr, len,
571                                 curp->p_idx, (curp->p_idx + 1));
572                 memmove(curp->p_idx + 1, curp->p_idx, len);
573                 ix = curp->p_idx;
574         }
575
576         ix->ei_block = cpu_to_le32(logical);
577         ext4_idx_store_pblock(ix, ptr);
578         curp->p_hdr->eh_entries = cpu_to_le16(le16_to_cpu(curp->p_hdr->eh_entries)+1);
579
580         BUG_ON(le16_to_cpu(curp->p_hdr->eh_entries)
581                              > le16_to_cpu(curp->p_hdr->eh_max));
582         BUG_ON(ix > EXT_LAST_INDEX(curp->p_hdr));
583
584         err = ext4_ext_dirty(handle, inode, curp);
585         ext4_std_error(inode->i_sb, err);
586
587         return err;
588 }
589
590 /*
591  * ext4_ext_split:
592  * inserts new subtree into the path, using free index entry
593  * at depth @at:
594  * - allocates all needed blocks (new leaf and all intermediate index blocks)
595  * - makes decision where to split
596  * - moves remaining extents and index entries (right to the split point)
597  *   into the newly allocated blocks
598  * - initializes subtree
599  */
600 static int ext4_ext_split(handle_t *handle, struct inode *inode,
601                                 struct ext4_ext_path *path,
602                                 struct ext4_extent *newext, int at)
603 {
604         struct buffer_head *bh = NULL;
605         int depth = ext_depth(inode);
606         struct ext4_extent_header *neh;
607         struct ext4_extent_idx *fidx;
608         struct ext4_extent *ex;
609         int i = at, k, m, a;
610         ext4_fsblk_t newblock, oldblock;
611         __le32 border;
612         ext4_fsblk_t *ablocks = NULL; /* array of allocated blocks */
613         int err = 0;
614
615         /* make decision: where to split? */
616         /* FIXME: now decision is simplest: at current extent */
617
618         /* if current leaf will be split, then we should use
619          * border from split point */
620         BUG_ON(path[depth].p_ext > EXT_MAX_EXTENT(path[depth].p_hdr));
621         if (path[depth].p_ext != EXT_MAX_EXTENT(path[depth].p_hdr)) {
622                 border = path[depth].p_ext[1].ee_block;
623                 ext_debug("leaf will be split."
624                                 " next leaf starts at %d\n",
625                                   le32_to_cpu(border));
626         } else {
627                 border = newext->ee_block;
628                 ext_debug("leaf will be added."
629                                 " next leaf starts at %d\n",
630                                 le32_to_cpu(border));
631         }
632
633         /*
634          * If error occurs, then we break processing
635          * and mark filesystem read-only. index won't
636          * be inserted and tree will be in consistent
637          * state. Next mount will repair buffers too.
638          */
639
640         /*
641          * Get array to track all allocated blocks.
642          * We need this to handle errors and free blocks
643          * upon them.
644          */
645         ablocks = kzalloc(sizeof(ext4_fsblk_t) * depth, GFP_NOFS);
646         if (!ablocks)
647                 return -ENOMEM;
648
649         /* allocate all needed blocks */
650         ext_debug("allocate %d blocks for indexes/leaf\n", depth - at);
651         for (a = 0; a < depth - at; a++) {
652                 newblock = ext4_ext_new_block(handle, inode, path, newext, &err);
653                 if (newblock == 0)
654                         goto cleanup;
655                 ablocks[a] = newblock;
656         }
657
658         /* initialize new leaf */
659         newblock = ablocks[--a];
660         BUG_ON(newblock == 0);
661         bh = sb_getblk(inode->i_sb, newblock);
662         if (!bh) {
663                 err = -EIO;
664                 goto cleanup;
665         }
666         lock_buffer(bh);
667
668         err = ext4_journal_get_create_access(handle, bh);
669         if (err)
670                 goto cleanup;
671
672         neh = ext_block_hdr(bh);
673         neh->eh_entries = 0;
674         neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode));
675         neh->eh_magic = EXT4_EXT_MAGIC;
676         neh->eh_depth = 0;
677         ex = EXT_FIRST_EXTENT(neh);
678
679         /* move remainder of path[depth] to the new leaf */
680         BUG_ON(path[depth].p_hdr->eh_entries != path[depth].p_hdr->eh_max);
681         /* start copy from next extent */
682         /* TODO: we could do it by single memmove */
683         m = 0;
684         path[depth].p_ext++;
685         while (path[depth].p_ext <=
686                         EXT_MAX_EXTENT(path[depth].p_hdr)) {
687                 ext_debug("move %d:%llu:%d in new leaf %llu\n",
688                                 le32_to_cpu(path[depth].p_ext->ee_block),
689                                 ext_pblock(path[depth].p_ext),
690                                 ext4_ext_get_actual_len(path[depth].p_ext),
691                                 newblock);
692                 /*memmove(ex++, path[depth].p_ext++,
693                                 sizeof(struct ext4_extent));
694                 neh->eh_entries++;*/
695                 path[depth].p_ext++;
696                 m++;
697         }
698         if (m) {
699                 memmove(ex, path[depth].p_ext-m, sizeof(struct ext4_extent)*m);
700                 neh->eh_entries = cpu_to_le16(le16_to_cpu(neh->eh_entries)+m);
701         }
702
703         set_buffer_uptodate(bh);
704         unlock_buffer(bh);
705
706         err = ext4_journal_dirty_metadata(handle, bh);
707         if (err)
708                 goto cleanup;
709         brelse(bh);
710         bh = NULL;
711
712         /* correct old leaf */
713         if (m) {
714                 err = ext4_ext_get_access(handle, inode, path + depth);
715                 if (err)
716                         goto cleanup;
717                 path[depth].p_hdr->eh_entries =
718                      cpu_to_le16(le16_to_cpu(path[depth].p_hdr->eh_entries)-m);
719                 err = ext4_ext_dirty(handle, inode, path + depth);
720                 if (err)
721                         goto cleanup;
722
723         }
724
725         /* create intermediate indexes */
726         k = depth - at - 1;
727         BUG_ON(k < 0);
728         if (k)
729                 ext_debug("create %d intermediate indices\n", k);
730         /* insert new index into current index block */
731         /* current depth stored in i var */
732         i = depth - 1;
733         while (k--) {
734                 oldblock = newblock;
735                 newblock = ablocks[--a];
736                 bh = sb_getblk(inode->i_sb, (ext4_fsblk_t)newblock);
737                 if (!bh) {
738                         err = -EIO;
739                         goto cleanup;
740                 }
741                 lock_buffer(bh);
742
743                 err = ext4_journal_get_create_access(handle, bh);
744                 if (err)
745                         goto cleanup;
746
747                 neh = ext_block_hdr(bh);
748                 neh->eh_entries = cpu_to_le16(1);
749                 neh->eh_magic = EXT4_EXT_MAGIC;
750                 neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode));
751                 neh->eh_depth = cpu_to_le16(depth - i);
752                 fidx = EXT_FIRST_INDEX(neh);
753                 fidx->ei_block = border;
754                 ext4_idx_store_pblock(fidx, oldblock);
755
756                 ext_debug("int.index at %d (block %llu): %lu -> %llu\n", i,
757                                 newblock, (unsigned long) le32_to_cpu(border),
758                                 oldblock);
759                 /* copy indexes */
760                 m = 0;
761                 path[i].p_idx++;
762
763                 ext_debug("cur 0x%p, last 0x%p\n", path[i].p_idx,
764                                 EXT_MAX_INDEX(path[i].p_hdr));
765                 BUG_ON(EXT_MAX_INDEX(path[i].p_hdr) !=
766                                 EXT_LAST_INDEX(path[i].p_hdr));
767                 while (path[i].p_idx <= EXT_MAX_INDEX(path[i].p_hdr)) {
768                         ext_debug("%d: move %d:%d in new index %llu\n", i,
769                                         le32_to_cpu(path[i].p_idx->ei_block),
770                                         idx_pblock(path[i].p_idx),
771                                         newblock);
772                         /*memmove(++fidx, path[i].p_idx++,
773                                         sizeof(struct ext4_extent_idx));
774                         neh->eh_entries++;
775                         BUG_ON(neh->eh_entries > neh->eh_max);*/
776                         path[i].p_idx++;
777                         m++;
778                 }
779                 if (m) {
780                         memmove(++fidx, path[i].p_idx - m,
781                                 sizeof(struct ext4_extent_idx) * m);
782                         neh->eh_entries =
783                                 cpu_to_le16(le16_to_cpu(neh->eh_entries) + m);
784                 }
785                 set_buffer_uptodate(bh);
786                 unlock_buffer(bh);
787
788                 err = ext4_journal_dirty_metadata(handle, bh);
789                 if (err)
790                         goto cleanup;
791                 brelse(bh);
792                 bh = NULL;
793
794                 /* correct old index */
795                 if (m) {
796                         err = ext4_ext_get_access(handle, inode, path + i);
797                         if (err)
798                                 goto cleanup;
799                         path[i].p_hdr->eh_entries = cpu_to_le16(le16_to_cpu(path[i].p_hdr->eh_entries)-m);
800                         err = ext4_ext_dirty(handle, inode, path + i);
801                         if (err)
802                                 goto cleanup;
803                 }
804
805                 i--;
806         }
807
808         /* insert new index */
809         err = ext4_ext_insert_index(handle, inode, path + at,
810                                     le32_to_cpu(border), newblock);
811
812 cleanup:
813         if (bh) {
814                 if (buffer_locked(bh))
815                         unlock_buffer(bh);
816                 brelse(bh);
817         }
818
819         if (err) {
820                 /* free all allocated blocks in error case */
821                 for (i = 0; i < depth; i++) {
822                         if (!ablocks[i])
823                                 continue;
824                         ext4_free_blocks(handle, inode, ablocks[i], 1);
825                 }
826         }
827         kfree(ablocks);
828
829         return err;
830 }
831
832 /*
833  * ext4_ext_grow_indepth:
834  * implements tree growing procedure:
835  * - allocates new block
836  * - moves top-level data (index block or leaf) into the new block
837  * - initializes new top-level, creating index that points to the
838  *   just created block
839  */
840 static int ext4_ext_grow_indepth(handle_t *handle, struct inode *inode,
841                                         struct ext4_ext_path *path,
842                                         struct ext4_extent *newext)
843 {
844         struct ext4_ext_path *curp = path;
845         struct ext4_extent_header *neh;
846         struct ext4_extent_idx *fidx;
847         struct buffer_head *bh;
848         ext4_fsblk_t newblock;
849         int err = 0;
850
851         newblock = ext4_ext_new_block(handle, inode, path, newext, &err);
852         if (newblock == 0)
853                 return err;
854
855         bh = sb_getblk(inode->i_sb, newblock);
856         if (!bh) {
857                 err = -EIO;
858                 ext4_std_error(inode->i_sb, err);
859                 return err;
860         }
861         lock_buffer(bh);
862
863         err = ext4_journal_get_create_access(handle, bh);
864         if (err) {
865                 unlock_buffer(bh);
866                 goto out;
867         }
868
869         /* move top-level index/leaf into new block */
870         memmove(bh->b_data, curp->p_hdr, sizeof(EXT4_I(inode)->i_data));
871
872         /* set size of new block */
873         neh = ext_block_hdr(bh);
874         /* old root could have indexes or leaves
875          * so calculate e_max right way */
876         if (ext_depth(inode))
877           neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode));
878         else
879           neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode));
880         neh->eh_magic = EXT4_EXT_MAGIC;
881         set_buffer_uptodate(bh);
882         unlock_buffer(bh);
883
884         err = ext4_journal_dirty_metadata(handle, bh);
885         if (err)
886                 goto out;
887
888         /* create index in new top-level index: num,max,pointer */
889         err = ext4_ext_get_access(handle, inode, curp);
890         if (err)
891                 goto out;
892
893         curp->p_hdr->eh_magic = EXT4_EXT_MAGIC;
894         curp->p_hdr->eh_max = cpu_to_le16(ext4_ext_space_root_idx(inode));
895         curp->p_hdr->eh_entries = cpu_to_le16(1);
896         curp->p_idx = EXT_FIRST_INDEX(curp->p_hdr);
897         /* FIXME: it works, but actually path[0] can be index */
898         curp->p_idx->ei_block = EXT_FIRST_EXTENT(path[0].p_hdr)->ee_block;
899         ext4_idx_store_pblock(curp->p_idx, newblock);
900
901         neh = ext_inode_hdr(inode);
902         fidx = EXT_FIRST_INDEX(neh);
903         ext_debug("new root: num %d(%d), lblock %d, ptr %llu\n",
904                   le16_to_cpu(neh->eh_entries), le16_to_cpu(neh->eh_max),
905                   le32_to_cpu(fidx->ei_block), idx_pblock(fidx));
906
907         neh->eh_depth = cpu_to_le16(path->p_depth + 1);
908         err = ext4_ext_dirty(handle, inode, curp);
909 out:
910         brelse(bh);
911
912         return err;
913 }
914
915 /*
916  * ext4_ext_create_new_leaf:
917  * finds empty index and adds new leaf.
918  * if no free index is found, then it requests in-depth growing.
919  */
920 static int ext4_ext_create_new_leaf(handle_t *handle, struct inode *inode,
921                                         struct ext4_ext_path *path,
922                                         struct ext4_extent *newext)
923 {
924         struct ext4_ext_path *curp;
925         int depth, i, err = 0;
926
927 repeat:
928         i = depth = ext_depth(inode);
929
930         /* walk up to the tree and look for free index entry */
931         curp = path + depth;
932         while (i > 0 && !EXT_HAS_FREE_INDEX(curp)) {
933                 i--;
934                 curp--;
935         }
936
937         /* we use already allocated block for index block,
938          * so subsequent data blocks should be contiguous */
939         if (EXT_HAS_FREE_INDEX(curp)) {
940                 /* if we found index with free entry, then use that
941                  * entry: create all needed subtree and add new leaf */
942                 err = ext4_ext_split(handle, inode, path, newext, i);
943
944                 /* refill path */
945                 ext4_ext_drop_refs(path);
946                 path = ext4_ext_find_extent(inode,
947                                             le32_to_cpu(newext->ee_block),
948                                             path);
949                 if (IS_ERR(path))
950                         err = PTR_ERR(path);
951         } else {
952                 /* tree is full, time to grow in depth */
953                 err = ext4_ext_grow_indepth(handle, inode, path, newext);
954                 if (err)
955                         goto out;
956
957                 /* refill path */
958                 ext4_ext_drop_refs(path);
959                 path = ext4_ext_find_extent(inode,
960                                             le32_to_cpu(newext->ee_block),
961                                             path);
962                 if (IS_ERR(path)) {
963                         err = PTR_ERR(path);
964                         goto out;
965                 }
966
967                 /*
968                  * only first (depth 0 -> 1) produces free space;
969                  * in all other cases we have to split the grown tree
970                  */
971                 depth = ext_depth(inode);
972                 if (path[depth].p_hdr->eh_entries == path[depth].p_hdr->eh_max) {
973                         /* now we need to split */
974                         goto repeat;
975                 }
976         }
977
978 out:
979         return err;
980 }
981
982 /*
983  * ext4_ext_next_allocated_block:
984  * returns allocated block in subsequent extent or EXT_MAX_BLOCK.
985  * NOTE: it considers block number from index entry as
986  * allocated block. Thus, index entries have to be consistent
987  * with leaves.
988  */
989 static unsigned long
990 ext4_ext_next_allocated_block(struct ext4_ext_path *path)
991 {
992         int depth;
993
994         BUG_ON(path == NULL);
995         depth = path->p_depth;
996
997         if (depth == 0 && path->p_ext == NULL)
998                 return EXT_MAX_BLOCK;
999
1000         while (depth >= 0) {
1001                 if (depth == path->p_depth) {
1002                         /* leaf */
1003                         if (path[depth].p_ext !=
1004                                         EXT_LAST_EXTENT(path[depth].p_hdr))
1005                           return le32_to_cpu(path[depth].p_ext[1].ee_block);
1006                 } else {
1007                         /* index */
1008                         if (path[depth].p_idx !=
1009                                         EXT_LAST_INDEX(path[depth].p_hdr))
1010                           return le32_to_cpu(path[depth].p_idx[1].ei_block);
1011                 }
1012                 depth--;
1013         }
1014
1015         return EXT_MAX_BLOCK;
1016 }
1017
1018 /*
1019  * ext4_ext_next_leaf_block:
1020  * returns first allocated block from next leaf or EXT_MAX_BLOCK
1021  */
1022 static unsigned ext4_ext_next_leaf_block(struct inode *inode,
1023                                         struct ext4_ext_path *path)
1024 {
1025         int depth;
1026
1027         BUG_ON(path == NULL);
1028         depth = path->p_depth;
1029
1030         /* zero-tree has no leaf blocks at all */
1031         if (depth == 0)
1032                 return EXT_MAX_BLOCK;
1033
1034         /* go to index block */
1035         depth--;
1036
1037         while (depth >= 0) {
1038                 if (path[depth].p_idx !=
1039                                 EXT_LAST_INDEX(path[depth].p_hdr))
1040                   return le32_to_cpu(path[depth].p_idx[1].ei_block);
1041                 depth--;
1042         }
1043
1044         return EXT_MAX_BLOCK;
1045 }
1046
1047 /*
1048  * ext4_ext_correct_indexes:
1049  * if leaf gets modified and modified extent is first in the leaf,
1050  * then we have to correct all indexes above.
1051  * TODO: do we need to correct tree in all cases?
1052  */
1053 int ext4_ext_correct_indexes(handle_t *handle, struct inode *inode,
1054                                 struct ext4_ext_path *path)
1055 {
1056         struct ext4_extent_header *eh;
1057         int depth = ext_depth(inode);
1058         struct ext4_extent *ex;
1059         __le32 border;
1060         int k, err = 0;
1061
1062         eh = path[depth].p_hdr;
1063         ex = path[depth].p_ext;
1064         BUG_ON(ex == NULL);
1065         BUG_ON(eh == NULL);
1066
1067         if (depth == 0) {
1068                 /* there is no tree at all */
1069                 return 0;
1070         }
1071
1072         if (ex != EXT_FIRST_EXTENT(eh)) {
1073                 /* we correct tree if first leaf got modified only */
1074                 return 0;
1075         }
1076
1077         /*
1078          * TODO: we need correction if border is smaller than current one
1079          */
1080         k = depth - 1;
1081         border = path[depth].p_ext->ee_block;
1082         err = ext4_ext_get_access(handle, inode, path + k);
1083         if (err)
1084                 return err;
1085         path[k].p_idx->ei_block = border;
1086         err = ext4_ext_dirty(handle, inode, path + k);
1087         if (err)
1088                 return err;
1089
1090         while (k--) {
1091                 /* change all left-side indexes */
1092                 if (path[k+1].p_idx != EXT_FIRST_INDEX(path[k+1].p_hdr))
1093                         break;
1094                 err = ext4_ext_get_access(handle, inode, path + k);
1095                 if (err)
1096                         break;
1097                 path[k].p_idx->ei_block = border;
1098                 err = ext4_ext_dirty(handle, inode, path + k);
1099                 if (err)
1100                         break;
1101         }
1102
1103         return err;
1104 }
1105
1106 static int
1107 ext4_can_extents_be_merged(struct inode *inode, struct ext4_extent *ex1,
1108                                 struct ext4_extent *ex2)
1109 {
1110         unsigned short ext1_ee_len, ext2_ee_len;
1111
1112         /*
1113          * Make sure that either both extents are uninitialized, or
1114          * both are _not_.
1115          */
1116         if (ext4_ext_is_uninitialized(ex1) ^ ext4_ext_is_uninitialized(ex2))
1117                 return 0;
1118
1119         ext1_ee_len = ext4_ext_get_actual_len(ex1);
1120         ext2_ee_len = ext4_ext_get_actual_len(ex2);
1121
1122         if (le32_to_cpu(ex1->ee_block) + ext1_ee_len !=
1123                         le32_to_cpu(ex2->ee_block))
1124                 return 0;
1125
1126         /*
1127          * To allow future support for preallocated extents to be added
1128          * as an RO_COMPAT feature, refuse to merge to extents if
1129          * this can result in the top bit of ee_len being set.
1130          */
1131         if (ext1_ee_len + ext2_ee_len > EXT_MAX_LEN)
1132                 return 0;
1133 #ifdef AGGRESSIVE_TEST
1134         if (le16_to_cpu(ex1->ee_len) >= 4)
1135                 return 0;
1136 #endif
1137
1138         if (ext_pblock(ex1) + ext1_ee_len == ext_pblock(ex2))
1139                 return 1;
1140         return 0;
1141 }
1142
1143 /*
1144  * check if a portion of the "newext" extent overlaps with an
1145  * existing extent.
1146  *
1147  * If there is an overlap discovered, it updates the length of the newext
1148  * such that there will be no overlap, and then returns 1.
1149  * If there is no overlap found, it returns 0.
1150  */
1151 unsigned int ext4_ext_check_overlap(struct inode *inode,
1152                                     struct ext4_extent *newext,
1153                                     struct ext4_ext_path *path)
1154 {
1155         unsigned long b1, b2;
1156         unsigned int depth, len1;
1157         unsigned int ret = 0;
1158
1159         b1 = le32_to_cpu(newext->ee_block);
1160         len1 = ext4_ext_get_actual_len(newext);
1161         depth = ext_depth(inode);
1162         if (!path[depth].p_ext)
1163                 goto out;
1164         b2 = le32_to_cpu(path[depth].p_ext->ee_block);
1165
1166         /*
1167          * get the next allocated block if the extent in the path
1168          * is before the requested block(s) 
1169          */
1170         if (b2 < b1) {
1171                 b2 = ext4_ext_next_allocated_block(path);
1172                 if (b2 == EXT_MAX_BLOCK)
1173                         goto out;
1174         }
1175
1176         /* check for wrap through zero */
1177         if (b1 + len1 < b1) {
1178                 len1 = EXT_MAX_BLOCK - b1;
1179                 newext->ee_len = cpu_to_le16(len1);
1180                 ret = 1;
1181         }
1182
1183         /* check for overlap */
1184         if (b1 + len1 > b2) {
1185                 newext->ee_len = cpu_to_le16(b2 - b1);
1186                 ret = 1;
1187         }
1188 out:
1189         return ret;
1190 }
1191
1192 /*
1193  * ext4_ext_insert_extent:
1194  * tries to merge requsted extent into the existing extent or
1195  * inserts requested extent as new one into the tree,
1196  * creating new leaf in the no-space case.
1197  */
1198 int ext4_ext_insert_extent(handle_t *handle, struct inode *inode,
1199                                 struct ext4_ext_path *path,
1200                                 struct ext4_extent *newext)
1201 {
1202         struct ext4_extent_header * eh;
1203         struct ext4_extent *ex, *fex;
1204         struct ext4_extent *nearex; /* nearest extent */
1205         struct ext4_ext_path *npath = NULL;
1206         int depth, len, err, next;
1207         unsigned uninitialized = 0;
1208
1209         BUG_ON(ext4_ext_get_actual_len(newext) == 0);
1210         depth = ext_depth(inode);
1211         ex = path[depth].p_ext;
1212         BUG_ON(path[depth].p_hdr == NULL);
1213
1214         /* try to insert block into found extent and return */
1215         if (ex && ext4_can_extents_be_merged(inode, ex, newext)) {
1216                 ext_debug("append %d block to %d:%d (from %llu)\n",
1217                                 ext4_ext_get_actual_len(newext),
1218                                 le32_to_cpu(ex->ee_block),
1219                                 ext4_ext_get_actual_len(ex), ext_pblock(ex));
1220                 err = ext4_ext_get_access(handle, inode, path + depth);
1221                 if (err)
1222                         return err;
1223
1224                 /*
1225                  * ext4_can_extents_be_merged should have checked that either
1226                  * both extents are uninitialized, or both aren't. Thus we
1227                  * need to check only one of them here.
1228                  */
1229                 if (ext4_ext_is_uninitialized(ex))
1230                         uninitialized = 1;
1231                 ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
1232                                         + ext4_ext_get_actual_len(newext));
1233                 if (uninitialized)
1234                         ext4_ext_mark_uninitialized(ex);
1235                 eh = path[depth].p_hdr;
1236                 nearex = ex;
1237                 goto merge;
1238         }
1239
1240 repeat:
1241         depth = ext_depth(inode);
1242         eh = path[depth].p_hdr;
1243         if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max))
1244                 goto has_space;
1245
1246         /* probably next leaf has space for us? */
1247         fex = EXT_LAST_EXTENT(eh);
1248         next = ext4_ext_next_leaf_block(inode, path);
1249         if (le32_to_cpu(newext->ee_block) > le32_to_cpu(fex->ee_block)
1250             && next != EXT_MAX_BLOCK) {
1251                 ext_debug("next leaf block - %d\n", next);
1252                 BUG_ON(npath != NULL);
1253                 npath = ext4_ext_find_extent(inode, next, NULL);
1254                 if (IS_ERR(npath))
1255                         return PTR_ERR(npath);
1256                 BUG_ON(npath->p_depth != path->p_depth);
1257                 eh = npath[depth].p_hdr;
1258                 if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max)) {
1259                         ext_debug("next leaf isnt full(%d)\n",
1260                                   le16_to_cpu(eh->eh_entries));
1261                         path = npath;
1262                         goto repeat;
1263                 }
1264                 ext_debug("next leaf has no free space(%d,%d)\n",
1265                           le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
1266         }
1267
1268         /*
1269          * There is no free space in the found leaf.
1270          * We're gonna add a new leaf in the tree.
1271          */
1272         err = ext4_ext_create_new_leaf(handle, inode, path, newext);
1273         if (err)
1274                 goto cleanup;
1275         depth = ext_depth(inode);
1276         eh = path[depth].p_hdr;
1277
1278 has_space:
1279         nearex = path[depth].p_ext;
1280
1281         err = ext4_ext_get_access(handle, inode, path + depth);
1282         if (err)
1283                 goto cleanup;
1284
1285         if (!nearex) {
1286                 /* there is no extent in this leaf, create first one */
1287                 ext_debug("first extent in the leaf: %d:%llu:%d\n",
1288                                 le32_to_cpu(newext->ee_block),
1289                                 ext_pblock(newext),
1290                                 ext4_ext_get_actual_len(newext));
1291                 path[depth].p_ext = EXT_FIRST_EXTENT(eh);
1292         } else if (le32_to_cpu(newext->ee_block)
1293                            > le32_to_cpu(nearex->ee_block)) {
1294 /*              BUG_ON(newext->ee_block == nearex->ee_block); */
1295                 if (nearex != EXT_LAST_EXTENT(eh)) {
1296                         len = EXT_MAX_EXTENT(eh) - nearex;
1297                         len = (len - 1) * sizeof(struct ext4_extent);
1298                         len = len < 0 ? 0 : len;
1299                         ext_debug("insert %d:%llu:%d after: nearest 0x%p, "
1300                                         "move %d from 0x%p to 0x%p\n",
1301                                         le32_to_cpu(newext->ee_block),
1302                                         ext_pblock(newext),
1303                                         ext4_ext_get_actual_len(newext),
1304                                         nearex, len, nearex + 1, nearex + 2);
1305                         memmove(nearex + 2, nearex + 1, len);
1306                 }
1307                 path[depth].p_ext = nearex + 1;
1308         } else {
1309                 BUG_ON(newext->ee_block == nearex->ee_block);
1310                 len = (EXT_MAX_EXTENT(eh) - nearex) * sizeof(struct ext4_extent);
1311                 len = len < 0 ? 0 : len;
1312                 ext_debug("insert %d:%llu:%d before: nearest 0x%p, "
1313                                 "move %d from 0x%p to 0x%p\n",
1314                                 le32_to_cpu(newext->ee_block),
1315                                 ext_pblock(newext),
1316                                 ext4_ext_get_actual_len(newext),
1317                                 nearex, len, nearex + 1, nearex + 2);
1318                 memmove(nearex + 1, nearex, len);
1319                 path[depth].p_ext = nearex;
1320         }
1321
1322         eh->eh_entries = cpu_to_le16(le16_to_cpu(eh->eh_entries)+1);
1323         nearex = path[depth].p_ext;
1324         nearex->ee_block = newext->ee_block;
1325         nearex->ee_start = newext->ee_start;
1326         nearex->ee_start_hi = newext->ee_start_hi;
1327         nearex->ee_len = newext->ee_len;
1328
1329 merge:
1330         /* try to merge extents to the right */
1331         while (nearex < EXT_LAST_EXTENT(eh)) {
1332                 if (!ext4_can_extents_be_merged(inode, nearex, nearex + 1))
1333                         break;
1334                 /* merge with next extent! */
1335                 if (ext4_ext_is_uninitialized(nearex))
1336                         uninitialized = 1;
1337                 nearex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(nearex)
1338                                         + ext4_ext_get_actual_len(nearex + 1));
1339                 if (uninitialized)
1340                         ext4_ext_mark_uninitialized(nearex);
1341
1342                 if (nearex + 1 < EXT_LAST_EXTENT(eh)) {
1343                         len = (EXT_LAST_EXTENT(eh) - nearex - 1)
1344                                         * sizeof(struct ext4_extent);
1345                         memmove(nearex + 1, nearex + 2, len);
1346                 }
1347                 eh->eh_entries = cpu_to_le16(le16_to_cpu(eh->eh_entries)-1);
1348                 BUG_ON(eh->eh_entries == 0);
1349         }
1350
1351         /* try to merge extents to the left */
1352
1353         /* time to correct all indexes above */
1354         err = ext4_ext_correct_indexes(handle, inode, path);
1355         if (err)
1356                 goto cleanup;
1357
1358         err = ext4_ext_dirty(handle, inode, path + depth);
1359
1360 cleanup:
1361         if (npath) {
1362                 ext4_ext_drop_refs(npath);
1363                 kfree(npath);
1364         }
1365         ext4_ext_tree_changed(inode);
1366         ext4_ext_invalidate_cache(inode);
1367         return err;
1368 }
1369
1370 int ext4_ext_walk_space(struct inode *inode, unsigned long block,
1371                         unsigned long num, ext_prepare_callback func,
1372                         void *cbdata)
1373 {
1374         struct ext4_ext_path *path = NULL;
1375         struct ext4_ext_cache cbex;
1376         struct ext4_extent *ex;
1377         unsigned long next, start = 0, end = 0;
1378         unsigned long last = block + num;
1379         int depth, exists, err = 0;
1380
1381         BUG_ON(func == NULL);
1382         BUG_ON(inode == NULL);
1383
1384         while (block < last && block != EXT_MAX_BLOCK) {
1385                 num = last - block;
1386                 /* find extent for this block */
1387                 path = ext4_ext_find_extent(inode, block, path);
1388                 if (IS_ERR(path)) {
1389                         err = PTR_ERR(path);
1390                         path = NULL;
1391                         break;
1392                 }
1393
1394                 depth = ext_depth(inode);
1395                 BUG_ON(path[depth].p_hdr == NULL);
1396                 ex = path[depth].p_ext;
1397                 next = ext4_ext_next_allocated_block(path);
1398
1399                 exists = 0;
1400                 if (!ex) {
1401                         /* there is no extent yet, so try to allocate
1402                          * all requested space */
1403                         start = block;
1404                         end = block + num;
1405                 } else if (le32_to_cpu(ex->ee_block) > block) {
1406                         /* need to allocate space before found extent */
1407                         start = block;
1408                         end = le32_to_cpu(ex->ee_block);
1409                         if (block + num < end)
1410                                 end = block + num;
1411                 } else if (block >= le32_to_cpu(ex->ee_block)
1412                                         + ext4_ext_get_actual_len(ex)) {
1413                         /* need to allocate space after found extent */
1414                         start = block;
1415                         end = block + num;
1416                         if (end >= next)
1417                                 end = next;
1418                 } else if (block >= le32_to_cpu(ex->ee_block)) {
1419                         /*
1420                          * some part of requested space is covered
1421                          * by found extent
1422                          */
1423                         start = block;
1424                         end = le32_to_cpu(ex->ee_block)
1425                                 + ext4_ext_get_actual_len(ex);
1426                         if (block + num < end)
1427                                 end = block + num;
1428                         exists = 1;
1429                 } else {
1430                         BUG();
1431                 }
1432                 BUG_ON(end <= start);
1433
1434                 if (!exists) {
1435                         cbex.ec_block = start;
1436                         cbex.ec_len = end - start;
1437                         cbex.ec_start = 0;
1438                         cbex.ec_type = EXT4_EXT_CACHE_GAP;
1439                 } else {
1440                         cbex.ec_block = le32_to_cpu(ex->ee_block);
1441                         cbex.ec_len = ext4_ext_get_actual_len(ex);
1442                         cbex.ec_start = ext_pblock(ex);
1443                         cbex.ec_type = EXT4_EXT_CACHE_EXTENT;
1444                 }
1445
1446                 BUG_ON(cbex.ec_len == 0);
1447                 err = func(inode, path, &cbex, cbdata);
1448                 ext4_ext_drop_refs(path);
1449
1450                 if (err < 0)
1451                         break;
1452                 if (err == EXT_REPEAT)
1453                         continue;
1454                 else if (err == EXT_BREAK) {
1455                         err = 0;
1456                         break;
1457                 }
1458
1459                 if (ext_depth(inode) != depth) {
1460                         /* depth was changed. we have to realloc path */
1461                         kfree(path);
1462                         path = NULL;
1463                 }
1464
1465                 block = cbex.ec_block + cbex.ec_len;
1466         }
1467
1468         if (path) {
1469                 ext4_ext_drop_refs(path);
1470                 kfree(path);
1471         }
1472
1473         return err;
1474 }
1475
1476 static void
1477 ext4_ext_put_in_cache(struct inode *inode, __u32 block,
1478                         __u32 len, __u32 start, int type)
1479 {
1480         struct ext4_ext_cache *cex;
1481         BUG_ON(len == 0);
1482         cex = &EXT4_I(inode)->i_cached_extent;
1483         cex->ec_type = type;
1484         cex->ec_block = block;
1485         cex->ec_len = len;
1486         cex->ec_start = start;
1487 }
1488
1489 /*
1490  * ext4_ext_put_gap_in_cache:
1491  * calculate boundaries of the gap that the requested block fits into
1492  * and cache this gap
1493  */
1494 static void
1495 ext4_ext_put_gap_in_cache(struct inode *inode, struct ext4_ext_path *path,
1496                                 unsigned long block)
1497 {
1498         int depth = ext_depth(inode);
1499         unsigned long lblock, len;
1500         struct ext4_extent *ex;
1501
1502         ex = path[depth].p_ext;
1503         if (ex == NULL) {
1504                 /* there is no extent yet, so gap is [0;-] */
1505                 lblock = 0;
1506                 len = EXT_MAX_BLOCK;
1507                 ext_debug("cache gap(whole file):");
1508         } else if (block < le32_to_cpu(ex->ee_block)) {
1509                 lblock = block;
1510                 len = le32_to_cpu(ex->ee_block) - block;
1511                 ext_debug("cache gap(before): %lu [%lu:%lu]",
1512                                 (unsigned long) block,
1513                                 (unsigned long) le32_to_cpu(ex->ee_block),
1514                                 (unsigned long) ext4_ext_get_actual_len(ex));
1515         } else if (block >= le32_to_cpu(ex->ee_block)
1516                         + ext4_ext_get_actual_len(ex)) {
1517                 lblock = le32_to_cpu(ex->ee_block)
1518                         + ext4_ext_get_actual_len(ex);
1519                 len = ext4_ext_next_allocated_block(path);
1520                 ext_debug("cache gap(after): [%lu:%lu] %lu",
1521                                 (unsigned long) le32_to_cpu(ex->ee_block),
1522                                 (unsigned long) ext4_ext_get_actual_len(ex),
1523                                 (unsigned long) block);
1524                 BUG_ON(len == lblock);
1525                 len = len - lblock;
1526         } else {
1527                 lblock = len = 0;
1528                 BUG();
1529         }
1530
1531         ext_debug(" -> %lu:%lu\n", (unsigned long) lblock, len);
1532         ext4_ext_put_in_cache(inode, lblock, len, 0, EXT4_EXT_CACHE_GAP);
1533 }
1534
1535 static int
1536 ext4_ext_in_cache(struct inode *inode, unsigned long block,
1537                         struct ext4_extent *ex)
1538 {
1539         struct ext4_ext_cache *cex;
1540
1541         cex = &EXT4_I(inode)->i_cached_extent;
1542
1543         /* has cache valid data? */
1544         if (cex->ec_type == EXT4_EXT_CACHE_NO)
1545                 return EXT4_EXT_CACHE_NO;
1546
1547         BUG_ON(cex->ec_type != EXT4_EXT_CACHE_GAP &&
1548                         cex->ec_type != EXT4_EXT_CACHE_EXTENT);
1549         if (block >= cex->ec_block && block < cex->ec_block + cex->ec_len) {
1550                 ex->ee_block = cpu_to_le32(cex->ec_block);
1551                 ext4_ext_store_pblock(ex, cex->ec_start);
1552                 ex->ee_len = cpu_to_le16(cex->ec_len);
1553                 ext_debug("%lu cached by %lu:%lu:%llu\n",
1554                                 (unsigned long) block,
1555                                 (unsigned long) cex->ec_block,
1556                                 (unsigned long) cex->ec_len,
1557                                 cex->ec_start);
1558                 return cex->ec_type;
1559         }
1560
1561         /* not in cache */
1562         return EXT4_EXT_CACHE_NO;
1563 }
1564
1565 /*
1566  * ext4_ext_rm_idx:
1567  * removes index from the index block.
1568  * It's used in truncate case only, thus all requests are for
1569  * last index in the block only.
1570  */
1571 int ext4_ext_rm_idx(handle_t *handle, struct inode *inode,
1572                         struct ext4_ext_path *path)
1573 {
1574         struct buffer_head *bh;
1575         int err;
1576         ext4_fsblk_t leaf;
1577
1578         /* free index block */
1579         path--;
1580         leaf = idx_pblock(path->p_idx);
1581         BUG_ON(path->p_hdr->eh_entries == 0);
1582         err = ext4_ext_get_access(handle, inode, path);
1583         if (err)
1584                 return err;
1585         path->p_hdr->eh_entries = cpu_to_le16(le16_to_cpu(path->p_hdr->eh_entries)-1);
1586         err = ext4_ext_dirty(handle, inode, path);
1587         if (err)
1588                 return err;
1589         ext_debug("index is empty, remove it, free block %llu\n", leaf);
1590         bh = sb_find_get_block(inode->i_sb, leaf);
1591         ext4_forget(handle, 1, inode, bh, leaf);
1592         ext4_free_blocks(handle, inode, leaf, 1);
1593         return err;
1594 }
1595
1596 /*
1597  * ext4_ext_calc_credits_for_insert:
1598  * This routine returns max. credits that the extent tree can consume.
1599  * It should be OK for low-performance paths like ->writepage()
1600  * To allow many writing processes to fit into a single transaction,
1601  * the caller should calculate credits under truncate_mutex and
1602  * pass the actual path.
1603  */
1604 int ext4_ext_calc_credits_for_insert(struct inode *inode,
1605                                                 struct ext4_ext_path *path)
1606 {
1607         int depth, needed;
1608
1609         if (path) {
1610                 /* probably there is space in leaf? */
1611                 depth = ext_depth(inode);
1612                 if (le16_to_cpu(path[depth].p_hdr->eh_entries)
1613                                 < le16_to_cpu(path[depth].p_hdr->eh_max))
1614                         return 1;
1615         }
1616
1617         /*
1618          * given 32-bit logical block (4294967296 blocks), max. tree
1619          * can be 4 levels in depth -- 4 * 340^4 == 53453440000.
1620          * Let's also add one more level for imbalance.
1621          */
1622         depth = 5;
1623
1624         /* allocation of new data block(s) */
1625         needed = 2;
1626
1627         /*
1628          * tree can be full, so it would need to grow in depth:
1629          * we need one credit to modify old root, credits for
1630          * new root will be added in split accounting
1631          */
1632         needed += 1;
1633
1634         /*
1635          * Index split can happen, we would need:
1636          *    allocate intermediate indexes (bitmap + group)
1637          *  + change two blocks at each level, but root (already included)
1638          */
1639         needed += (depth * 2) + (depth * 2);
1640
1641         /* any allocation modifies superblock */
1642         needed += 1;
1643
1644         return needed;
1645 }
1646
1647 static int ext4_remove_blocks(handle_t *handle, struct inode *inode,
1648                                 struct ext4_extent *ex,
1649                                 unsigned long from, unsigned long to)
1650 {
1651         struct buffer_head *bh;
1652         unsigned short ee_len =  ext4_ext_get_actual_len(ex);
1653         int i;
1654
1655 #ifdef EXTENTS_STATS
1656         {
1657                 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1658                 spin_lock(&sbi->s_ext_stats_lock);
1659                 sbi->s_ext_blocks += ee_len;
1660                 sbi->s_ext_extents++;
1661                 if (ee_len < sbi->s_ext_min)
1662                         sbi->s_ext_min = ee_len;
1663                 if (ee_len > sbi->s_ext_max)
1664                         sbi->s_ext_max = ee_len;
1665                 if (ext_depth(inode) > sbi->s_depth_max)
1666                         sbi->s_depth_max = ext_depth(inode);
1667                 spin_unlock(&sbi->s_ext_stats_lock);
1668         }
1669 #endif
1670         if (from >= le32_to_cpu(ex->ee_block)
1671             && to == le32_to_cpu(ex->ee_block) + ee_len - 1) {
1672                 /* tail removal */
1673                 unsigned long num;
1674                 ext4_fsblk_t start;
1675                 num = le32_to_cpu(ex->ee_block) + ee_len - from;
1676                 start = ext_pblock(ex) + ee_len - num;
1677                 ext_debug("free last %lu blocks starting %llu\n", num, start);
1678                 for (i = 0; i < num; i++) {
1679                         bh = sb_find_get_block(inode->i_sb, start + i);
1680                         ext4_forget(handle, 0, inode, bh, start + i);
1681                 }
1682                 ext4_free_blocks(handle, inode, start, num);
1683         } else if (from == le32_to_cpu(ex->ee_block)
1684                    && to <= le32_to_cpu(ex->ee_block) + ee_len - 1) {
1685                 printk("strange request: removal %lu-%lu from %u:%u\n",
1686                         from, to, le32_to_cpu(ex->ee_block), ee_len);
1687         } else {
1688                 printk("strange request: removal(2) %lu-%lu from %u:%u\n",
1689                         from, to, le32_to_cpu(ex->ee_block), ee_len);
1690         }
1691         return 0;
1692 }
1693
1694 static int
1695 ext4_ext_rm_leaf(handle_t *handle, struct inode *inode,
1696                 struct ext4_ext_path *path, unsigned long start)
1697 {
1698         int err = 0, correct_index = 0;
1699         int depth = ext_depth(inode), credits;
1700         struct ext4_extent_header *eh;
1701         unsigned a, b, block, num;
1702         unsigned long ex_ee_block;
1703         unsigned short ex_ee_len;
1704         unsigned uninitialized = 0;
1705         struct ext4_extent *ex;
1706
1707         ext_debug("truncate since %lu in leaf\n", start);
1708         if (!path[depth].p_hdr)
1709                 path[depth].p_hdr = ext_block_hdr(path[depth].p_bh);
1710         eh = path[depth].p_hdr;
1711         BUG_ON(eh == NULL);
1712         BUG_ON(le16_to_cpu(eh->eh_entries) > le16_to_cpu(eh->eh_max));
1713         BUG_ON(eh->eh_magic != EXT4_EXT_MAGIC);
1714
1715         /* find where to start removing */
1716         ex = EXT_LAST_EXTENT(eh);
1717
1718         ex_ee_block = le32_to_cpu(ex->ee_block);
1719         if (ext4_ext_is_uninitialized(ex))
1720                 uninitialized = 1;
1721         ex_ee_len = ext4_ext_get_actual_len(ex);
1722
1723         while (ex >= EXT_FIRST_EXTENT(eh) &&
1724                         ex_ee_block + ex_ee_len > start) {
1725                 ext_debug("remove ext %lu:%u\n", ex_ee_block, ex_ee_len);
1726                 path[depth].p_ext = ex;
1727
1728                 a = ex_ee_block > start ? ex_ee_block : start;
1729                 b = ex_ee_block + ex_ee_len - 1 < EXT_MAX_BLOCK ?
1730                         ex_ee_block + ex_ee_len - 1 : EXT_MAX_BLOCK;
1731
1732                 ext_debug("  border %u:%u\n", a, b);
1733
1734                 if (a != ex_ee_block && b != ex_ee_block + ex_ee_len - 1) {
1735                         block = 0;
1736                         num = 0;
1737                         BUG();
1738                 } else if (a != ex_ee_block) {
1739                         /* remove tail of the extent */
1740                         block = ex_ee_block;
1741                         num = a - block;
1742                 } else if (b != ex_ee_block + ex_ee_len - 1) {
1743                         /* remove head of the extent */
1744                         block = a;
1745                         num = b - a;
1746                         /* there is no "make a hole" API yet */
1747                         BUG();
1748                 } else {
1749                         /* remove whole extent: excellent! */
1750                         block = ex_ee_block;
1751                         num = 0;
1752                         BUG_ON(a != ex_ee_block);
1753                         BUG_ON(b != ex_ee_block + ex_ee_len - 1);
1754                 }
1755
1756                 /* at present, extent can't cross block group: */
1757                 /* leaf + bitmap + group desc + sb + inode */
1758                 credits = 5;
1759                 if (ex == EXT_FIRST_EXTENT(eh)) {
1760                         correct_index = 1;
1761                         credits += (ext_depth(inode)) + 1;
1762                 }
1763 #ifdef CONFIG_QUOTA
1764                 credits += 2 * EXT4_QUOTA_TRANS_BLOCKS(inode->i_sb);
1765 #endif
1766
1767                 handle = ext4_ext_journal_restart(handle, credits);
1768                 if (IS_ERR(handle)) {
1769                         err = PTR_ERR(handle);
1770                         goto out;
1771                 }
1772
1773                 err = ext4_ext_get_access(handle, inode, path + depth);
1774                 if (err)
1775                         goto out;
1776
1777                 err = ext4_remove_blocks(handle, inode, ex, a, b);
1778                 if (err)
1779                         goto out;
1780
1781                 if (num == 0) {
1782                         /* this extent is removed; mark slot entirely unused */
1783                         ext4_ext_store_pblock(ex, 0);
1784                         eh->eh_entries = cpu_to_le16(le16_to_cpu(eh->eh_entries)-1);
1785                 }
1786
1787                 ex->ee_block = cpu_to_le32(block);
1788                 ex->ee_len = cpu_to_le16(num);
1789                 if (uninitialized)
1790                         ext4_ext_mark_uninitialized(ex);
1791
1792                 err = ext4_ext_dirty(handle, inode, path + depth);
1793                 if (err)
1794                         goto out;
1795
1796                 ext_debug("new extent: %u:%u:%llu\n", block, num,
1797                                 ext_pblock(ex));
1798                 ex--;
1799                 ex_ee_block = le32_to_cpu(ex->ee_block);
1800                 ex_ee_len = ext4_ext_get_actual_len(ex);
1801         }
1802
1803         if (correct_index && eh->eh_entries)
1804                 err = ext4_ext_correct_indexes(handle, inode, path);
1805
1806         /* if this leaf is free, then we should
1807          * remove it from index block above */
1808         if (err == 0 && eh->eh_entries == 0 && path[depth].p_bh != NULL)
1809                 err = ext4_ext_rm_idx(handle, inode, path + depth);
1810
1811 out:
1812         return err;
1813 }
1814
1815 /*
1816  * ext4_ext_more_to_rm:
1817  * returns 1 if current index has to be freed (even partial)
1818  */
1819 static int
1820 ext4_ext_more_to_rm(struct ext4_ext_path *path)
1821 {
1822         BUG_ON(path->p_idx == NULL);
1823
1824         if (path->p_idx < EXT_FIRST_INDEX(path->p_hdr))
1825                 return 0;
1826
1827         /*
1828          * if truncate on deeper level happened, it wasn't partial,
1829          * so we have to consider current index for truncation
1830          */
1831         if (le16_to_cpu(path->p_hdr->eh_entries) == path->p_block)
1832                 return 0;
1833         return 1;
1834 }
1835
1836 int ext4_ext_remove_space(struct inode *inode, unsigned long start)
1837 {
1838         struct super_block *sb = inode->i_sb;
1839         int depth = ext_depth(inode);
1840         struct ext4_ext_path *path;
1841         handle_t *handle;
1842         int i = 0, err = 0;
1843
1844         ext_debug("truncate since %lu\n", start);
1845
1846         /* probably first extent we're gonna free will be last in block */
1847         handle = ext4_journal_start(inode, depth + 1);
1848         if (IS_ERR(handle))
1849                 return PTR_ERR(handle);
1850
1851         ext4_ext_invalidate_cache(inode);
1852
1853         /*
1854          * We start scanning from right side, freeing all the blocks
1855          * after i_size and walking into the tree depth-wise.
1856          */
1857         path = kzalloc(sizeof(struct ext4_ext_path) * (depth + 1), GFP_KERNEL);
1858         if (path == NULL) {
1859                 ext4_journal_stop(handle);
1860                 return -ENOMEM;
1861         }
1862         path[0].p_hdr = ext_inode_hdr(inode);
1863         if (ext4_ext_check_header(__FUNCTION__, inode, path[0].p_hdr)) {
1864                 err = -EIO;
1865                 goto out;
1866         }
1867         path[0].p_depth = depth;
1868
1869         while (i >= 0 && err == 0) {
1870                 if (i == depth) {
1871                         /* this is leaf block */
1872                         err = ext4_ext_rm_leaf(handle, inode, path, start);
1873                         /* root level has p_bh == NULL, brelse() eats this */
1874                         brelse(path[i].p_bh);
1875                         path[i].p_bh = NULL;
1876                         i--;
1877                         continue;
1878                 }
1879
1880                 /* this is index block */
1881                 if (!path[i].p_hdr) {
1882                         ext_debug("initialize header\n");
1883                         path[i].p_hdr = ext_block_hdr(path[i].p_bh);
1884                         if (ext4_ext_check_header(__FUNCTION__, inode,
1885                                                         path[i].p_hdr)) {
1886                                 err = -EIO;
1887                                 goto out;
1888                         }
1889                 }
1890
1891                 BUG_ON(le16_to_cpu(path[i].p_hdr->eh_entries)
1892                            > le16_to_cpu(path[i].p_hdr->eh_max));
1893                 BUG_ON(path[i].p_hdr->eh_magic != EXT4_EXT_MAGIC);
1894
1895                 if (!path[i].p_idx) {
1896                         /* this level hasn't been touched yet */
1897                         path[i].p_idx = EXT_LAST_INDEX(path[i].p_hdr);
1898                         path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries)+1;
1899                         ext_debug("init index ptr: hdr 0x%p, num %d\n",
1900                                   path[i].p_hdr,
1901                                   le16_to_cpu(path[i].p_hdr->eh_entries));
1902                 } else {
1903                         /* we were already here, see at next index */
1904                         path[i].p_idx--;
1905                 }
1906
1907                 ext_debug("level %d - index, first 0x%p, cur 0x%p\n",
1908                                 i, EXT_FIRST_INDEX(path[i].p_hdr),
1909                                 path[i].p_idx);
1910                 if (ext4_ext_more_to_rm(path + i)) {
1911                         /* go to the next level */
1912                         ext_debug("move to level %d (block %llu)\n",
1913                                   i + 1, idx_pblock(path[i].p_idx));
1914                         memset(path + i + 1, 0, sizeof(*path));
1915                         path[i+1].p_bh =
1916                                 sb_bread(sb, idx_pblock(path[i].p_idx));
1917                         if (!path[i+1].p_bh) {
1918                                 /* should we reset i_size? */
1919                                 err = -EIO;
1920                                 break;
1921                         }
1922
1923                         /* save actual number of indexes since this
1924                          * number is changed at the next iteration */
1925                         path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries);
1926                         i++;
1927                 } else {
1928                         /* we finished processing this index, go up */
1929                         if (path[i].p_hdr->eh_entries == 0 && i > 0) {
1930                                 /* index is empty, remove it;
1931                                  * handle must be already prepared by the
1932                                  * truncatei_leaf() */
1933                                 err = ext4_ext_rm_idx(handle, inode, path + i);
1934                         }
1935                         /* root level has p_bh == NULL, brelse() eats this */
1936                         brelse(path[i].p_bh);
1937                         path[i].p_bh = NULL;
1938                         i--;
1939                         ext_debug("return to level %d\n", i);
1940                 }
1941         }
1942
1943         /* TODO: flexible tree reduction should be here */
1944         if (path->p_hdr->eh_entries == 0) {
1945                 /*
1946                  * truncate to zero freed all the tree,
1947                  * so we need to correct eh_depth
1948                  */
1949                 err = ext4_ext_get_access(handle, inode, path);
1950                 if (err == 0) {
1951                         ext_inode_hdr(inode)->eh_depth = 0;
1952                         ext_inode_hdr(inode)->eh_max =
1953                                 cpu_to_le16(ext4_ext_space_root(inode));
1954                         err = ext4_ext_dirty(handle, inode, path);
1955                 }
1956         }
1957 out:
1958         ext4_ext_tree_changed(inode);
1959         ext4_ext_drop_refs(path);
1960         kfree(path);
1961         ext4_journal_stop(handle);
1962
1963         return err;
1964 }
1965
1966 /*
1967  * called at mount time
1968  */
1969 void ext4_ext_init(struct super_block *sb)
1970 {
1971         /*
1972          * possible initialization would be here
1973          */
1974
1975         if (test_opt(sb, EXTENTS)) {
1976                 printk("EXT4-fs: file extents enabled");
1977 #ifdef AGGRESSIVE_TEST
1978                 printk(", aggressive tests");
1979 #endif
1980 #ifdef CHECK_BINSEARCH
1981                 printk(", check binsearch");
1982 #endif
1983 #ifdef EXTENTS_STATS
1984                 printk(", stats");
1985 #endif
1986                 printk("\n");
1987 #ifdef EXTENTS_STATS
1988                 spin_lock_init(&EXT4_SB(sb)->s_ext_stats_lock);
1989                 EXT4_SB(sb)->s_ext_min = 1 << 30;
1990                 EXT4_SB(sb)->s_ext_max = 0;
1991 #endif
1992         }
1993 }
1994
1995 /*
1996  * called at umount time
1997  */
1998 void ext4_ext_release(struct super_block *sb)
1999 {
2000         if (!test_opt(sb, EXTENTS))
2001                 return;
2002
2003 #ifdef EXTENTS_STATS
2004         if (EXT4_SB(sb)->s_ext_blocks && EXT4_SB(sb)->s_ext_extents) {
2005                 struct ext4_sb_info *sbi = EXT4_SB(sb);
2006                 printk(KERN_ERR "EXT4-fs: %lu blocks in %lu extents (%lu ave)\n",
2007                         sbi->s_ext_blocks, sbi->s_ext_extents,
2008                         sbi->s_ext_blocks / sbi->s_ext_extents);
2009                 printk(KERN_ERR "EXT4-fs: extents: %lu min, %lu max, max depth %lu\n",
2010                         sbi->s_ext_min, sbi->s_ext_max, sbi->s_depth_max);
2011         }
2012 #endif
2013 }
2014
2015 int ext4_ext_get_blocks(handle_t *handle, struct inode *inode,
2016                         ext4_fsblk_t iblock,
2017                         unsigned long max_blocks, struct buffer_head *bh_result,
2018                         int create, int extend_disksize)
2019 {
2020         struct ext4_ext_path *path = NULL;
2021         struct ext4_extent newex, *ex;
2022         ext4_fsblk_t goal, newblock;
2023         int err = 0, depth;
2024         unsigned long allocated = 0;
2025
2026         __clear_bit(BH_New, &bh_result->b_state);
2027         ext_debug("blocks %d/%lu requested for inode %u\n", (int) iblock,
2028                         max_blocks, (unsigned) inode->i_ino);
2029         mutex_lock(&EXT4_I(inode)->truncate_mutex);
2030
2031         /* check in cache */
2032         goal = ext4_ext_in_cache(inode, iblock, &newex);
2033         if (goal) {
2034                 if (goal == EXT4_EXT_CACHE_GAP) {
2035                         if (!create) {
2036                                 /* block isn't allocated yet and
2037                                  * user doesn't want to allocate it */
2038                                 goto out2;
2039                         }
2040                         /* we should allocate requested block */
2041                 } else if (goal == EXT4_EXT_CACHE_EXTENT) {
2042                         /* block is already allocated */
2043                         newblock = iblock
2044                                    - le32_to_cpu(newex.ee_block)
2045                                    + ext_pblock(&newex);
2046                         /* number of remaining blocks in the extent */
2047                         allocated = le16_to_cpu(newex.ee_len) -
2048                                         (iblock - le32_to_cpu(newex.ee_block));
2049                         goto out;
2050                 } else {
2051                         BUG();
2052                 }
2053         }
2054
2055         /* find extent for this block */
2056         path = ext4_ext_find_extent(inode, iblock, NULL);
2057         if (IS_ERR(path)) {
2058                 err = PTR_ERR(path);
2059                 path = NULL;
2060                 goto out2;
2061         }
2062
2063         depth = ext_depth(inode);
2064
2065         /*
2066          * consistent leaf must not be empty;
2067          * this situation is possible, though, _during_ tree modification;
2068          * this is why assert can't be put in ext4_ext_find_extent()
2069          */
2070         BUG_ON(path[depth].p_ext == NULL && depth != 0);
2071
2072         ex = path[depth].p_ext;
2073         if (ex) {
2074                 unsigned long ee_block = le32_to_cpu(ex->ee_block);
2075                 ext4_fsblk_t ee_start = ext_pblock(ex);
2076                 unsigned short ee_len;
2077
2078                 /*
2079                  * Allow future support for preallocated extents to be added
2080                  * as an RO_COMPAT feature:
2081                  * Uninitialized extents are treated as holes, except that
2082                  * we avoid (fail) allocating new blocks during a write.
2083                  */
2084                 if (le16_to_cpu(ex->ee_len) > EXT_MAX_LEN)
2085                         goto out2;
2086                 ee_len = ext4_ext_get_actual_len(ex);
2087                 /* if found extent covers block, simply return it */
2088                 if (iblock >= ee_block && iblock < ee_block + ee_len) {
2089                         newblock = iblock - ee_block + ee_start;
2090                         /* number of remaining blocks in the extent */
2091                         allocated = ee_len - (iblock - ee_block);
2092                         ext_debug("%d fit into %lu:%d -> %llu\n", (int) iblock,
2093                                         ee_block, ee_len, newblock);
2094                         /* Do not put uninitialized extent in the cache */
2095                         if (!ext4_ext_is_uninitialized(ex))
2096                                 ext4_ext_put_in_cache(inode, ee_block,
2097                                                         ee_len, ee_start,
2098                                                         EXT4_EXT_CACHE_EXTENT);
2099                         goto out;
2100                 }
2101         }
2102
2103         /*
2104          * requested block isn't allocated yet;
2105          * we couldn't try to create block if create flag is zero
2106          */
2107         if (!create) {
2108                 /* put just found gap into cache to speed up
2109                  * subsequent requests */
2110                 ext4_ext_put_gap_in_cache(inode, path, iblock);
2111                 goto out2;
2112         }
2113         /*
2114          * Okay, we need to do block allocation.  Lazily initialize the block
2115          * allocation info here if necessary.
2116          */
2117         if (S_ISREG(inode->i_mode) && (!EXT4_I(inode)->i_block_alloc_info))
2118                 ext4_init_block_alloc_info(inode);
2119
2120         /* allocate new block */
2121         goal = ext4_ext_find_goal(inode, path, iblock);
2122
2123         /* Check if we can really insert (iblock)::(iblock+max_blocks) extent */
2124         newex.ee_block = cpu_to_le32(iblock);
2125         newex.ee_len = cpu_to_le16(max_blocks);
2126         err = ext4_ext_check_overlap(inode, &newex, path);
2127         if (err)
2128                 allocated = le16_to_cpu(newex.ee_len);
2129         else
2130                 allocated = max_blocks;
2131         newblock = ext4_new_blocks(handle, inode, goal, &allocated, &err);
2132         if (!newblock)
2133                 goto out2;
2134         ext_debug("allocate new block: goal %llu, found %llu/%lu\n",
2135                         goal, newblock, allocated);
2136
2137         /* try to insert new extent into found leaf and return */
2138         ext4_ext_store_pblock(&newex, newblock);
2139         newex.ee_len = cpu_to_le16(allocated);
2140         if (create == EXT4_CREATE_UNINITIALIZED_EXT)  /* Mark uninitialized */
2141                 ext4_ext_mark_uninitialized(&newex);
2142         err = ext4_ext_insert_extent(handle, inode, path, &newex);
2143         if (err) {
2144                 /* free data blocks we just allocated */
2145                 ext4_free_blocks(handle, inode, ext_pblock(&newex),
2146                                         le16_to_cpu(newex.ee_len));
2147                 goto out2;
2148         }
2149
2150         if (extend_disksize && inode->i_size > EXT4_I(inode)->i_disksize)
2151                 EXT4_I(inode)->i_disksize = inode->i_size;
2152
2153         /* previous routine could use block we allocated */
2154         newblock = ext_pblock(&newex);
2155         __set_bit(BH_New, &bh_result->b_state);
2156
2157         /* Cache only when it is _not_ an uninitialized extent */
2158         if (create != EXT4_CREATE_UNINITIALIZED_EXT)
2159                 ext4_ext_put_in_cache(inode, iblock, allocated, newblock,
2160                                                 EXT4_EXT_CACHE_EXTENT);
2161 out:
2162         if (allocated > max_blocks)
2163                 allocated = max_blocks;
2164         ext4_ext_show_leaf(inode, path);
2165         __set_bit(BH_Mapped, &bh_result->b_state);
2166         bh_result->b_bdev = inode->i_sb->s_bdev;
2167         bh_result->b_blocknr = newblock;
2168 out2:
2169         if (path) {
2170                 ext4_ext_drop_refs(path);
2171                 kfree(path);
2172         }
2173         mutex_unlock(&EXT4_I(inode)->truncate_mutex);
2174
2175         return err ? err : allocated;
2176 }
2177
2178 void ext4_ext_truncate(struct inode * inode, struct page *page)
2179 {
2180         struct address_space *mapping = inode->i_mapping;
2181         struct super_block *sb = inode->i_sb;
2182         unsigned long last_block;
2183         handle_t *handle;
2184         int err = 0;
2185
2186         /*
2187          * probably first extent we're gonna free will be last in block
2188          */
2189         err = ext4_writepage_trans_blocks(inode) + 3;
2190         handle = ext4_journal_start(inode, err);
2191         if (IS_ERR(handle)) {
2192                 if (page) {
2193                         clear_highpage(page);
2194                         flush_dcache_page(page);
2195                         unlock_page(page);
2196                         page_cache_release(page);
2197                 }
2198                 return;
2199         }
2200
2201         if (page)
2202                 ext4_block_truncate_page(handle, page, mapping, inode->i_size);
2203
2204         mutex_lock(&EXT4_I(inode)->truncate_mutex);
2205         ext4_ext_invalidate_cache(inode);
2206
2207         /*
2208          * TODO: optimization is possible here.
2209          * Probably we need not scan at all,
2210          * because page truncation is enough.
2211          */
2212         if (ext4_orphan_add(handle, inode))
2213                 goto out_stop;
2214
2215         /* we have to know where to truncate from in crash case */
2216         EXT4_I(inode)->i_disksize = inode->i_size;
2217         ext4_mark_inode_dirty(handle, inode);
2218
2219         last_block = (inode->i_size + sb->s_blocksize - 1)
2220                         >> EXT4_BLOCK_SIZE_BITS(sb);
2221         err = ext4_ext_remove_space(inode, last_block);
2222
2223         /* In a multi-transaction truncate, we only make the final
2224          * transaction synchronous. */
2225         if (IS_SYNC(inode))
2226                 handle->h_sync = 1;
2227
2228 out_stop:
2229         /*
2230          * If this was a simple ftruncate() and the file will remain alive,
2231          * then we need to clear up the orphan record which we created above.
2232          * However, if this was a real unlink then we were called by
2233          * ext4_delete_inode(), and we allow that function to clean up the
2234          * orphan info for us.
2235          */
2236         if (inode->i_nlink)
2237                 ext4_orphan_del(handle, inode);
2238
2239         mutex_unlock(&EXT4_I(inode)->truncate_mutex);
2240         ext4_journal_stop(handle);
2241 }
2242
2243 /*
2244  * ext4_ext_writepage_trans_blocks:
2245  * calculate max number of blocks we could modify
2246  * in order to allocate new block for an inode
2247  */
2248 int ext4_ext_writepage_trans_blocks(struct inode *inode, int num)
2249 {
2250         int needed;
2251
2252         needed = ext4_ext_calc_credits_for_insert(inode, NULL);
2253
2254         /* caller wants to allocate num blocks, but note it includes sb */
2255         needed = needed * num - (num - 1);
2256
2257 #ifdef CONFIG_QUOTA
2258         needed += 2 * EXT4_QUOTA_TRANS_BLOCKS(inode->i_sb);
2259 #endif
2260
2261         return needed;
2262 }
2263
2264 /*
2265  * preallocate space for a file. This implements ext4's fallocate inode
2266  * operation, which gets called from sys_fallocate system call.
2267  * For block-mapped files, posix_fallocate should fall back to the method
2268  * of writing zeroes to the required new blocks (the same behavior which is
2269  * expected for file systems which do not support fallocate() system call).
2270  */
2271 long ext4_fallocate(struct inode *inode, int mode, loff_t offset, loff_t len)
2272 {
2273         handle_t *handle;
2274         ext4_fsblk_t block, max_blocks;
2275         ext4_fsblk_t nblocks = 0;
2276         int ret = 0;
2277         int ret2 = 0;
2278         int retries = 0;
2279         struct buffer_head map_bh;
2280         unsigned int credits, blkbits = inode->i_blkbits;
2281
2282         /*
2283          * currently supporting (pre)allocate mode for extent-based
2284          * files _only_
2285          */
2286         if (!(EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL))
2287                 return -EOPNOTSUPP;
2288
2289         /* preallocation to directories is currently not supported */
2290         if (S_ISDIR(inode->i_mode))
2291                 return -ENODEV;
2292
2293         block = offset >> blkbits;
2294         max_blocks = (EXT4_BLOCK_ALIGN(len + offset, blkbits) >> blkbits)
2295                         - block;
2296
2297         /*
2298          * credits to insert 1 extent into extent tree + buffers to be able to
2299          * modify 1 super block, 1 block bitmap and 1 group descriptor.
2300          */
2301         credits = EXT4_DATA_TRANS_BLOCKS(inode->i_sb) + 3;
2302 retry:
2303         while (ret >= 0 && ret < max_blocks) {
2304                 block = block + ret;
2305                 max_blocks = max_blocks - ret;
2306                 handle = ext4_journal_start(inode, credits);
2307                 if (IS_ERR(handle)) {
2308                         ret = PTR_ERR(handle);
2309                         break;
2310                 }
2311
2312                 ret = ext4_ext_get_blocks(handle, inode, block,
2313                                           max_blocks, &map_bh,
2314                                           EXT4_CREATE_UNINITIALIZED_EXT, 0);
2315                 WARN_ON(!ret);
2316                 if (!ret) {
2317                         ext4_error(inode->i_sb, "ext4_fallocate",
2318                                    "ext4_ext_get_blocks returned 0! inode#%lu"
2319                                    ", block=%llu, max_blocks=%llu",
2320                                    inode->i_ino, block, max_blocks);
2321                         ret = -EIO;
2322                         ext4_mark_inode_dirty(handle, inode);
2323                         ret2 = ext4_journal_stop(handle);
2324                         break;
2325                 }
2326                 if (ret > 0) {
2327                         /* check wrap through sign-bit/zero here */
2328                         if ((block + ret) < 0 || (block + ret) < block) {
2329                                 ret = -EIO;
2330                                 ext4_mark_inode_dirty(handle, inode);
2331                                 ret2 = ext4_journal_stop(handle);
2332                                 break;
2333                         }
2334                         if (buffer_new(&map_bh) && ((block + ret) >
2335                             (EXT4_BLOCK_ALIGN(i_size_read(inode), blkbits)
2336                             >> blkbits)))
2337                                         nblocks = nblocks + ret;
2338                 }
2339
2340                 /* Update ctime if new blocks get allocated */
2341                 if (nblocks) {
2342                         struct timespec now;
2343
2344                         now = current_fs_time(inode->i_sb);
2345                         if (!timespec_equal(&inode->i_ctime, &now))
2346                                 inode->i_ctime = now;
2347                 }
2348
2349                 ext4_mark_inode_dirty(handle, inode);
2350                 ret2 = ext4_journal_stop(handle);
2351                 if (ret2)
2352                         break;
2353         }
2354
2355         if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
2356                 goto retry;
2357
2358         /*
2359          * Time to update the file size.
2360          * Update only when preallocation was requested beyond the file size.
2361          */
2362         if (!(mode & FALLOC_FL_KEEP_SIZE) &&
2363             (offset + len) > i_size_read(inode)) {
2364                 if (ret > 0) {
2365                         /*
2366                          * if no error, we assume preallocation succeeded
2367                          * completely
2368                          */
2369                         mutex_lock(&inode->i_mutex);
2370                         i_size_write(inode, offset + len);
2371                         EXT4_I(inode)->i_disksize = i_size_read(inode);
2372                         mutex_unlock(&inode->i_mutex);
2373                 } else if (ret < 0 && nblocks) {
2374                         /* Handle partial allocation scenario */
2375                         loff_t newsize;
2376
2377                         mutex_lock(&inode->i_mutex);
2378                         newsize  = (nblocks << blkbits) + i_size_read(inode);
2379                         i_size_write(inode, EXT4_BLOCK_ALIGN(newsize, blkbits));
2380                         EXT4_I(inode)->i_disksize = i_size_read(inode);
2381                         mutex_unlock(&inode->i_mutex);
2382                 }
2383         }
2384
2385         return ret > 0 ? ret2 : ret;
2386 }