]> nv-tegra.nvidia Code Review - linux-2.6.git/blob - fs/ext4/extents.c
[PATCH] ext4: fix credit calculation in ext4_ext_calc_credits_for_insert
[linux-2.6.git] / 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/smp_lock.h>
38 #include <linux/highuid.h>
39 #include <linux/pagemap.h>
40 #include <linux/quotaops.h>
41 #include <linux/string.h>
42 #include <linux/slab.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 inline 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 inline 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 inline 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 inline 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                 if ((ex = path[depth].p_ext))
190                         return ext_pblock(ex)+(block-le32_to_cpu(ex->ee_block));
191
192                 /* it looks like index is empty;
193                  * try to find starting block from index itself */
194                 if (path[depth].p_bh)
195                         return path[depth].p_bh->b_blocknr;
196         }
197
198         /* OK. use inode's group */
199         bg_start = (ei->i_block_group * EXT4_BLOCKS_PER_GROUP(inode->i_sb)) +
200                 le32_to_cpu(EXT4_SB(inode->i_sb)->s_es->s_first_data_block);
201         colour = (current->pid % 16) *
202                         (EXT4_BLOCKS_PER_GROUP(inode->i_sb) / 16);
203         return bg_start + colour + block;
204 }
205
206 static ext4_fsblk_t
207 ext4_ext_new_block(handle_t *handle, struct inode *inode,
208                         struct ext4_ext_path *path,
209                         struct ext4_extent *ex, int *err)
210 {
211         ext4_fsblk_t goal, newblock;
212
213         goal = ext4_ext_find_goal(inode, path, le32_to_cpu(ex->ee_block));
214         newblock = ext4_new_block(handle, inode, goal, err);
215         return newblock;
216 }
217
218 static inline int ext4_ext_space_block(struct inode *inode)
219 {
220         int size;
221
222         size = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
223                         / sizeof(struct ext4_extent);
224 #ifdef AGRESSIVE_TEST
225         if (size > 6)
226                 size = 6;
227 #endif
228         return size;
229 }
230
231 static inline int ext4_ext_space_block_idx(struct inode *inode)
232 {
233         int size;
234
235         size = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
236                         / sizeof(struct ext4_extent_idx);
237 #ifdef AGRESSIVE_TEST
238         if (size > 5)
239                 size = 5;
240 #endif
241         return size;
242 }
243
244 static inline int ext4_ext_space_root(struct inode *inode)
245 {
246         int size;
247
248         size = sizeof(EXT4_I(inode)->i_data);
249         size -= sizeof(struct ext4_extent_header);
250         size /= sizeof(struct ext4_extent);
251 #ifdef AGRESSIVE_TEST
252         if (size > 3)
253                 size = 3;
254 #endif
255         return size;
256 }
257
258 static inline int ext4_ext_space_root_idx(struct inode *inode)
259 {
260         int size;
261
262         size = sizeof(EXT4_I(inode)->i_data);
263         size -= sizeof(struct ext4_extent_header);
264         size /= sizeof(struct ext4_extent_idx);
265 #ifdef AGRESSIVE_TEST
266         if (size > 4)
267                 size = 4;
268 #endif
269         return size;
270 }
271
272 #ifdef EXT_DEBUG
273 static void ext4_ext_show_path(struct inode *inode, struct ext4_ext_path *path)
274 {
275         int k, l = path->p_depth;
276
277         ext_debug("path:");
278         for (k = 0; k <= l; k++, path++) {
279                 if (path->p_idx) {
280                   ext_debug("  %d->%llu", le32_to_cpu(path->p_idx->ei_block),
281                             idx_pblock(path->p_idx));
282                 } else if (path->p_ext) {
283                         ext_debug("  %d:%d:%llu ",
284                                   le32_to_cpu(path->p_ext->ee_block),
285                                   le16_to_cpu(path->p_ext->ee_len),
286                                   ext_pblock(path->p_ext));
287                 } else
288                         ext_debug("  []");
289         }
290         ext_debug("\n");
291 }
292
293 static void ext4_ext_show_leaf(struct inode *inode, struct ext4_ext_path *path)
294 {
295         int depth = ext_depth(inode);
296         struct ext4_extent_header *eh;
297         struct ext4_extent *ex;
298         int i;
299
300         if (!path)
301                 return;
302
303         eh = path[depth].p_hdr;
304         ex = EXT_FIRST_EXTENT(eh);
305
306         for (i = 0; i < le16_to_cpu(eh->eh_entries); i++, ex++) {
307                 ext_debug("%d:%d:%llu ", le32_to_cpu(ex->ee_block),
308                           le16_to_cpu(ex->ee_len), ext_pblock(ex));
309         }
310         ext_debug("\n");
311 }
312 #else
313 #define ext4_ext_show_path(inode,path)
314 #define ext4_ext_show_leaf(inode,path)
315 #endif
316
317 static void ext4_ext_drop_refs(struct ext4_ext_path *path)
318 {
319         int depth = path->p_depth;
320         int i;
321
322         for (i = 0; i <= depth; i++, path++)
323                 if (path->p_bh) {
324                         brelse(path->p_bh);
325                         path->p_bh = NULL;
326                 }
327 }
328
329 /*
330  * ext4_ext_binsearch_idx:
331  * binary search for the closest index of the given block
332  */
333 static void
334 ext4_ext_binsearch_idx(struct inode *inode, struct ext4_ext_path *path, int block)
335 {
336         struct ext4_extent_header *eh = path->p_hdr;
337         struct ext4_extent_idx *r, *l, *m;
338
339         BUG_ON(eh->eh_magic != EXT4_EXT_MAGIC);
340         BUG_ON(le16_to_cpu(eh->eh_entries) > le16_to_cpu(eh->eh_max));
341         BUG_ON(le16_to_cpu(eh->eh_entries) <= 0);
342
343         ext_debug("binsearch for %d(idx):  ", block);
344
345         l = EXT_FIRST_INDEX(eh) + 1;
346         r = EXT_FIRST_INDEX(eh) + le16_to_cpu(eh->eh_entries) - 1;
347         while (l <= r) {
348                 m = l + (r - l) / 2;
349                 if (block < le32_to_cpu(m->ei_block))
350                         r = m - 1;
351                 else
352                         l = m + 1;
353                 ext_debug("%p(%u):%p(%u):%p(%u) ", l, l->ei_block,
354                                 m, m->ei_block, r, r->ei_block);
355         }
356
357         path->p_idx = l - 1;
358         ext_debug("  -> %d->%lld ", le32_to_cpu(path->p_idx->ei_block),
359                   idx_block(path->p_idx));
360
361 #ifdef CHECK_BINSEARCH
362         {
363                 struct ext4_extent_idx *chix, *ix;
364                 int k;
365
366                 chix = ix = EXT_FIRST_INDEX(eh);
367                 for (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ix++) {
368                   if (k != 0 &&
369                       le32_to_cpu(ix->ei_block) <= le32_to_cpu(ix[-1].ei_block)) {
370                                 printk("k=%d, ix=0x%p, first=0x%p\n", k,
371                                         ix, EXT_FIRST_INDEX(eh));
372                                 printk("%u <= %u\n",
373                                        le32_to_cpu(ix->ei_block),
374                                        le32_to_cpu(ix[-1].ei_block));
375                         }
376                         BUG_ON(k && le32_to_cpu(ix->ei_block)
377                                            <= le32_to_cpu(ix[-1].ei_block));
378                         if (block < le32_to_cpu(ix->ei_block))
379                                 break;
380                         chix = ix;
381                 }
382                 BUG_ON(chix != path->p_idx);
383         }
384 #endif
385
386 }
387
388 /*
389  * ext4_ext_binsearch:
390  * binary search for closest extent of the given block
391  */
392 static void
393 ext4_ext_binsearch(struct inode *inode, struct ext4_ext_path *path, int block)
394 {
395         struct ext4_extent_header *eh = path->p_hdr;
396         struct ext4_extent *r, *l, *m;
397
398         BUG_ON(eh->eh_magic != EXT4_EXT_MAGIC);
399         BUG_ON(le16_to_cpu(eh->eh_entries) > le16_to_cpu(eh->eh_max));
400
401         if (eh->eh_entries == 0) {
402                 /*
403                  * this leaf is empty:
404                  * we get such a leaf in split/add case
405                  */
406                 return;
407         }
408
409         ext_debug("binsearch for %d:  ", block);
410
411         l = EXT_FIRST_EXTENT(eh) + 1;
412         r = EXT_FIRST_EXTENT(eh) + le16_to_cpu(eh->eh_entries) - 1;
413
414         while (l <= r) {
415                 m = l + (r - l) / 2;
416                 if (block < le32_to_cpu(m->ee_block))
417                         r = m - 1;
418                 else
419                         l = m + 1;
420                 ext_debug("%p(%u):%p(%u):%p(%u) ", l, l->ee_block,
421                                 m, m->ee_block, r, r->ee_block);
422         }
423
424         path->p_ext = l - 1;
425         ext_debug("  -> %d:%llu:%d ",
426                         le32_to_cpu(path->p_ext->ee_block),
427                         ext_pblock(path->p_ext),
428                         le16_to_cpu(path->p_ext->ee_len));
429
430 #ifdef CHECK_BINSEARCH
431         {
432                 struct ext4_extent *chex, *ex;
433                 int k;
434
435                 chex = ex = EXT_FIRST_EXTENT(eh);
436                 for (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ex++) {
437                         BUG_ON(k && le32_to_cpu(ex->ee_block)
438                                           <= le32_to_cpu(ex[-1].ee_block));
439                         if (block < le32_to_cpu(ex->ee_block))
440                                 break;
441                         chex = ex;
442                 }
443                 BUG_ON(chex != path->p_ext);
444         }
445 #endif
446
447 }
448
449 int ext4_ext_tree_init(handle_t *handle, struct inode *inode)
450 {
451         struct ext4_extent_header *eh;
452
453         eh = ext_inode_hdr(inode);
454         eh->eh_depth = 0;
455         eh->eh_entries = 0;
456         eh->eh_magic = EXT4_EXT_MAGIC;
457         eh->eh_max = cpu_to_le16(ext4_ext_space_root(inode));
458         ext4_mark_inode_dirty(handle, inode);
459         ext4_ext_invalidate_cache(inode);
460         return 0;
461 }
462
463 struct ext4_ext_path *
464 ext4_ext_find_extent(struct inode *inode, int block, struct ext4_ext_path *path)
465 {
466         struct ext4_extent_header *eh;
467         struct buffer_head *bh;
468         short int depth, i, ppos = 0, alloc = 0;
469
470         eh = ext_inode_hdr(inode);
471         BUG_ON(eh == NULL);
472         if (ext4_ext_check_header(__FUNCTION__, inode, eh))
473                 return ERR_PTR(-EIO);
474
475         i = depth = ext_depth(inode);
476
477         /* account possible depth increase */
478         if (!path) {
479                 path = kmalloc(sizeof(struct ext4_ext_path) * (depth + 2),
480                                 GFP_NOFS);
481                 if (!path)
482                         return ERR_PTR(-ENOMEM);
483                 alloc = 1;
484         }
485         memset(path, 0, sizeof(struct ext4_ext_path) * (depth + 1));
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         if ((err = ext4_ext_get_access(handle, inode, curp)))
547                 return err;
548
549         BUG_ON(logical == le32_to_cpu(curp->p_idx->ei_block));
550         len = EXT_MAX_INDEX(curp->p_hdr) - curp->p_idx;
551         if (logical > le32_to_cpu(curp->p_idx->ei_block)) {
552                 /* insert after */
553                 if (curp->p_idx != EXT_LAST_INDEX(curp->p_hdr)) {
554                         len = (len - 1) * sizeof(struct ext4_extent_idx);
555                         len = len < 0 ? 0 : len;
556                         ext_debug("insert new index %d after: %d. "
557                                         "move %d from 0x%p to 0x%p\n",
558                                         logical, ptr, len,
559                                         (curp->p_idx + 1), (curp->p_idx + 2));
560                         memmove(curp->p_idx + 2, curp->p_idx + 1, len);
561                 }
562                 ix = curp->p_idx + 1;
563         } else {
564                 /* insert before */
565                 len = len * sizeof(struct ext4_extent_idx);
566                 len = len < 0 ? 0 : len;
567                 ext_debug("insert new index %d before: %d. "
568                                 "move %d from 0x%p to 0x%p\n",
569                                 logical, ptr, len,
570                                 curp->p_idx, (curp->p_idx + 1));
571                 memmove(curp->p_idx + 1, curp->p_idx, len);
572                 ix = curp->p_idx;
573         }
574
575         ix->ei_block = cpu_to_le32(logical);
576         ext4_idx_store_pblock(ix, ptr);
577         curp->p_hdr->eh_entries = cpu_to_le16(le16_to_cpu(curp->p_hdr->eh_entries)+1);
578
579         BUG_ON(le16_to_cpu(curp->p_hdr->eh_entries)
580                              > le16_to_cpu(curp->p_hdr->eh_max));
581         BUG_ON(ix > EXT_LAST_INDEX(curp->p_hdr));
582
583         err = ext4_ext_dirty(handle, inode, curp);
584         ext4_std_error(inode->i_sb, err);
585
586         return err;
587 }
588
589 /*
590  * ext4_ext_split:
591  * inserts new subtree into the path, using free index entry
592  * at depth @at:
593  * - allocates all needed blocks (new leaf and all intermediate index blocks)
594  * - makes decision where to split
595  * - moves remaining extents and index entries (right to the split point)
596  *   into the newly allocated blocks
597  * - initializes subtree
598  */
599 static int ext4_ext_split(handle_t *handle, struct inode *inode,
600                                 struct ext4_ext_path *path,
601                                 struct ext4_extent *newext, int at)
602 {
603         struct buffer_head *bh = NULL;
604         int depth = ext_depth(inode);
605         struct ext4_extent_header *neh;
606         struct ext4_extent_idx *fidx;
607         struct ext4_extent *ex;
608         int i = at, k, m, a;
609         ext4_fsblk_t newblock, oldblock;
610         __le32 border;
611         ext4_fsblk_t *ablocks = NULL; /* array of allocated blocks */
612         int err = 0;
613
614         /* make decision: where to split? */
615         /* FIXME: now decision is simplest: at current extent */
616
617         /* if current leaf will be split, then we should use
618          * border from split point */
619         BUG_ON(path[depth].p_ext > EXT_MAX_EXTENT(path[depth].p_hdr));
620         if (path[depth].p_ext != EXT_MAX_EXTENT(path[depth].p_hdr)) {
621                 border = path[depth].p_ext[1].ee_block;
622                 ext_debug("leaf will be split."
623                                 " next leaf starts at %d\n",
624                                   le32_to_cpu(border));
625         } else {
626                 border = newext->ee_block;
627                 ext_debug("leaf will be added."
628                                 " next leaf starts at %d\n",
629                                 le32_to_cpu(border));
630         }
631
632         /*
633          * If error occurs, then we break processing
634          * and mark filesystem read-only. index won't
635          * be inserted and tree will be in consistent
636          * state. Next mount will repair buffers too.
637          */
638
639         /*
640          * Get array to track all allocated blocks.
641          * We need this to handle errors and free blocks
642          * upon them.
643          */
644         ablocks = kmalloc(sizeof(ext4_fsblk_t) * depth, GFP_NOFS);
645         if (!ablocks)
646                 return -ENOMEM;
647         memset(ablocks, 0, sizeof(ext4_fsblk_t) * depth);
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         if ((err = ext4_journal_get_create_access(handle, bh)))
669                 goto cleanup;
670
671         neh = ext_block_hdr(bh);
672         neh->eh_entries = 0;
673         neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode));
674         neh->eh_magic = EXT4_EXT_MAGIC;
675         neh->eh_depth = 0;
676         ex = EXT_FIRST_EXTENT(neh);
677
678         /* move remainder of path[depth] to the new leaf */
679         BUG_ON(path[depth].p_hdr->eh_entries != path[depth].p_hdr->eh_max);
680         /* start copy from next extent */
681         /* TODO: we could do it by single memmove */
682         m = 0;
683         path[depth].p_ext++;
684         while (path[depth].p_ext <=
685                         EXT_MAX_EXTENT(path[depth].p_hdr)) {
686                 ext_debug("move %d:%llu:%d in new leaf %llu\n",
687                                 le32_to_cpu(path[depth].p_ext->ee_block),
688                                 ext_pblock(path[depth].p_ext),
689                                 le16_to_cpu(path[depth].p_ext->ee_len),
690                                 newblock);
691                 /*memmove(ex++, path[depth].p_ext++,
692                                 sizeof(struct ext4_extent));
693                 neh->eh_entries++;*/
694                 path[depth].p_ext++;
695                 m++;
696         }
697         if (m) {
698                 memmove(ex, path[depth].p_ext-m, sizeof(struct ext4_extent)*m);
699                 neh->eh_entries = cpu_to_le16(le16_to_cpu(neh->eh_entries)+m);
700         }
701
702         set_buffer_uptodate(bh);
703         unlock_buffer(bh);
704
705         if ((err = ext4_journal_dirty_metadata(handle, bh)))
706                 goto cleanup;
707         brelse(bh);
708         bh = NULL;
709
710         /* correct old leaf */
711         if (m) {
712                 if ((err = ext4_ext_get_access(handle, inode, path + depth)))
713                         goto cleanup;
714                 path[depth].p_hdr->eh_entries =
715                      cpu_to_le16(le16_to_cpu(path[depth].p_hdr->eh_entries)-m);
716                 if ((err = ext4_ext_dirty(handle, inode, path + depth)))
717                         goto cleanup;
718
719         }
720
721         /* create intermediate indexes */
722         k = depth - at - 1;
723         BUG_ON(k < 0);
724         if (k)
725                 ext_debug("create %d intermediate indices\n", k);
726         /* insert new index into current index block */
727         /* current depth stored in i var */
728         i = depth - 1;
729         while (k--) {
730                 oldblock = newblock;
731                 newblock = ablocks[--a];
732                 bh = sb_getblk(inode->i_sb, (ext4_fsblk_t)newblock);
733                 if (!bh) {
734                         err = -EIO;
735                         goto cleanup;
736                 }
737                 lock_buffer(bh);
738
739                 if ((err = ext4_journal_get_create_access(handle, bh)))
740                         goto cleanup;
741
742                 neh = ext_block_hdr(bh);
743                 neh->eh_entries = cpu_to_le16(1);
744                 neh->eh_magic = EXT4_EXT_MAGIC;
745                 neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode));
746                 neh->eh_depth = cpu_to_le16(depth - i);
747                 fidx = EXT_FIRST_INDEX(neh);
748                 fidx->ei_block = border;
749                 ext4_idx_store_pblock(fidx, oldblock);
750
751                 ext_debug("int.index at %d (block %llu): %lu -> %llu\n", i,
752                                 newblock, (unsigned long) le32_to_cpu(border),
753                                 oldblock);
754                 /* copy indexes */
755                 m = 0;
756                 path[i].p_idx++;
757
758                 ext_debug("cur 0x%p, last 0x%p\n", path[i].p_idx,
759                                 EXT_MAX_INDEX(path[i].p_hdr));
760                 BUG_ON(EXT_MAX_INDEX(path[i].p_hdr) !=
761                                 EXT_LAST_INDEX(path[i].p_hdr));
762                 while (path[i].p_idx <= EXT_MAX_INDEX(path[i].p_hdr)) {
763                         ext_debug("%d: move %d:%d in new index %llu\n", i,
764                                         le32_to_cpu(path[i].p_idx->ei_block),
765                                         idx_pblock(path[i].p_idx),
766                                         newblock);
767                         /*memmove(++fidx, path[i].p_idx++,
768                                         sizeof(struct ext4_extent_idx));
769                         neh->eh_entries++;
770                         BUG_ON(neh->eh_entries > neh->eh_max);*/
771                         path[i].p_idx++;
772                         m++;
773                 }
774                 if (m) {
775                         memmove(++fidx, path[i].p_idx - m,
776                                 sizeof(struct ext4_extent_idx) * m);
777                         neh->eh_entries =
778                                 cpu_to_le16(le16_to_cpu(neh->eh_entries) + m);
779                 }
780                 set_buffer_uptodate(bh);
781                 unlock_buffer(bh);
782
783                 if ((err = ext4_journal_dirty_metadata(handle, bh)))
784                         goto cleanup;
785                 brelse(bh);
786                 bh = NULL;
787
788                 /* correct old index */
789                 if (m) {
790                         err = ext4_ext_get_access(handle, inode, path + i);
791                         if (err)
792                                 goto cleanup;
793                         path[i].p_hdr->eh_entries = cpu_to_le16(le16_to_cpu(path[i].p_hdr->eh_entries)-m);
794                         err = ext4_ext_dirty(handle, inode, path + i);
795                         if (err)
796                                 goto cleanup;
797                 }
798
799                 i--;
800         }
801
802         /* insert new index */
803         err = ext4_ext_insert_index(handle, inode, path + at,
804                                     le32_to_cpu(border), newblock);
805
806 cleanup:
807         if (bh) {
808                 if (buffer_locked(bh))
809                         unlock_buffer(bh);
810                 brelse(bh);
811         }
812
813         if (err) {
814                 /* free all allocated blocks in error case */
815                 for (i = 0; i < depth; i++) {
816                         if (!ablocks[i])
817                                 continue;
818                         ext4_free_blocks(handle, inode, ablocks[i], 1);
819                 }
820         }
821         kfree(ablocks);
822
823         return err;
824 }
825
826 /*
827  * ext4_ext_grow_indepth:
828  * implements tree growing procedure:
829  * - allocates new block
830  * - moves top-level data (index block or leaf) into the new block
831  * - initializes new top-level, creating index that points to the
832  *   just created block
833  */
834 static int ext4_ext_grow_indepth(handle_t *handle, struct inode *inode,
835                                         struct ext4_ext_path *path,
836                                         struct ext4_extent *newext)
837 {
838         struct ext4_ext_path *curp = path;
839         struct ext4_extent_header *neh;
840         struct ext4_extent_idx *fidx;
841         struct buffer_head *bh;
842         ext4_fsblk_t newblock;
843         int err = 0;
844
845         newblock = ext4_ext_new_block(handle, inode, path, newext, &err);
846         if (newblock == 0)
847                 return err;
848
849         bh = sb_getblk(inode->i_sb, newblock);
850         if (!bh) {
851                 err = -EIO;
852                 ext4_std_error(inode->i_sb, err);
853                 return err;
854         }
855         lock_buffer(bh);
856
857         if ((err = ext4_journal_get_create_access(handle, bh))) {
858                 unlock_buffer(bh);
859                 goto out;
860         }
861
862         /* move top-level index/leaf into new block */
863         memmove(bh->b_data, curp->p_hdr, sizeof(EXT4_I(inode)->i_data));
864
865         /* set size of new block */
866         neh = ext_block_hdr(bh);
867         /* old root could have indexes or leaves
868          * so calculate e_max right way */
869         if (ext_depth(inode))
870           neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode));
871         else
872           neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode));
873         neh->eh_magic = EXT4_EXT_MAGIC;
874         set_buffer_uptodate(bh);
875         unlock_buffer(bh);
876
877         if ((err = ext4_journal_dirty_metadata(handle, bh)))
878                 goto out;
879
880         /* create index in new top-level index: num,max,pointer */
881         if ((err = ext4_ext_get_access(handle, inode, curp)))
882                 goto out;
883
884         curp->p_hdr->eh_magic = EXT4_EXT_MAGIC;
885         curp->p_hdr->eh_max = cpu_to_le16(ext4_ext_space_root_idx(inode));
886         curp->p_hdr->eh_entries = cpu_to_le16(1);
887         curp->p_idx = EXT_FIRST_INDEX(curp->p_hdr);
888         /* FIXME: it works, but actually path[0] can be index */
889         curp->p_idx->ei_block = EXT_FIRST_EXTENT(path[0].p_hdr)->ee_block;
890         ext4_idx_store_pblock(curp->p_idx, newblock);
891
892         neh = ext_inode_hdr(inode);
893         fidx = EXT_FIRST_INDEX(neh);
894         ext_debug("new root: num %d(%d), lblock %d, ptr %llu\n",
895                   le16_to_cpu(neh->eh_entries), le16_to_cpu(neh->eh_max),
896                   le32_to_cpu(fidx->ei_block), idx_pblock(fidx));
897
898         neh->eh_depth = cpu_to_le16(path->p_depth + 1);
899         err = ext4_ext_dirty(handle, inode, curp);
900 out:
901         brelse(bh);
902
903         return err;
904 }
905
906 /*
907  * ext4_ext_create_new_leaf:
908  * finds empty index and adds new leaf.
909  * if no free index is found, then it requests in-depth growing.
910  */
911 static int ext4_ext_create_new_leaf(handle_t *handle, struct inode *inode,
912                                         struct ext4_ext_path *path,
913                                         struct ext4_extent *newext)
914 {
915         struct ext4_ext_path *curp;
916         int depth, i, err = 0;
917
918 repeat:
919         i = depth = ext_depth(inode);
920
921         /* walk up to the tree and look for free index entry */
922         curp = path + depth;
923         while (i > 0 && !EXT_HAS_FREE_INDEX(curp)) {
924                 i--;
925                 curp--;
926         }
927
928         /* we use already allocated block for index block,
929          * so subsequent data blocks should be contiguous */
930         if (EXT_HAS_FREE_INDEX(curp)) {
931                 /* if we found index with free entry, then use that
932                  * entry: create all needed subtree and add new leaf */
933                 err = ext4_ext_split(handle, inode, path, newext, i);
934
935                 /* refill path */
936                 ext4_ext_drop_refs(path);
937                 path = ext4_ext_find_extent(inode,
938                                             le32_to_cpu(newext->ee_block),
939                                             path);
940                 if (IS_ERR(path))
941                         err = PTR_ERR(path);
942         } else {
943                 /* tree is full, time to grow in depth */
944                 err = ext4_ext_grow_indepth(handle, inode, path, newext);
945                 if (err)
946                         goto out;
947
948                 /* refill path */
949                 ext4_ext_drop_refs(path);
950                 path = ext4_ext_find_extent(inode,
951                                             le32_to_cpu(newext->ee_block),
952                                             path);
953                 if (IS_ERR(path)) {
954                         err = PTR_ERR(path);
955                         goto out;
956                 }
957
958                 /*
959                  * only first (depth 0 -> 1) produces free space;
960                  * in all other cases we have to split the grown tree
961                  */
962                 depth = ext_depth(inode);
963                 if (path[depth].p_hdr->eh_entries == path[depth].p_hdr->eh_max) {
964                         /* now we need to split */
965                         goto repeat;
966                 }
967         }
968
969 out:
970         return err;
971 }
972
973 /*
974  * ext4_ext_next_allocated_block:
975  * returns allocated block in subsequent extent or EXT_MAX_BLOCK.
976  * NOTE: it considers block number from index entry as
977  * allocated block. Thus, index entries have to be consistent
978  * with leaves.
979  */
980 static unsigned long
981 ext4_ext_next_allocated_block(struct ext4_ext_path *path)
982 {
983         int depth;
984
985         BUG_ON(path == NULL);
986         depth = path->p_depth;
987
988         if (depth == 0 && path->p_ext == NULL)
989                 return EXT_MAX_BLOCK;
990
991         while (depth >= 0) {
992                 if (depth == path->p_depth) {
993                         /* leaf */
994                         if (path[depth].p_ext !=
995                                         EXT_LAST_EXTENT(path[depth].p_hdr))
996                           return le32_to_cpu(path[depth].p_ext[1].ee_block);
997                 } else {
998                         /* index */
999                         if (path[depth].p_idx !=
1000                                         EXT_LAST_INDEX(path[depth].p_hdr))
1001                           return le32_to_cpu(path[depth].p_idx[1].ei_block);
1002                 }
1003                 depth--;
1004         }
1005
1006         return EXT_MAX_BLOCK;
1007 }
1008
1009 /*
1010  * ext4_ext_next_leaf_block:
1011  * returns first allocated block from next leaf or EXT_MAX_BLOCK
1012  */
1013 static unsigned ext4_ext_next_leaf_block(struct inode *inode,
1014                                         struct ext4_ext_path *path)
1015 {
1016         int depth;
1017
1018         BUG_ON(path == NULL);
1019         depth = path->p_depth;
1020
1021         /* zero-tree has no leaf blocks at all */
1022         if (depth == 0)
1023                 return EXT_MAX_BLOCK;
1024
1025         /* go to index block */
1026         depth--;
1027
1028         while (depth >= 0) {
1029                 if (path[depth].p_idx !=
1030                                 EXT_LAST_INDEX(path[depth].p_hdr))
1031                   return le32_to_cpu(path[depth].p_idx[1].ei_block);
1032                 depth--;
1033         }
1034
1035         return EXT_MAX_BLOCK;
1036 }
1037
1038 /*
1039  * ext4_ext_correct_indexes:
1040  * if leaf gets modified and modified extent is first in the leaf,
1041  * then we have to correct all indexes above.
1042  * TODO: do we need to correct tree in all cases?
1043  */
1044 int ext4_ext_correct_indexes(handle_t *handle, struct inode *inode,
1045                                 struct ext4_ext_path *path)
1046 {
1047         struct ext4_extent_header *eh;
1048         int depth = ext_depth(inode);
1049         struct ext4_extent *ex;
1050         __le32 border;
1051         int k, err = 0;
1052
1053         eh = path[depth].p_hdr;
1054         ex = path[depth].p_ext;
1055         BUG_ON(ex == NULL);
1056         BUG_ON(eh == NULL);
1057
1058         if (depth == 0) {
1059                 /* there is no tree at all */
1060                 return 0;
1061         }
1062
1063         if (ex != EXT_FIRST_EXTENT(eh)) {
1064                 /* we correct tree if first leaf got modified only */
1065                 return 0;
1066         }
1067
1068         /*
1069          * TODO: we need correction if border is smaller than current one
1070          */
1071         k = depth - 1;
1072         border = path[depth].p_ext->ee_block;
1073         if ((err = ext4_ext_get_access(handle, inode, path + k)))
1074                 return err;
1075         path[k].p_idx->ei_block = border;
1076         if ((err = ext4_ext_dirty(handle, inode, path + k)))
1077                 return err;
1078
1079         while (k--) {
1080                 /* change all left-side indexes */
1081                 if (path[k+1].p_idx != EXT_FIRST_INDEX(path[k+1].p_hdr))
1082                         break;
1083                 if ((err = ext4_ext_get_access(handle, inode, path + k)))
1084                         break;
1085                 path[k].p_idx->ei_block = border;
1086                 if ((err = ext4_ext_dirty(handle, inode, path + k)))
1087                         break;
1088         }
1089
1090         return err;
1091 }
1092
1093 static int inline
1094 ext4_can_extents_be_merged(struct inode *inode, struct ext4_extent *ex1,
1095                                 struct ext4_extent *ex2)
1096 {
1097         if (le32_to_cpu(ex1->ee_block) + le16_to_cpu(ex1->ee_len) !=
1098                         le32_to_cpu(ex2->ee_block))
1099                 return 0;
1100
1101         /*
1102          * To allow future support for preallocated extents to be added
1103          * as an RO_COMPAT feature, refuse to merge to extents if
1104          * this can result in the top bit of ee_len being set.
1105          */
1106         if (le16_to_cpu(ex1->ee_len) + le16_to_cpu(ex2->ee_len) > EXT_MAX_LEN)
1107                 return 0;
1108 #ifdef AGRESSIVE_TEST
1109         if (le16_to_cpu(ex1->ee_len) >= 4)
1110                 return 0;
1111 #endif
1112
1113         if (ext_pblock(ex1) + le16_to_cpu(ex1->ee_len) == ext_pblock(ex2))
1114                 return 1;
1115         return 0;
1116 }
1117
1118 /*
1119  * ext4_ext_insert_extent:
1120  * tries to merge requsted extent into the existing extent or
1121  * inserts requested extent as new one into the tree,
1122  * creating new leaf in the no-space case.
1123  */
1124 int ext4_ext_insert_extent(handle_t *handle, struct inode *inode,
1125                                 struct ext4_ext_path *path,
1126                                 struct ext4_extent *newext)
1127 {
1128         struct ext4_extent_header * eh;
1129         struct ext4_extent *ex, *fex;
1130         struct ext4_extent *nearex; /* nearest extent */
1131         struct ext4_ext_path *npath = NULL;
1132         int depth, len, err, next;
1133
1134         BUG_ON(newext->ee_len == 0);
1135         depth = ext_depth(inode);
1136         ex = path[depth].p_ext;
1137         BUG_ON(path[depth].p_hdr == NULL);
1138
1139         /* try to insert block into found extent and return */
1140         if (ex && ext4_can_extents_be_merged(inode, ex, newext)) {
1141                 ext_debug("append %d block to %d:%d (from %llu)\n",
1142                                 le16_to_cpu(newext->ee_len),
1143                                 le32_to_cpu(ex->ee_block),
1144                                 le16_to_cpu(ex->ee_len), ext_pblock(ex));
1145                 if ((err = ext4_ext_get_access(handle, inode, path + depth)))
1146                         return err;
1147                 ex->ee_len = cpu_to_le16(le16_to_cpu(ex->ee_len)
1148                                          + le16_to_cpu(newext->ee_len));
1149                 eh = path[depth].p_hdr;
1150                 nearex = ex;
1151                 goto merge;
1152         }
1153
1154 repeat:
1155         depth = ext_depth(inode);
1156         eh = path[depth].p_hdr;
1157         if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max))
1158                 goto has_space;
1159
1160         /* probably next leaf has space for us? */
1161         fex = EXT_LAST_EXTENT(eh);
1162         next = ext4_ext_next_leaf_block(inode, path);
1163         if (le32_to_cpu(newext->ee_block) > le32_to_cpu(fex->ee_block)
1164             && next != EXT_MAX_BLOCK) {
1165                 ext_debug("next leaf block - %d\n", next);
1166                 BUG_ON(npath != NULL);
1167                 npath = ext4_ext_find_extent(inode, next, NULL);
1168                 if (IS_ERR(npath))
1169                         return PTR_ERR(npath);
1170                 BUG_ON(npath->p_depth != path->p_depth);
1171                 eh = npath[depth].p_hdr;
1172                 if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max)) {
1173                         ext_debug("next leaf isnt full(%d)\n",
1174                                   le16_to_cpu(eh->eh_entries));
1175                         path = npath;
1176                         goto repeat;
1177                 }
1178                 ext_debug("next leaf has no free space(%d,%d)\n",
1179                           le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
1180         }
1181
1182         /*
1183          * There is no free space in the found leaf.
1184          * We're gonna add a new leaf in the tree.
1185          */
1186         err = ext4_ext_create_new_leaf(handle, inode, path, newext);
1187         if (err)
1188                 goto cleanup;
1189         depth = ext_depth(inode);
1190         eh = path[depth].p_hdr;
1191
1192 has_space:
1193         nearex = path[depth].p_ext;
1194
1195         if ((err = ext4_ext_get_access(handle, inode, path + depth)))
1196                 goto cleanup;
1197
1198         if (!nearex) {
1199                 /* there is no extent in this leaf, create first one */
1200                 ext_debug("first extent in the leaf: %d:%llu:%d\n",
1201                                 le32_to_cpu(newext->ee_block),
1202                                 ext_pblock(newext),
1203                                 le16_to_cpu(newext->ee_len));
1204                 path[depth].p_ext = EXT_FIRST_EXTENT(eh);
1205         } else if (le32_to_cpu(newext->ee_block)
1206                            > le32_to_cpu(nearex->ee_block)) {
1207 /*              BUG_ON(newext->ee_block == nearex->ee_block); */
1208                 if (nearex != EXT_LAST_EXTENT(eh)) {
1209                         len = EXT_MAX_EXTENT(eh) - nearex;
1210                         len = (len - 1) * sizeof(struct ext4_extent);
1211                         len = len < 0 ? 0 : len;
1212                         ext_debug("insert %d:%llu:%d after: nearest 0x%p, "
1213                                         "move %d from 0x%p to 0x%p\n",
1214                                         le32_to_cpu(newext->ee_block),
1215                                         ext_pblock(newext),
1216                                         le16_to_cpu(newext->ee_len),
1217                                         nearex, len, nearex + 1, nearex + 2);
1218                         memmove(nearex + 2, nearex + 1, len);
1219                 }
1220                 path[depth].p_ext = nearex + 1;
1221         } else {
1222                 BUG_ON(newext->ee_block == nearex->ee_block);
1223                 len = (EXT_MAX_EXTENT(eh) - nearex) * sizeof(struct ext4_extent);
1224                 len = len < 0 ? 0 : len;
1225                 ext_debug("insert %d:%llu:%d before: nearest 0x%p, "
1226                                 "move %d from 0x%p to 0x%p\n",
1227                                 le32_to_cpu(newext->ee_block),
1228                                 ext_pblock(newext),
1229                                 le16_to_cpu(newext->ee_len),
1230                                 nearex, len, nearex + 1, nearex + 2);
1231                 memmove(nearex + 1, nearex, len);
1232                 path[depth].p_ext = nearex;
1233         }
1234
1235         eh->eh_entries = cpu_to_le16(le16_to_cpu(eh->eh_entries)+1);
1236         nearex = path[depth].p_ext;
1237         nearex->ee_block = newext->ee_block;
1238         nearex->ee_start = newext->ee_start;
1239         nearex->ee_start_hi = newext->ee_start_hi;
1240         nearex->ee_len = newext->ee_len;
1241
1242 merge:
1243         /* try to merge extents to the right */
1244         while (nearex < EXT_LAST_EXTENT(eh)) {
1245                 if (!ext4_can_extents_be_merged(inode, nearex, nearex + 1))
1246                         break;
1247                 /* merge with next extent! */
1248                 nearex->ee_len = cpu_to_le16(le16_to_cpu(nearex->ee_len)
1249                                              + le16_to_cpu(nearex[1].ee_len));
1250                 if (nearex + 1 < EXT_LAST_EXTENT(eh)) {
1251                         len = (EXT_LAST_EXTENT(eh) - nearex - 1)
1252                                         * sizeof(struct ext4_extent);
1253                         memmove(nearex + 1, nearex + 2, len);
1254                 }
1255                 eh->eh_entries = cpu_to_le16(le16_to_cpu(eh->eh_entries)-1);
1256                 BUG_ON(eh->eh_entries == 0);
1257         }
1258
1259         /* try to merge extents to the left */
1260
1261         /* time to correct all indexes above */
1262         err = ext4_ext_correct_indexes(handle, inode, path);
1263         if (err)
1264                 goto cleanup;
1265
1266         err = ext4_ext_dirty(handle, inode, path + depth);
1267
1268 cleanup:
1269         if (npath) {
1270                 ext4_ext_drop_refs(npath);
1271                 kfree(npath);
1272         }
1273         ext4_ext_tree_changed(inode);
1274         ext4_ext_invalidate_cache(inode);
1275         return err;
1276 }
1277
1278 int ext4_ext_walk_space(struct inode *inode, unsigned long block,
1279                         unsigned long num, ext_prepare_callback func,
1280                         void *cbdata)
1281 {
1282         struct ext4_ext_path *path = NULL;
1283         struct ext4_ext_cache cbex;
1284         struct ext4_extent *ex;
1285         unsigned long next, start = 0, end = 0;
1286         unsigned long last = block + num;
1287         int depth, exists, err = 0;
1288
1289         BUG_ON(func == NULL);
1290         BUG_ON(inode == NULL);
1291
1292         while (block < last && block != EXT_MAX_BLOCK) {
1293                 num = last - block;
1294                 /* find extent for this block */
1295                 path = ext4_ext_find_extent(inode, block, path);
1296                 if (IS_ERR(path)) {
1297                         err = PTR_ERR(path);
1298                         path = NULL;
1299                         break;
1300                 }
1301
1302                 depth = ext_depth(inode);
1303                 BUG_ON(path[depth].p_hdr == NULL);
1304                 ex = path[depth].p_ext;
1305                 next = ext4_ext_next_allocated_block(path);
1306
1307                 exists = 0;
1308                 if (!ex) {
1309                         /* there is no extent yet, so try to allocate
1310                          * all requested space */
1311                         start = block;
1312                         end = block + num;
1313                 } else if (le32_to_cpu(ex->ee_block) > block) {
1314                         /* need to allocate space before found extent */
1315                         start = block;
1316                         end = le32_to_cpu(ex->ee_block);
1317                         if (block + num < end)
1318                                 end = block + num;
1319                 } else if (block >=
1320                              le32_to_cpu(ex->ee_block) + le16_to_cpu(ex->ee_len)) {
1321                         /* need to allocate space after found extent */
1322                         start = block;
1323                         end = block + num;
1324                         if (end >= next)
1325                                 end = next;
1326                 } else if (block >= le32_to_cpu(ex->ee_block)) {
1327                         /*
1328                          * some part of requested space is covered
1329                          * by found extent
1330                          */
1331                         start = block;
1332                         end = le32_to_cpu(ex->ee_block) + le16_to_cpu(ex->ee_len);
1333                         if (block + num < end)
1334                                 end = block + num;
1335                         exists = 1;
1336                 } else {
1337                         BUG();
1338                 }
1339                 BUG_ON(end <= start);
1340
1341                 if (!exists) {
1342                         cbex.ec_block = start;
1343                         cbex.ec_len = end - start;
1344                         cbex.ec_start = 0;
1345                         cbex.ec_type = EXT4_EXT_CACHE_GAP;
1346                 } else {
1347                         cbex.ec_block = le32_to_cpu(ex->ee_block);
1348                         cbex.ec_len = le16_to_cpu(ex->ee_len);
1349                         cbex.ec_start = ext_pblock(ex);
1350                         cbex.ec_type = EXT4_EXT_CACHE_EXTENT;
1351                 }
1352
1353                 BUG_ON(cbex.ec_len == 0);
1354                 err = func(inode, path, &cbex, cbdata);
1355                 ext4_ext_drop_refs(path);
1356
1357                 if (err < 0)
1358                         break;
1359                 if (err == EXT_REPEAT)
1360                         continue;
1361                 else if (err == EXT_BREAK) {
1362                         err = 0;
1363                         break;
1364                 }
1365
1366                 if (ext_depth(inode) != depth) {
1367                         /* depth was changed. we have to realloc path */
1368                         kfree(path);
1369                         path = NULL;
1370                 }
1371
1372                 block = cbex.ec_block + cbex.ec_len;
1373         }
1374
1375         if (path) {
1376                 ext4_ext_drop_refs(path);
1377                 kfree(path);
1378         }
1379
1380         return err;
1381 }
1382
1383 static inline void
1384 ext4_ext_put_in_cache(struct inode *inode, __u32 block,
1385                         __u32 len, __u32 start, int type)
1386 {
1387         struct ext4_ext_cache *cex;
1388         BUG_ON(len == 0);
1389         cex = &EXT4_I(inode)->i_cached_extent;
1390         cex->ec_type = type;
1391         cex->ec_block = block;
1392         cex->ec_len = len;
1393         cex->ec_start = start;
1394 }
1395
1396 /*
1397  * ext4_ext_put_gap_in_cache:
1398  * calculate boundaries of the gap that the requested block fits into
1399  * and cache this gap
1400  */
1401 static inline void
1402 ext4_ext_put_gap_in_cache(struct inode *inode, struct ext4_ext_path *path,
1403                                 unsigned long block)
1404 {
1405         int depth = ext_depth(inode);
1406         unsigned long lblock, len;
1407         struct ext4_extent *ex;
1408
1409         ex = path[depth].p_ext;
1410         if (ex == NULL) {
1411                 /* there is no extent yet, so gap is [0;-] */
1412                 lblock = 0;
1413                 len = EXT_MAX_BLOCK;
1414                 ext_debug("cache gap(whole file):");
1415         } else if (block < le32_to_cpu(ex->ee_block)) {
1416                 lblock = block;
1417                 len = le32_to_cpu(ex->ee_block) - block;
1418                 ext_debug("cache gap(before): %lu [%lu:%lu]",
1419                                 (unsigned long) block,
1420                                 (unsigned long) le32_to_cpu(ex->ee_block),
1421                                 (unsigned long) le16_to_cpu(ex->ee_len));
1422         } else if (block >= le32_to_cpu(ex->ee_block)
1423                             + le16_to_cpu(ex->ee_len)) {
1424                 lblock = le32_to_cpu(ex->ee_block)
1425                          + le16_to_cpu(ex->ee_len);
1426                 len = ext4_ext_next_allocated_block(path);
1427                 ext_debug("cache gap(after): [%lu:%lu] %lu",
1428                                 (unsigned long) le32_to_cpu(ex->ee_block),
1429                                 (unsigned long) le16_to_cpu(ex->ee_len),
1430                                 (unsigned long) block);
1431                 BUG_ON(len == lblock);
1432                 len = len - lblock;
1433         } else {
1434                 lblock = len = 0;
1435                 BUG();
1436         }
1437
1438         ext_debug(" -> %lu:%lu\n", (unsigned long) lblock, len);
1439         ext4_ext_put_in_cache(inode, lblock, len, 0, EXT4_EXT_CACHE_GAP);
1440 }
1441
1442 static inline int
1443 ext4_ext_in_cache(struct inode *inode, unsigned long block,
1444                         struct ext4_extent *ex)
1445 {
1446         struct ext4_ext_cache *cex;
1447
1448         cex = &EXT4_I(inode)->i_cached_extent;
1449
1450         /* has cache valid data? */
1451         if (cex->ec_type == EXT4_EXT_CACHE_NO)
1452                 return EXT4_EXT_CACHE_NO;
1453
1454         BUG_ON(cex->ec_type != EXT4_EXT_CACHE_GAP &&
1455                         cex->ec_type != EXT4_EXT_CACHE_EXTENT);
1456         if (block >= cex->ec_block && block < cex->ec_block + cex->ec_len) {
1457                 ex->ee_block = cpu_to_le32(cex->ec_block);
1458                 ext4_ext_store_pblock(ex, cex->ec_start);
1459                 ex->ee_len = cpu_to_le16(cex->ec_len);
1460                 ext_debug("%lu cached by %lu:%lu:%llu\n",
1461                                 (unsigned long) block,
1462                                 (unsigned long) cex->ec_block,
1463                                 (unsigned long) cex->ec_len,
1464                                 cex->ec_start);
1465                 return cex->ec_type;
1466         }
1467
1468         /* not in cache */
1469         return EXT4_EXT_CACHE_NO;
1470 }
1471
1472 /*
1473  * ext4_ext_rm_idx:
1474  * removes index from the index block.
1475  * It's used in truncate case only, thus all requests are for
1476  * last index in the block only.
1477  */
1478 int ext4_ext_rm_idx(handle_t *handle, struct inode *inode,
1479                         struct ext4_ext_path *path)
1480 {
1481         struct buffer_head *bh;
1482         int err;
1483         ext4_fsblk_t leaf;
1484
1485         /* free index block */
1486         path--;
1487         leaf = idx_pblock(path->p_idx);
1488         BUG_ON(path->p_hdr->eh_entries == 0);
1489         if ((err = ext4_ext_get_access(handle, inode, path)))
1490                 return err;
1491         path->p_hdr->eh_entries = cpu_to_le16(le16_to_cpu(path->p_hdr->eh_entries)-1);
1492         if ((err = ext4_ext_dirty(handle, inode, path)))
1493                 return err;
1494         ext_debug("index is empty, remove it, free block %llu\n", leaf);
1495         bh = sb_find_get_block(inode->i_sb, leaf);
1496         ext4_forget(handle, 1, inode, bh, leaf);
1497         ext4_free_blocks(handle, inode, leaf, 1);
1498         return err;
1499 }
1500
1501 /*
1502  * ext4_ext_calc_credits_for_insert:
1503  * This routine returns max. credits that the extent tree can consume.
1504  * It should be OK for low-performance paths like ->writepage()
1505  * To allow many writing processes to fit into a single transaction,
1506  * the caller should calculate credits under truncate_mutex and
1507  * pass the actual path.
1508  */
1509 int inline ext4_ext_calc_credits_for_insert(struct inode *inode,
1510                                                 struct ext4_ext_path *path)
1511 {
1512         int depth, needed;
1513
1514         if (path) {
1515                 /* probably there is space in leaf? */
1516                 depth = ext_depth(inode);
1517                 if (le16_to_cpu(path[depth].p_hdr->eh_entries)
1518                                 < le16_to_cpu(path[depth].p_hdr->eh_max))
1519                         return 1;
1520         }
1521
1522         /*
1523          * given 32-bit logical block (4294967296 blocks), max. tree
1524          * can be 4 levels in depth -- 4 * 340^4 == 53453440000.
1525          * Let's also add one more level for imbalance.
1526          */
1527         depth = 5;
1528
1529         /* allocation of new data block(s) */
1530         needed = 2;
1531
1532         /*
1533          * tree can be full, so it would need to grow in depth:
1534          * we need one credit to modify old root, credits for
1535          * new root will be added in split accounting
1536          */
1537         needed += 1;
1538
1539         /*
1540          * Index split can happen, we would need:
1541          *    allocate intermediate indexes (bitmap + group)
1542          *  + change two blocks at each level, but root (already included)
1543          */
1544         needed += (depth * 2) + (depth * 2);
1545
1546         /* any allocation modifies superblock */
1547         needed += 1;
1548
1549         return needed;
1550 }
1551
1552 static int ext4_remove_blocks(handle_t *handle, struct inode *inode,
1553                                 struct ext4_extent *ex,
1554                                 unsigned long from, unsigned long to)
1555 {
1556         struct buffer_head *bh;
1557         int i;
1558
1559 #ifdef EXTENTS_STATS
1560         {
1561                 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1562                 unsigned short ee_len =  le16_to_cpu(ex->ee_len);
1563                 spin_lock(&sbi->s_ext_stats_lock);
1564                 sbi->s_ext_blocks += ee_len;
1565                 sbi->s_ext_extents++;
1566                 if (ee_len < sbi->s_ext_min)
1567                         sbi->s_ext_min = ee_len;
1568                 if (ee_len > sbi->s_ext_max)
1569                         sbi->s_ext_max = ee_len;
1570                 if (ext_depth(inode) > sbi->s_depth_max)
1571                         sbi->s_depth_max = ext_depth(inode);
1572                 spin_unlock(&sbi->s_ext_stats_lock);
1573         }
1574 #endif
1575         if (from >= le32_to_cpu(ex->ee_block)
1576             && to == le32_to_cpu(ex->ee_block) + le16_to_cpu(ex->ee_len) - 1) {
1577                 /* tail removal */
1578                 unsigned long num;
1579                 ext4_fsblk_t start;
1580                 num = le32_to_cpu(ex->ee_block) + le16_to_cpu(ex->ee_len) - from;
1581                 start = ext_pblock(ex) + le16_to_cpu(ex->ee_len) - num;
1582                 ext_debug("free last %lu blocks starting %llu\n", num, start);
1583                 for (i = 0; i < num; i++) {
1584                         bh = sb_find_get_block(inode->i_sb, start + i);
1585                         ext4_forget(handle, 0, inode, bh, start + i);
1586                 }
1587                 ext4_free_blocks(handle, inode, start, num);
1588         } else if (from == le32_to_cpu(ex->ee_block)
1589                    && to <= le32_to_cpu(ex->ee_block) + le16_to_cpu(ex->ee_len) - 1) {
1590                 printk("strange request: removal %lu-%lu from %u:%u\n",
1591                        from, to, le32_to_cpu(ex->ee_block), le16_to_cpu(ex->ee_len));
1592         } else {
1593                 printk("strange request: removal(2) %lu-%lu from %u:%u\n",
1594                        from, to, le32_to_cpu(ex->ee_block), le16_to_cpu(ex->ee_len));
1595         }
1596         return 0;
1597 }
1598
1599 static int
1600 ext4_ext_rm_leaf(handle_t *handle, struct inode *inode,
1601                 struct ext4_ext_path *path, unsigned long start)
1602 {
1603         int err = 0, correct_index = 0;
1604         int depth = ext_depth(inode), credits;
1605         struct ext4_extent_header *eh;
1606         unsigned a, b, block, num;
1607         unsigned long ex_ee_block;
1608         unsigned short ex_ee_len;
1609         struct ext4_extent *ex;
1610
1611         ext_debug("truncate since %lu in leaf\n", start);
1612         if (!path[depth].p_hdr)
1613                 path[depth].p_hdr = ext_block_hdr(path[depth].p_bh);
1614         eh = path[depth].p_hdr;
1615         BUG_ON(eh == NULL);
1616         BUG_ON(le16_to_cpu(eh->eh_entries) > le16_to_cpu(eh->eh_max));
1617         BUG_ON(eh->eh_magic != EXT4_EXT_MAGIC);
1618
1619         /* find where to start removing */
1620         ex = EXT_LAST_EXTENT(eh);
1621
1622         ex_ee_block = le32_to_cpu(ex->ee_block);
1623         ex_ee_len = le16_to_cpu(ex->ee_len);
1624
1625         while (ex >= EXT_FIRST_EXTENT(eh) &&
1626                         ex_ee_block + ex_ee_len > start) {
1627                 ext_debug("remove ext %lu:%u\n", ex_ee_block, ex_ee_len);
1628                 path[depth].p_ext = ex;
1629
1630                 a = ex_ee_block > start ? ex_ee_block : start;
1631                 b = ex_ee_block + ex_ee_len - 1 < EXT_MAX_BLOCK ?
1632                         ex_ee_block + ex_ee_len - 1 : EXT_MAX_BLOCK;
1633
1634                 ext_debug("  border %u:%u\n", a, b);
1635
1636                 if (a != ex_ee_block && b != ex_ee_block + ex_ee_len - 1) {
1637                         block = 0;
1638                         num = 0;
1639                         BUG();
1640                 } else if (a != ex_ee_block) {
1641                         /* remove tail of the extent */
1642                         block = ex_ee_block;
1643                         num = a - block;
1644                 } else if (b != ex_ee_block + ex_ee_len - 1) {
1645                         /* remove head of the extent */
1646                         block = a;
1647                         num = b - a;
1648                         /* there is no "make a hole" API yet */
1649                         BUG();
1650                 } else {
1651                         /* remove whole extent: excellent! */
1652                         block = ex_ee_block;
1653                         num = 0;
1654                         BUG_ON(a != ex_ee_block);
1655                         BUG_ON(b != ex_ee_block + ex_ee_len - 1);
1656                 }
1657
1658                 /* at present, extent can't cross block group: */
1659                 /* leaf + bitmap + group desc + sb + inode */
1660                 credits = 5;
1661                 if (ex == EXT_FIRST_EXTENT(eh)) {
1662                         correct_index = 1;
1663                         credits += (ext_depth(inode)) + 1;
1664                 }
1665 #ifdef CONFIG_QUOTA
1666                 credits += 2 * EXT4_QUOTA_TRANS_BLOCKS(inode->i_sb);
1667 #endif
1668
1669                 handle = ext4_ext_journal_restart(handle, credits);
1670                 if (IS_ERR(handle)) {
1671                         err = PTR_ERR(handle);
1672                         goto out;
1673                 }
1674
1675                 err = ext4_ext_get_access(handle, inode, path + depth);
1676                 if (err)
1677                         goto out;
1678
1679                 err = ext4_remove_blocks(handle, inode, ex, a, b);
1680                 if (err)
1681                         goto out;
1682
1683                 if (num == 0) {
1684                         /* this extent is removed; mark slot entirely unused */
1685                         ext4_ext_store_pblock(ex, 0);
1686                         eh->eh_entries = cpu_to_le16(le16_to_cpu(eh->eh_entries)-1);
1687                 }
1688
1689                 ex->ee_block = cpu_to_le32(block);
1690                 ex->ee_len = cpu_to_le16(num);
1691
1692                 err = ext4_ext_dirty(handle, inode, path + depth);
1693                 if (err)
1694                         goto out;
1695
1696                 ext_debug("new extent: %u:%u:%llu\n", block, num,
1697                                 ext_pblock(ex));
1698                 ex--;
1699                 ex_ee_block = le32_to_cpu(ex->ee_block);
1700                 ex_ee_len = le16_to_cpu(ex->ee_len);
1701         }
1702
1703         if (correct_index && eh->eh_entries)
1704                 err = ext4_ext_correct_indexes(handle, inode, path);
1705
1706         /* if this leaf is free, then we should
1707          * remove it from index block above */
1708         if (err == 0 && eh->eh_entries == 0 && path[depth].p_bh != NULL)
1709                 err = ext4_ext_rm_idx(handle, inode, path + depth);
1710
1711 out:
1712         return err;
1713 }
1714
1715 /*
1716  * ext4_ext_more_to_rm:
1717  * returns 1 if current index has to be freed (even partial)
1718  */
1719 static int inline
1720 ext4_ext_more_to_rm(struct ext4_ext_path *path)
1721 {
1722         BUG_ON(path->p_idx == NULL);
1723
1724         if (path->p_idx < EXT_FIRST_INDEX(path->p_hdr))
1725                 return 0;
1726
1727         /*
1728          * if truncate on deeper level happened, it wasn't partial,
1729          * so we have to consider current index for truncation
1730          */
1731         if (le16_to_cpu(path->p_hdr->eh_entries) == path->p_block)
1732                 return 0;
1733         return 1;
1734 }
1735
1736 int ext4_ext_remove_space(struct inode *inode, unsigned long start)
1737 {
1738         struct super_block *sb = inode->i_sb;
1739         int depth = ext_depth(inode);
1740         struct ext4_ext_path *path;
1741         handle_t *handle;
1742         int i = 0, err = 0;
1743
1744         ext_debug("truncate since %lu\n", start);
1745
1746         /* probably first extent we're gonna free will be last in block */
1747         handle = ext4_journal_start(inode, depth + 1);
1748         if (IS_ERR(handle))
1749                 return PTR_ERR(handle);
1750
1751         ext4_ext_invalidate_cache(inode);
1752
1753         /*
1754          * We start scanning from right side, freeing all the blocks
1755          * after i_size and walking into the tree depth-wise.
1756          */
1757         path = kmalloc(sizeof(struct ext4_ext_path) * (depth + 1), GFP_KERNEL);
1758         if (path == NULL) {
1759                 ext4_journal_stop(handle);
1760                 return -ENOMEM;
1761         }
1762         memset(path, 0, sizeof(struct ext4_ext_path) * (depth + 1));
1763         path[0].p_hdr = ext_inode_hdr(inode);
1764         if (ext4_ext_check_header(__FUNCTION__, inode, path[0].p_hdr)) {
1765                 err = -EIO;
1766                 goto out;
1767         }
1768         path[0].p_depth = depth;
1769
1770         while (i >= 0 && err == 0) {
1771                 if (i == depth) {
1772                         /* this is leaf block */
1773                         err = ext4_ext_rm_leaf(handle, inode, path, start);
1774                         /* root level has p_bh == NULL, brelse() eats this */
1775                         brelse(path[i].p_bh);
1776                         path[i].p_bh = NULL;
1777                         i--;
1778                         continue;
1779                 }
1780
1781                 /* this is index block */
1782                 if (!path[i].p_hdr) {
1783                         ext_debug("initialize header\n");
1784                         path[i].p_hdr = ext_block_hdr(path[i].p_bh);
1785                         if (ext4_ext_check_header(__FUNCTION__, inode,
1786                                                         path[i].p_hdr)) {
1787                                 err = -EIO;
1788                                 goto out;
1789                         }
1790                 }
1791
1792                 BUG_ON(le16_to_cpu(path[i].p_hdr->eh_entries)
1793                            > le16_to_cpu(path[i].p_hdr->eh_max));
1794                 BUG_ON(path[i].p_hdr->eh_magic != EXT4_EXT_MAGIC);
1795
1796                 if (!path[i].p_idx) {
1797                         /* this level hasn't been touched yet */
1798                         path[i].p_idx = EXT_LAST_INDEX(path[i].p_hdr);
1799                         path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries)+1;
1800                         ext_debug("init index ptr: hdr 0x%p, num %d\n",
1801                                   path[i].p_hdr,
1802                                   le16_to_cpu(path[i].p_hdr->eh_entries));
1803                 } else {
1804                         /* we were already here, see at next index */
1805                         path[i].p_idx--;
1806                 }
1807
1808                 ext_debug("level %d - index, first 0x%p, cur 0x%p\n",
1809                                 i, EXT_FIRST_INDEX(path[i].p_hdr),
1810                                 path[i].p_idx);
1811                 if (ext4_ext_more_to_rm(path + i)) {
1812                         /* go to the next level */
1813                         ext_debug("move to level %d (block %llu)\n",
1814                                   i + 1, idx_pblock(path[i].p_idx));
1815                         memset(path + i + 1, 0, sizeof(*path));
1816                         path[i+1].p_bh =
1817                                 sb_bread(sb, idx_pblock(path[i].p_idx));
1818                         if (!path[i+1].p_bh) {
1819                                 /* should we reset i_size? */
1820                                 err = -EIO;
1821                                 break;
1822                         }
1823
1824                         /* save actual number of indexes since this
1825                          * number is changed at the next iteration */
1826                         path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries);
1827                         i++;
1828                 } else {
1829                         /* we finished processing this index, go up */
1830                         if (path[i].p_hdr->eh_entries == 0 && i > 0) {
1831                                 /* index is empty, remove it;
1832                                  * handle must be already prepared by the
1833                                  * truncatei_leaf() */
1834                                 err = ext4_ext_rm_idx(handle, inode, path + i);
1835                         }
1836                         /* root level has p_bh == NULL, brelse() eats this */
1837                         brelse(path[i].p_bh);
1838                         path[i].p_bh = NULL;
1839                         i--;
1840                         ext_debug("return to level %d\n", i);
1841                 }
1842         }
1843
1844         /* TODO: flexible tree reduction should be here */
1845         if (path->p_hdr->eh_entries == 0) {
1846                 /*
1847                  * truncate to zero freed all the tree,
1848                  * so we need to correct eh_depth
1849                  */
1850                 err = ext4_ext_get_access(handle, inode, path);
1851                 if (err == 0) {
1852                         ext_inode_hdr(inode)->eh_depth = 0;
1853                         ext_inode_hdr(inode)->eh_max =
1854                                 cpu_to_le16(ext4_ext_space_root(inode));
1855                         err = ext4_ext_dirty(handle, inode, path);
1856                 }
1857         }
1858 out:
1859         ext4_ext_tree_changed(inode);
1860         ext4_ext_drop_refs(path);
1861         kfree(path);
1862         ext4_journal_stop(handle);
1863
1864         return err;
1865 }
1866
1867 /*
1868  * called at mount time
1869  */
1870 void ext4_ext_init(struct super_block *sb)
1871 {
1872         /*
1873          * possible initialization would be here
1874          */
1875
1876         if (test_opt(sb, EXTENTS)) {
1877                 printk("EXT4-fs: file extents enabled");
1878 #ifdef AGRESSIVE_TEST
1879                 printk(", agressive tests");
1880 #endif
1881 #ifdef CHECK_BINSEARCH
1882                 printk(", check binsearch");
1883 #endif
1884 #ifdef EXTENTS_STATS
1885                 printk(", stats");
1886 #endif
1887                 printk("\n");
1888 #ifdef EXTENTS_STATS
1889                 spin_lock_init(&EXT4_SB(sb)->s_ext_stats_lock);
1890                 EXT4_SB(sb)->s_ext_min = 1 << 30;
1891                 EXT4_SB(sb)->s_ext_max = 0;
1892 #endif
1893         }
1894 }
1895
1896 /*
1897  * called at umount time
1898  */
1899 void ext4_ext_release(struct super_block *sb)
1900 {
1901         if (!test_opt(sb, EXTENTS))
1902                 return;
1903
1904 #ifdef EXTENTS_STATS
1905         if (EXT4_SB(sb)->s_ext_blocks && EXT4_SB(sb)->s_ext_extents) {
1906                 struct ext4_sb_info *sbi = EXT4_SB(sb);
1907                 printk(KERN_ERR "EXT4-fs: %lu blocks in %lu extents (%lu ave)\n",
1908                         sbi->s_ext_blocks, sbi->s_ext_extents,
1909                         sbi->s_ext_blocks / sbi->s_ext_extents);
1910                 printk(KERN_ERR "EXT4-fs: extents: %lu min, %lu max, max depth %lu\n",
1911                         sbi->s_ext_min, sbi->s_ext_max, sbi->s_depth_max);
1912         }
1913 #endif
1914 }
1915
1916 int ext4_ext_get_blocks(handle_t *handle, struct inode *inode,
1917                         ext4_fsblk_t iblock,
1918                         unsigned long max_blocks, struct buffer_head *bh_result,
1919                         int create, int extend_disksize)
1920 {
1921         struct ext4_ext_path *path = NULL;
1922         struct ext4_extent newex, *ex;
1923         ext4_fsblk_t goal, newblock;
1924         int err = 0, depth;
1925         unsigned long allocated = 0;
1926
1927         __clear_bit(BH_New, &bh_result->b_state);
1928         ext_debug("blocks %d/%lu requested for inode %u\n", (int) iblock,
1929                         max_blocks, (unsigned) inode->i_ino);
1930         mutex_lock(&EXT4_I(inode)->truncate_mutex);
1931
1932         /* check in cache */
1933         if ((goal = ext4_ext_in_cache(inode, iblock, &newex))) {
1934                 if (goal == EXT4_EXT_CACHE_GAP) {
1935                         if (!create) {
1936                                 /* block isn't allocated yet and
1937                                  * user doesn't want to allocate it */
1938                                 goto out2;
1939                         }
1940                         /* we should allocate requested block */
1941                 } else if (goal == EXT4_EXT_CACHE_EXTENT) {
1942                         /* block is already allocated */
1943                         newblock = iblock
1944                                    - le32_to_cpu(newex.ee_block)
1945                                    + ext_pblock(&newex);
1946                         /* number of remaining blocks in the extent */
1947                         allocated = le16_to_cpu(newex.ee_len) -
1948                                         (iblock - le32_to_cpu(newex.ee_block));
1949                         goto out;
1950                 } else {
1951                         BUG();
1952                 }
1953         }
1954
1955         /* find extent for this block */
1956         path = ext4_ext_find_extent(inode, iblock, NULL);
1957         if (IS_ERR(path)) {
1958                 err = PTR_ERR(path);
1959                 path = NULL;
1960                 goto out2;
1961         }
1962
1963         depth = ext_depth(inode);
1964
1965         /*
1966          * consistent leaf must not be empty;
1967          * this situation is possible, though, _during_ tree modification;
1968          * this is why assert can't be put in ext4_ext_find_extent()
1969          */
1970         BUG_ON(path[depth].p_ext == NULL && depth != 0);
1971
1972         if ((ex = path[depth].p_ext)) {
1973                 unsigned long ee_block = le32_to_cpu(ex->ee_block);
1974                 ext4_fsblk_t ee_start = ext_pblock(ex);
1975                 unsigned short ee_len  = le16_to_cpu(ex->ee_len);
1976
1977                 /*
1978                  * Allow future support for preallocated extents to be added
1979                  * as an RO_COMPAT feature:
1980                  * Uninitialized extents are treated as holes, except that
1981                  * we avoid (fail) allocating new blocks during a write.
1982                  */
1983                 if (ee_len > EXT_MAX_LEN)
1984                         goto out2;
1985                 /* if found extent covers block, simply return it */
1986                 if (iblock >= ee_block && iblock < ee_block + ee_len) {
1987                         newblock = iblock - ee_block + ee_start;
1988                         /* number of remaining blocks in the extent */
1989                         allocated = ee_len - (iblock - ee_block);
1990                         ext_debug("%d fit into %lu:%d -> %llu\n", (int) iblock,
1991                                         ee_block, ee_len, newblock);
1992                         ext4_ext_put_in_cache(inode, ee_block, ee_len,
1993                                                 ee_start, EXT4_EXT_CACHE_EXTENT);
1994                         goto out;
1995                 }
1996         }
1997
1998         /*
1999          * requested block isn't allocated yet;
2000          * we couldn't try to create block if create flag is zero
2001          */
2002         if (!create) {
2003                 /* put just found gap into cache to speed up
2004                  * subsequent requests */
2005                 ext4_ext_put_gap_in_cache(inode, path, iblock);
2006                 goto out2;
2007         }
2008         /*
2009          * Okay, we need to do block allocation.  Lazily initialize the block
2010          * allocation info here if necessary.
2011          */
2012         if (S_ISREG(inode->i_mode) && (!EXT4_I(inode)->i_block_alloc_info))
2013                 ext4_init_block_alloc_info(inode);
2014
2015         /* allocate new block */
2016         goal = ext4_ext_find_goal(inode, path, iblock);
2017         allocated = max_blocks;
2018         newblock = ext4_new_blocks(handle, inode, goal, &allocated, &err);
2019         if (!newblock)
2020                 goto out2;
2021         ext_debug("allocate new block: goal %llu, found %llu/%lu\n",
2022                         goal, newblock, allocated);
2023
2024         /* try to insert new extent into found leaf and return */
2025         newex.ee_block = cpu_to_le32(iblock);
2026         ext4_ext_store_pblock(&newex, newblock);
2027         newex.ee_len = cpu_to_le16(allocated);
2028         err = ext4_ext_insert_extent(handle, inode, path, &newex);
2029         if (err)
2030                 goto out2;
2031
2032         if (extend_disksize && inode->i_size > EXT4_I(inode)->i_disksize)
2033                 EXT4_I(inode)->i_disksize = inode->i_size;
2034
2035         /* previous routine could use block we allocated */
2036         newblock = ext_pblock(&newex);
2037         __set_bit(BH_New, &bh_result->b_state);
2038
2039         ext4_ext_put_in_cache(inode, iblock, allocated, newblock,
2040                                 EXT4_EXT_CACHE_EXTENT);
2041 out:
2042         if (allocated > max_blocks)
2043                 allocated = max_blocks;
2044         ext4_ext_show_leaf(inode, path);
2045         __set_bit(BH_Mapped, &bh_result->b_state);
2046         bh_result->b_bdev = inode->i_sb->s_bdev;
2047         bh_result->b_blocknr = newblock;
2048 out2:
2049         if (path) {
2050                 ext4_ext_drop_refs(path);
2051                 kfree(path);
2052         }
2053         mutex_unlock(&EXT4_I(inode)->truncate_mutex);
2054
2055         return err ? err : allocated;
2056 }
2057
2058 void ext4_ext_truncate(struct inode * inode, struct page *page)
2059 {
2060         struct address_space *mapping = inode->i_mapping;
2061         struct super_block *sb = inode->i_sb;
2062         unsigned long last_block;
2063         handle_t *handle;
2064         int err = 0;
2065
2066         /*
2067          * probably first extent we're gonna free will be last in block
2068          */
2069         err = ext4_writepage_trans_blocks(inode) + 3;
2070         handle = ext4_journal_start(inode, err);
2071         if (IS_ERR(handle)) {
2072                 if (page) {
2073                         clear_highpage(page);
2074                         flush_dcache_page(page);
2075                         unlock_page(page);
2076                         page_cache_release(page);
2077                 }
2078                 return;
2079         }
2080
2081         if (page)
2082                 ext4_block_truncate_page(handle, page, mapping, inode->i_size);
2083
2084         mutex_lock(&EXT4_I(inode)->truncate_mutex);
2085         ext4_ext_invalidate_cache(inode);
2086
2087         /*
2088          * TODO: optimization is possible here.
2089          * Probably we need not scan at all,
2090          * because page truncation is enough.
2091          */
2092         if (ext4_orphan_add(handle, inode))
2093                 goto out_stop;
2094
2095         /* we have to know where to truncate from in crash case */
2096         EXT4_I(inode)->i_disksize = inode->i_size;
2097         ext4_mark_inode_dirty(handle, inode);
2098
2099         last_block = (inode->i_size + sb->s_blocksize - 1)
2100                         >> EXT4_BLOCK_SIZE_BITS(sb);
2101         err = ext4_ext_remove_space(inode, last_block);
2102
2103         /* In a multi-transaction truncate, we only make the final
2104          * transaction synchronous. */
2105         if (IS_SYNC(inode))
2106                 handle->h_sync = 1;
2107
2108 out_stop:
2109         /*
2110          * If this was a simple ftruncate() and the file will remain alive,
2111          * then we need to clear up the orphan record which we created above.
2112          * However, if this was a real unlink then we were called by
2113          * ext4_delete_inode(), and we allow that function to clean up the
2114          * orphan info for us.
2115          */
2116         if (inode->i_nlink)
2117                 ext4_orphan_del(handle, inode);
2118
2119         mutex_unlock(&EXT4_I(inode)->truncate_mutex);
2120         ext4_journal_stop(handle);
2121 }
2122
2123 /*
2124  * ext4_ext_writepage_trans_blocks:
2125  * calculate max number of blocks we could modify
2126  * in order to allocate new block for an inode
2127  */
2128 int ext4_ext_writepage_trans_blocks(struct inode *inode, int num)
2129 {
2130         int needed;
2131
2132         needed = ext4_ext_calc_credits_for_insert(inode, NULL);
2133
2134         /* caller wants to allocate num blocks, but note it includes sb */
2135         needed = needed * num - (num - 1);
2136
2137 #ifdef CONFIG_QUOTA
2138         needed += 2 * EXT4_QUOTA_TRANS_BLOCKS(inode->i_sb);
2139 #endif
2140
2141         return needed;
2142 }
2143
2144 EXPORT_SYMBOL(ext4_mark_inode_dirty);
2145 EXPORT_SYMBOL(ext4_ext_invalidate_cache);
2146 EXPORT_SYMBOL(ext4_ext_insert_extent);
2147 EXPORT_SYMBOL(ext4_ext_walk_space);
2148 EXPORT_SYMBOL(ext4_ext_find_goal);
2149 EXPORT_SYMBOL(ext4_ext_calc_credits_for_insert);
2150