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