[PATCH] ext4: uninitialised extent handling
[firefly-linux-kernel-4.4.55.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         /*
1086          * To allow future support for preallocated extents to be added
1087          * as an RO_COMPAT feature, refuse to merge to extents if
1088          * can result in the top bit of ee_len being set
1089          */
1090         if (le16_to_cpu(ex1->ee_len) + le16_to_cpu(ex2->ee_len) > EXT_MAX_LEN)
1091                 return 0;
1092 #ifdef AGRESSIVE_TEST
1093         if (le16_to_cpu(ex1->ee_len) >= 4)
1094                 return 0;
1095 #endif
1096
1097         if (ext_pblock(ex1) + le16_to_cpu(ex1->ee_len) == ext_pblock(ex2))
1098                 return 1;
1099         return 0;
1100 }
1101
1102 /*
1103  * this routine tries to merge requsted extent into the existing
1104  * extent or inserts requested extent as new one into the tree,
1105  * creating new leaf in no-space case
1106  */
1107 int ext4_ext_insert_extent(handle_t *handle, struct inode *inode,
1108                                 struct ext4_ext_path *path,
1109                                 struct ext4_extent *newext)
1110 {
1111         struct ext4_extent_header * eh;
1112         struct ext4_extent *ex, *fex;
1113         struct ext4_extent *nearex; /* nearest extent */
1114         struct ext4_ext_path *npath = NULL;
1115         int depth, len, err, next;
1116
1117         BUG_ON(newext->ee_len == 0);
1118         depth = ext_depth(inode);
1119         ex = path[depth].p_ext;
1120         BUG_ON(path[depth].p_hdr == NULL);
1121
1122         /* try to insert block into found extent and return */
1123         if (ex && ext4_can_extents_be_merged(inode, ex, newext)) {
1124                 ext_debug("append %d block to %d:%d (from "E3FSBLK")\n",
1125                                 le16_to_cpu(newext->ee_len),
1126                                 le32_to_cpu(ex->ee_block),
1127                                 le16_to_cpu(ex->ee_len), ext_pblock(ex));
1128                 if ((err = ext4_ext_get_access(handle, inode, path + depth)))
1129                         return err;
1130                 ex->ee_len = cpu_to_le16(le16_to_cpu(ex->ee_len)
1131                                          + le16_to_cpu(newext->ee_len));
1132                 eh = path[depth].p_hdr;
1133                 nearex = ex;
1134                 goto merge;
1135         }
1136
1137 repeat:
1138         depth = ext_depth(inode);
1139         eh = path[depth].p_hdr;
1140         if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max))
1141                 goto has_space;
1142
1143         /* probably next leaf has space for us? */
1144         fex = EXT_LAST_EXTENT(eh);
1145         next = ext4_ext_next_leaf_block(inode, path);
1146         if (le32_to_cpu(newext->ee_block) > le32_to_cpu(fex->ee_block)
1147             && next != EXT_MAX_BLOCK) {
1148                 ext_debug("next leaf block - %d\n", next);
1149                 BUG_ON(npath != NULL);
1150                 npath = ext4_ext_find_extent(inode, next, NULL);
1151                 if (IS_ERR(npath))
1152                         return PTR_ERR(npath);
1153                 BUG_ON(npath->p_depth != path->p_depth);
1154                 eh = npath[depth].p_hdr;
1155                 if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max)) {
1156                         ext_debug("next leaf isnt full(%d)\n",
1157                                   le16_to_cpu(eh->eh_entries));
1158                         path = npath;
1159                         goto repeat;
1160                 }
1161                 ext_debug("next leaf has no free space(%d,%d)\n",
1162                           le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
1163         }
1164
1165         /*
1166          * there is no free space in found leaf
1167          * we're gonna add new leaf in the tree
1168          */
1169         err = ext4_ext_create_new_leaf(handle, inode, path, newext);
1170         if (err)
1171                 goto cleanup;
1172         depth = ext_depth(inode);
1173         eh = path[depth].p_hdr;
1174
1175 has_space:
1176         nearex = path[depth].p_ext;
1177
1178         if ((err = ext4_ext_get_access(handle, inode, path + depth)))
1179                 goto cleanup;
1180
1181         if (!nearex) {
1182                 /* there is no extent in this leaf, create first one */
1183                 ext_debug("first extent in the leaf: %d:"E3FSBLK":%d\n",
1184                                 le32_to_cpu(newext->ee_block),
1185                                 ext_pblock(newext),
1186                                 le16_to_cpu(newext->ee_len));
1187                 path[depth].p_ext = EXT_FIRST_EXTENT(eh);
1188         } else if (le32_to_cpu(newext->ee_block)
1189                            > le32_to_cpu(nearex->ee_block)) {
1190 /*              BUG_ON(newext->ee_block == nearex->ee_block); */
1191                 if (nearex != EXT_LAST_EXTENT(eh)) {
1192                         len = EXT_MAX_EXTENT(eh) - nearex;
1193                         len = (len - 1) * sizeof(struct ext4_extent);
1194                         len = len < 0 ? 0 : len;
1195                         ext_debug("insert %d:"E3FSBLK":%d after: nearest 0x%p, "
1196                                         "move %d from 0x%p to 0x%p\n",
1197                                         le32_to_cpu(newext->ee_block),
1198                                         ext_pblock(newext),
1199                                         le16_to_cpu(newext->ee_len),
1200                                         nearex, len, nearex + 1, nearex + 2);
1201                         memmove(nearex + 2, nearex + 1, len);
1202                 }
1203                 path[depth].p_ext = nearex + 1;
1204         } else {
1205                 BUG_ON(newext->ee_block == nearex->ee_block);
1206                 len = (EXT_MAX_EXTENT(eh) - nearex) * sizeof(struct ext4_extent);
1207                 len = len < 0 ? 0 : len;
1208                 ext_debug("insert %d:"E3FSBLK":%d before: nearest 0x%p, "
1209                                 "move %d from 0x%p to 0x%p\n",
1210                                 le32_to_cpu(newext->ee_block),
1211                                 ext_pblock(newext),
1212                                 le16_to_cpu(newext->ee_len),
1213                                 nearex, len, nearex + 1, nearex + 2);
1214                 memmove(nearex + 1, nearex, len);
1215                 path[depth].p_ext = nearex;
1216         }
1217
1218         eh->eh_entries = cpu_to_le16(le16_to_cpu(eh->eh_entries)+1);
1219         nearex = path[depth].p_ext;
1220         nearex->ee_block = newext->ee_block;
1221         nearex->ee_start = newext->ee_start;
1222         nearex->ee_start_hi = newext->ee_start_hi;
1223         nearex->ee_len = newext->ee_len;
1224
1225 merge:
1226         /* try to merge extents to the right */
1227         while (nearex < EXT_LAST_EXTENT(eh)) {
1228                 if (!ext4_can_extents_be_merged(inode, nearex, nearex + 1))
1229                         break;
1230                 /* merge with next extent! */
1231                 nearex->ee_len = cpu_to_le16(le16_to_cpu(nearex->ee_len)
1232                                              + le16_to_cpu(nearex[1].ee_len));
1233                 if (nearex + 1 < EXT_LAST_EXTENT(eh)) {
1234                         len = (EXT_LAST_EXTENT(eh) - nearex - 1)
1235                                         * sizeof(struct ext4_extent);
1236                         memmove(nearex + 1, nearex + 2, len);
1237                 }
1238                 eh->eh_entries = cpu_to_le16(le16_to_cpu(eh->eh_entries)-1);
1239                 BUG_ON(eh->eh_entries == 0);
1240         }
1241
1242         /* try to merge extents to the left */
1243
1244         /* time to correct all indexes above */
1245         err = ext4_ext_correct_indexes(handle, inode, path);
1246         if (err)
1247                 goto cleanup;
1248
1249         err = ext4_ext_dirty(handle, inode, path + depth);
1250
1251 cleanup:
1252         if (npath) {
1253                 ext4_ext_drop_refs(npath);
1254                 kfree(npath);
1255         }
1256         ext4_ext_tree_changed(inode);
1257         ext4_ext_invalidate_cache(inode);
1258         return err;
1259 }
1260
1261 int ext4_ext_walk_space(struct inode *inode, unsigned long block,
1262                         unsigned long num, ext_prepare_callback func,
1263                         void *cbdata)
1264 {
1265         struct ext4_ext_path *path = NULL;
1266         struct ext4_ext_cache cbex;
1267         struct ext4_extent *ex;
1268         unsigned long next, start = 0, end = 0;
1269         unsigned long last = block + num;
1270         int depth, exists, err = 0;
1271
1272         BUG_ON(func == NULL);
1273         BUG_ON(inode == NULL);
1274
1275         while (block < last && block != EXT_MAX_BLOCK) {
1276                 num = last - block;
1277                 /* find extent for this block */
1278                 path = ext4_ext_find_extent(inode, block, path);
1279                 if (IS_ERR(path)) {
1280                         err = PTR_ERR(path);
1281                         path = NULL;
1282                         break;
1283                 }
1284
1285                 depth = ext_depth(inode);
1286                 BUG_ON(path[depth].p_hdr == NULL);
1287                 ex = path[depth].p_ext;
1288                 next = ext4_ext_next_allocated_block(path);
1289
1290                 exists = 0;
1291                 if (!ex) {
1292                         /* there is no extent yet, so try to allocate
1293                          * all requested space */
1294                         start = block;
1295                         end = block + num;
1296                 } else if (le32_to_cpu(ex->ee_block) > block) {
1297                         /* need to allocate space before found extent */
1298                         start = block;
1299                         end = le32_to_cpu(ex->ee_block);
1300                         if (block + num < end)
1301                                 end = block + num;
1302                 } else if (block >=
1303                              le32_to_cpu(ex->ee_block) + le16_to_cpu(ex->ee_len)) {
1304                         /* need to allocate space after found extent */
1305                         start = block;
1306                         end = block + num;
1307                         if (end >= next)
1308                                 end = next;
1309                 } else if (block >= le32_to_cpu(ex->ee_block)) {
1310                         /*
1311                          * some part of requested space is covered
1312                          * by found extent
1313                          */
1314                         start = block;
1315                         end = le32_to_cpu(ex->ee_block) + le16_to_cpu(ex->ee_len);
1316                         if (block + num < end)
1317                                 end = block + num;
1318                         exists = 1;
1319                 } else {
1320                         BUG();
1321                 }
1322                 BUG_ON(end <= start);
1323
1324                 if (!exists) {
1325                         cbex.ec_block = start;
1326                         cbex.ec_len = end - start;
1327                         cbex.ec_start = 0;
1328                         cbex.ec_type = EXT4_EXT_CACHE_GAP;
1329                 } else {
1330                         cbex.ec_block = le32_to_cpu(ex->ee_block);
1331                         cbex.ec_len = le16_to_cpu(ex->ee_len);
1332                         cbex.ec_start = ext_pblock(ex);
1333                         cbex.ec_type = EXT4_EXT_CACHE_EXTENT;
1334                 }
1335
1336                 BUG_ON(cbex.ec_len == 0);
1337                 err = func(inode, path, &cbex, cbdata);
1338                 ext4_ext_drop_refs(path);
1339
1340                 if (err < 0)
1341                         break;
1342                 if (err == EXT_REPEAT)
1343                         continue;
1344                 else if (err == EXT_BREAK) {
1345                         err = 0;
1346                         break;
1347                 }
1348
1349                 if (ext_depth(inode) != depth) {
1350                         /* depth was changed. we have to realloc path */
1351                         kfree(path);
1352                         path = NULL;
1353                 }
1354
1355                 block = cbex.ec_block + cbex.ec_len;
1356         }
1357
1358         if (path) {
1359                 ext4_ext_drop_refs(path);
1360                 kfree(path);
1361         }
1362
1363         return err;
1364 }
1365
1366 static inline void
1367 ext4_ext_put_in_cache(struct inode *inode, __u32 block,
1368                         __u32 len, __u32 start, int type)
1369 {
1370         struct ext4_ext_cache *cex;
1371         BUG_ON(len == 0);
1372         cex = &EXT4_I(inode)->i_cached_extent;
1373         cex->ec_type = type;
1374         cex->ec_block = block;
1375         cex->ec_len = len;
1376         cex->ec_start = start;
1377 }
1378
1379 /*
1380  * this routine calculate boundaries of the gap requested block fits into
1381  * and cache this gap
1382  */
1383 static inline void
1384 ext4_ext_put_gap_in_cache(struct inode *inode, struct ext4_ext_path *path,
1385                                 unsigned long block)
1386 {
1387         int depth = ext_depth(inode);
1388         unsigned long lblock, len;
1389         struct ext4_extent *ex;
1390
1391         ex = path[depth].p_ext;
1392         if (ex == NULL) {
1393                 /* there is no extent yet, so gap is [0;-] */
1394                 lblock = 0;
1395                 len = EXT_MAX_BLOCK;
1396                 ext_debug("cache gap(whole file):");
1397         } else if (block < le32_to_cpu(ex->ee_block)) {
1398                 lblock = block;
1399                 len = le32_to_cpu(ex->ee_block) - block;
1400                 ext_debug("cache gap(before): %lu [%lu:%lu]",
1401                                 (unsigned long) block,
1402                                 (unsigned long) le32_to_cpu(ex->ee_block),
1403                                 (unsigned long) le16_to_cpu(ex->ee_len));
1404         } else if (block >= le32_to_cpu(ex->ee_block)
1405                             + le16_to_cpu(ex->ee_len)) {
1406                 lblock = le32_to_cpu(ex->ee_block)
1407                          + le16_to_cpu(ex->ee_len);
1408                 len = ext4_ext_next_allocated_block(path);
1409                 ext_debug("cache gap(after): [%lu:%lu] %lu",
1410                                 (unsigned long) le32_to_cpu(ex->ee_block),
1411                                 (unsigned long) le16_to_cpu(ex->ee_len),
1412                                 (unsigned long) block);
1413                 BUG_ON(len == lblock);
1414                 len = len - lblock;
1415         } else {
1416                 lblock = len = 0;
1417                 BUG();
1418         }
1419
1420         ext_debug(" -> %lu:%lu\n", (unsigned long) lblock, len);
1421         ext4_ext_put_in_cache(inode, lblock, len, 0, EXT4_EXT_CACHE_GAP);
1422 }
1423
1424 static inline int
1425 ext4_ext_in_cache(struct inode *inode, unsigned long block,
1426                         struct ext4_extent *ex)
1427 {
1428         struct ext4_ext_cache *cex;
1429
1430         cex = &EXT4_I(inode)->i_cached_extent;
1431
1432         /* has cache valid data? */
1433         if (cex->ec_type == EXT4_EXT_CACHE_NO)
1434                 return EXT4_EXT_CACHE_NO;
1435
1436         BUG_ON(cex->ec_type != EXT4_EXT_CACHE_GAP &&
1437                         cex->ec_type != EXT4_EXT_CACHE_EXTENT);
1438         if (block >= cex->ec_block && block < cex->ec_block + cex->ec_len) {
1439                 ex->ee_block = cpu_to_le32(cex->ec_block);
1440                 ext4_ext_store_pblock(ex, cex->ec_start);
1441                 ex->ee_len = cpu_to_le16(cex->ec_len);
1442                 ext_debug("%lu cached by %lu:%lu:"E3FSBLK"\n",
1443                                 (unsigned long) block,
1444                                 (unsigned long) cex->ec_block,
1445                                 (unsigned long) cex->ec_len,
1446                                 cex->ec_start);
1447                 return cex->ec_type;
1448         }
1449
1450         /* not in cache */
1451         return EXT4_EXT_CACHE_NO;
1452 }
1453
1454 /*
1455  * routine removes index from the index block
1456  * it's used in truncate case only. thus all requests are for
1457  * last index in the block only
1458  */
1459 int ext4_ext_rm_idx(handle_t *handle, struct inode *inode,
1460                         struct ext4_ext_path *path)
1461 {
1462         struct buffer_head *bh;
1463         int err;
1464         ext4_fsblk_t leaf;
1465
1466         /* free index block */
1467         path--;
1468         leaf = idx_pblock(path->p_idx);
1469         BUG_ON(path->p_hdr->eh_entries == 0);
1470         if ((err = ext4_ext_get_access(handle, inode, path)))
1471                 return err;
1472         path->p_hdr->eh_entries = cpu_to_le16(le16_to_cpu(path->p_hdr->eh_entries)-1);
1473         if ((err = ext4_ext_dirty(handle, inode, path)))
1474                 return err;
1475         ext_debug("index is empty, remove it, free block "E3FSBLK"\n", leaf);
1476         bh = sb_find_get_block(inode->i_sb, leaf);
1477         ext4_forget(handle, 1, inode, bh, leaf);
1478         ext4_free_blocks(handle, inode, leaf, 1);
1479         return err;
1480 }
1481
1482 /*
1483  * This routine returns max. credits extent tree can consume.
1484  * It should be OK for low-performance paths like ->writepage()
1485  * To allow many writing process to fit a single transaction,
1486  * caller should calculate credits under truncate_mutex and
1487  * pass actual path.
1488  */
1489 int inline ext4_ext_calc_credits_for_insert(struct inode *inode,
1490                                                 struct ext4_ext_path *path)
1491 {
1492         int depth, needed;
1493
1494         if (path) {
1495                 /* probably there is space in leaf? */
1496                 depth = ext_depth(inode);
1497                 if (le16_to_cpu(path[depth].p_hdr->eh_entries)
1498                                 < le16_to_cpu(path[depth].p_hdr->eh_max))
1499                         return 1;
1500         }
1501
1502         /*
1503          * given 32bit logical block (4294967296 blocks), max. tree
1504          * can be 4 levels in depth -- 4 * 340^4 == 53453440000.
1505          * let's also add one more level for imbalance.
1506          */
1507         depth = 5;
1508
1509         /* allocation of new data block(s) */
1510         needed = 2;
1511
1512         /*
1513          * tree can be full, so it'd need to grow in depth:
1514          * allocation + old root + new root
1515          */
1516         needed += 2 + 1 + 1;
1517
1518         /*
1519          * Index split can happen, we'd need:
1520          *    allocate intermediate indexes (bitmap + group)
1521          *  + change two blocks at each level, but root (already included)
1522          */
1523         needed = (depth * 2) + (depth * 2);
1524
1525         /* any allocation modifies superblock */
1526         needed += 1;
1527
1528         return needed;
1529 }
1530
1531 static int ext4_remove_blocks(handle_t *handle, struct inode *inode,
1532                                 struct ext4_extent *ex,
1533                                 unsigned long from, unsigned long to)
1534 {
1535         struct buffer_head *bh;
1536         int i;
1537
1538 #ifdef EXTENTS_STATS
1539         {
1540                 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1541                 unsigned short ee_len =  le16_to_cpu(ex->ee_len);
1542                 spin_lock(&sbi->s_ext_stats_lock);
1543                 sbi->s_ext_blocks += ee_len;
1544                 sbi->s_ext_extents++;
1545                 if (ee_len < sbi->s_ext_min)
1546                         sbi->s_ext_min = ee_len;
1547                 if (ee_len > sbi->s_ext_max)
1548                         sbi->s_ext_max = ee_len;
1549                 if (ext_depth(inode) > sbi->s_depth_max)
1550                         sbi->s_depth_max = ext_depth(inode);
1551                 spin_unlock(&sbi->s_ext_stats_lock);
1552         }
1553 #endif
1554         if (from >= le32_to_cpu(ex->ee_block)
1555             && to == le32_to_cpu(ex->ee_block) + le16_to_cpu(ex->ee_len) - 1) {
1556                 /* tail removal */
1557                 unsigned long num;
1558                 ext4_fsblk_t start;
1559                 num = le32_to_cpu(ex->ee_block) + le16_to_cpu(ex->ee_len) - from;
1560                 start = ext_pblock(ex) + le16_to_cpu(ex->ee_len) - num;
1561                 ext_debug("free last %lu blocks starting "E3FSBLK"\n", num, start);
1562                 for (i = 0; i < num; i++) {
1563                         bh = sb_find_get_block(inode->i_sb, start + i);
1564                         ext4_forget(handle, 0, inode, bh, start + i);
1565                 }
1566                 ext4_free_blocks(handle, inode, start, num);
1567         } else if (from == le32_to_cpu(ex->ee_block)
1568                    && to <= le32_to_cpu(ex->ee_block) + le16_to_cpu(ex->ee_len) - 1) {
1569                 printk("strange request: removal %lu-%lu from %u:%u\n",
1570                        from, to, le32_to_cpu(ex->ee_block), le16_to_cpu(ex->ee_len));
1571         } else {
1572                 printk("strange request: removal(2) %lu-%lu from %u:%u\n",
1573                        from, to, le32_to_cpu(ex->ee_block), le16_to_cpu(ex->ee_len));
1574         }
1575         return 0;
1576 }
1577
1578 static int
1579 ext4_ext_rm_leaf(handle_t *handle, struct inode *inode,
1580                 struct ext4_ext_path *path, unsigned long start)
1581 {
1582         int err = 0, correct_index = 0;
1583         int depth = ext_depth(inode), credits;
1584         struct ext4_extent_header *eh;
1585         unsigned a, b, block, num;
1586         unsigned long ex_ee_block;
1587         unsigned short ex_ee_len;
1588         struct ext4_extent *ex;
1589
1590         ext_debug("truncate since %lu in leaf\n", start);
1591         if (!path[depth].p_hdr)
1592                 path[depth].p_hdr = ext_block_hdr(path[depth].p_bh);
1593         eh = path[depth].p_hdr;
1594         BUG_ON(eh == NULL);
1595         BUG_ON(le16_to_cpu(eh->eh_entries) > le16_to_cpu(eh->eh_max));
1596         BUG_ON(eh->eh_magic != EXT4_EXT_MAGIC);
1597
1598         /* find where to start removing */
1599         ex = EXT_LAST_EXTENT(eh);
1600
1601         ex_ee_block = le32_to_cpu(ex->ee_block);
1602         ex_ee_len = le16_to_cpu(ex->ee_len);
1603
1604         while (ex >= EXT_FIRST_EXTENT(eh) &&
1605                         ex_ee_block + ex_ee_len > start) {
1606                 ext_debug("remove ext %lu:%u\n", ex_ee_block, ex_ee_len);
1607                 path[depth].p_ext = ex;
1608
1609                 a = ex_ee_block > start ? ex_ee_block : start;
1610                 b = ex_ee_block + ex_ee_len - 1 < EXT_MAX_BLOCK ?
1611                         ex_ee_block + ex_ee_len - 1 : EXT_MAX_BLOCK;
1612
1613                 ext_debug("  border %u:%u\n", a, b);
1614
1615                 if (a != ex_ee_block && b != ex_ee_block + ex_ee_len - 1) {
1616                         block = 0;
1617                         num = 0;
1618                         BUG();
1619                 } else if (a != ex_ee_block) {
1620                         /* remove tail of the extent */
1621                         block = ex_ee_block;
1622                         num = a - block;
1623                 } else if (b != ex_ee_block + ex_ee_len - 1) {
1624                         /* remove head of the extent */
1625                         block = a;
1626                         num = b - a;
1627                         /* there is no "make a hole" API yet */
1628                         BUG();
1629                 } else {
1630                         /* remove whole extent: excellent! */
1631                         block = ex_ee_block;
1632                         num = 0;
1633                         BUG_ON(a != ex_ee_block);
1634                         BUG_ON(b != ex_ee_block + ex_ee_len - 1);
1635                 }
1636
1637                 /* at present, extent can't cross block group */
1638                 /* leaf + bitmap + group desc + sb + inode */
1639                 credits = 5;
1640                 if (ex == EXT_FIRST_EXTENT(eh)) {
1641                         correct_index = 1;
1642                         credits += (ext_depth(inode)) + 1;
1643                 }
1644 #ifdef CONFIG_QUOTA
1645                 credits += 2 * EXT4_QUOTA_TRANS_BLOCKS(inode->i_sb);
1646 #endif
1647
1648                 handle = ext4_ext_journal_restart(handle, credits);
1649                 if (IS_ERR(handle)) {
1650                         err = PTR_ERR(handle);
1651                         goto out;
1652                 }
1653
1654                 err = ext4_ext_get_access(handle, inode, path + depth);
1655                 if (err)
1656                         goto out;
1657
1658                 err = ext4_remove_blocks(handle, inode, ex, a, b);
1659                 if (err)
1660                         goto out;
1661
1662                 if (num == 0) {
1663                         /* this extent is removed entirely mark slot unused */
1664                         ext4_ext_store_pblock(ex, 0);
1665                         eh->eh_entries = cpu_to_le16(le16_to_cpu(eh->eh_entries)-1);
1666                 }
1667
1668                 ex->ee_block = cpu_to_le32(block);
1669                 ex->ee_len = cpu_to_le16(num);
1670
1671                 err = ext4_ext_dirty(handle, inode, path + depth);
1672                 if (err)
1673                         goto out;
1674
1675                 ext_debug("new extent: %u:%u:"E3FSBLK"\n", block, num,
1676                                 ext_pblock(ex));
1677                 ex--;
1678                 ex_ee_block = le32_to_cpu(ex->ee_block);
1679                 ex_ee_len = le16_to_cpu(ex->ee_len);
1680         }
1681
1682         if (correct_index && eh->eh_entries)
1683                 err = ext4_ext_correct_indexes(handle, inode, path);
1684
1685         /* if this leaf is free, then we should
1686          * remove it from index block above */
1687         if (err == 0 && eh->eh_entries == 0 && path[depth].p_bh != NULL)
1688                 err = ext4_ext_rm_idx(handle, inode, path + depth);
1689
1690 out:
1691         return err;
1692 }
1693
1694 /*
1695  * returns 1 if current index have to be freed (even partial)
1696  */
1697 static int inline
1698 ext4_ext_more_to_rm(struct ext4_ext_path *path)
1699 {
1700         BUG_ON(path->p_idx == NULL);
1701
1702         if (path->p_idx < EXT_FIRST_INDEX(path->p_hdr))
1703                 return 0;
1704
1705         /*
1706          * if truncate on deeper level happened it it wasn't partial
1707          * so we have to consider current index for truncation
1708          */
1709         if (le16_to_cpu(path->p_hdr->eh_entries) == path->p_block)
1710                 return 0;
1711         return 1;
1712 }
1713
1714 int ext4_ext_remove_space(struct inode *inode, unsigned long start)
1715 {
1716         struct super_block *sb = inode->i_sb;
1717         int depth = ext_depth(inode);
1718         struct ext4_ext_path *path;
1719         handle_t *handle;
1720         int i = 0, err = 0;
1721
1722         ext_debug("truncate since %lu\n", start);
1723
1724         /* probably first extent we're gonna free will be last in block */
1725         handle = ext4_journal_start(inode, depth + 1);
1726         if (IS_ERR(handle))
1727                 return PTR_ERR(handle);
1728
1729         ext4_ext_invalidate_cache(inode);
1730
1731         /*
1732          * we start scanning from right side freeing all the blocks
1733          * after i_size and walking into the deep
1734          */
1735         path = kmalloc(sizeof(struct ext4_ext_path) * (depth + 1), GFP_KERNEL);
1736         if (path == NULL) {
1737                 ext4_journal_stop(handle);
1738                 return -ENOMEM;
1739         }
1740         memset(path, 0, sizeof(struct ext4_ext_path) * (depth + 1));
1741         path[0].p_hdr = ext_inode_hdr(inode);
1742         if (ext4_ext_check_header(__FUNCTION__, inode, path[0].p_hdr)) {
1743                 err = -EIO;
1744                 goto out;
1745         }
1746         path[0].p_depth = depth;
1747
1748         while (i >= 0 && err == 0) {
1749                 if (i == depth) {
1750                         /* this is leaf block */
1751                         err = ext4_ext_rm_leaf(handle, inode, path, start);
1752                         /* root level have p_bh == NULL, brelse() eats this */
1753                         brelse(path[i].p_bh);
1754                         path[i].p_bh = NULL;
1755                         i--;
1756                         continue;
1757                 }
1758
1759                 /* this is index block */
1760                 if (!path[i].p_hdr) {
1761                         ext_debug("initialize header\n");
1762                         path[i].p_hdr = ext_block_hdr(path[i].p_bh);
1763                         if (ext4_ext_check_header(__FUNCTION__, inode,
1764                                                         path[i].p_hdr)) {
1765                                 err = -EIO;
1766                                 goto out;
1767                         }
1768                 }
1769
1770                 BUG_ON(le16_to_cpu(path[i].p_hdr->eh_entries)
1771                            > le16_to_cpu(path[i].p_hdr->eh_max));
1772                 BUG_ON(path[i].p_hdr->eh_magic != EXT4_EXT_MAGIC);
1773
1774                 if (!path[i].p_idx) {
1775                         /* this level hasn't touched yet */
1776                         path[i].p_idx = EXT_LAST_INDEX(path[i].p_hdr);
1777                         path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries)+1;
1778                         ext_debug("init index ptr: hdr 0x%p, num %d\n",
1779                                   path[i].p_hdr,
1780                                   le16_to_cpu(path[i].p_hdr->eh_entries));
1781                 } else {
1782                         /* we've already was here, see at next index */
1783                         path[i].p_idx--;
1784                 }
1785
1786                 ext_debug("level %d - index, first 0x%p, cur 0x%p\n",
1787                                 i, EXT_FIRST_INDEX(path[i].p_hdr),
1788                                 path[i].p_idx);
1789                 if (ext4_ext_more_to_rm(path + i)) {
1790                         /* go to the next level */
1791                         ext_debug("move to level %d (block "E3FSBLK")\n",
1792                                   i + 1, idx_pblock(path[i].p_idx));
1793                         memset(path + i + 1, 0, sizeof(*path));
1794                         path[i+1].p_bh =
1795                                 sb_bread(sb, idx_pblock(path[i].p_idx));
1796                         if (!path[i+1].p_bh) {
1797                                 /* should we reset i_size? */
1798                                 err = -EIO;
1799                                 break;
1800                         }
1801
1802                         /* put actual number of indexes to know is this
1803                          * number got changed at the next iteration */
1804                         path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries);
1805                         i++;
1806                 } else {
1807                         /* we finish processing this index, go up */
1808                         if (path[i].p_hdr->eh_entries == 0 && i > 0) {
1809                                 /* index is empty, remove it
1810                                  * handle must be already prepared by the
1811                                  * truncatei_leaf() */
1812                                 err = ext4_ext_rm_idx(handle, inode, path + i);
1813                         }
1814                         /* root level have p_bh == NULL, brelse() eats this */
1815                         brelse(path[i].p_bh);
1816                         path[i].p_bh = NULL;
1817                         i--;
1818                         ext_debug("return to level %d\n", i);
1819                 }
1820         }
1821
1822         /* TODO: flexible tree reduction should be here */
1823         if (path->p_hdr->eh_entries == 0) {
1824                 /*
1825                  * truncate to zero freed all the tree
1826                  * so, we need to correct eh_depth
1827                  */
1828                 err = ext4_ext_get_access(handle, inode, path);
1829                 if (err == 0) {
1830                         ext_inode_hdr(inode)->eh_depth = 0;
1831                         ext_inode_hdr(inode)->eh_max =
1832                                 cpu_to_le16(ext4_ext_space_root(inode));
1833                         err = ext4_ext_dirty(handle, inode, path);
1834                 }
1835         }
1836 out:
1837         ext4_ext_tree_changed(inode);
1838         ext4_ext_drop_refs(path);
1839         kfree(path);
1840         ext4_journal_stop(handle);
1841
1842         return err;
1843 }
1844
1845 /*
1846  * called at mount time
1847  */
1848 void ext4_ext_init(struct super_block *sb)
1849 {
1850         /*
1851          * possible initialization would be here
1852          */
1853
1854         if (test_opt(sb, EXTENTS)) {
1855                 printk("EXT4-fs: file extents enabled");
1856 #ifdef AGRESSIVE_TEST
1857                 printk(", agressive tests");
1858 #endif
1859 #ifdef CHECK_BINSEARCH
1860                 printk(", check binsearch");
1861 #endif
1862 #ifdef EXTENTS_STATS
1863                 printk(", stats");
1864 #endif
1865                 printk("\n");
1866 #ifdef EXTENTS_STATS
1867                 spin_lock_init(&EXT4_SB(sb)->s_ext_stats_lock);
1868                 EXT4_SB(sb)->s_ext_min = 1 << 30;
1869                 EXT4_SB(sb)->s_ext_max = 0;
1870 #endif
1871         }
1872 }
1873
1874 /*
1875  * called at umount time
1876  */
1877 void ext4_ext_release(struct super_block *sb)
1878 {
1879         if (!test_opt(sb, EXTENTS))
1880                 return;
1881
1882 #ifdef EXTENTS_STATS
1883         if (EXT4_SB(sb)->s_ext_blocks && EXT4_SB(sb)->s_ext_extents) {
1884                 struct ext4_sb_info *sbi = EXT4_SB(sb);
1885                 printk(KERN_ERR "EXT4-fs: %lu blocks in %lu extents (%lu ave)\n",
1886                         sbi->s_ext_blocks, sbi->s_ext_extents,
1887                         sbi->s_ext_blocks / sbi->s_ext_extents);
1888                 printk(KERN_ERR "EXT4-fs: extents: %lu min, %lu max, max depth %lu\n",
1889                         sbi->s_ext_min, sbi->s_ext_max, sbi->s_depth_max);
1890         }
1891 #endif
1892 }
1893
1894 int ext4_ext_get_blocks(handle_t *handle, struct inode *inode,
1895                         ext4_fsblk_t iblock,
1896                         unsigned long max_blocks, struct buffer_head *bh_result,
1897                         int create, int extend_disksize)
1898 {
1899         struct ext4_ext_path *path = NULL;
1900         struct ext4_extent newex, *ex;
1901         ext4_fsblk_t goal, newblock;
1902         int err = 0, depth;
1903         unsigned long allocated = 0;
1904
1905         __clear_bit(BH_New, &bh_result->b_state);
1906         ext_debug("blocks %d/%lu requested for inode %u\n", (int) iblock,
1907                         max_blocks, (unsigned) inode->i_ino);
1908         mutex_lock(&EXT4_I(inode)->truncate_mutex);
1909
1910         /* check in cache */
1911         if ((goal = ext4_ext_in_cache(inode, iblock, &newex))) {
1912                 if (goal == EXT4_EXT_CACHE_GAP) {
1913                         if (!create) {
1914                                 /* block isn't allocated yet and
1915                                  * user don't want to allocate it */
1916                                 goto out2;
1917                         }
1918                         /* we should allocate requested block */
1919                 } else if (goal == EXT4_EXT_CACHE_EXTENT) {
1920                         /* block is already allocated */
1921                         newblock = iblock
1922                                    - le32_to_cpu(newex.ee_block)
1923                                    + ext_pblock(&newex);
1924                         /* number of remain blocks in the extent */
1925                         allocated = le16_to_cpu(newex.ee_len) -
1926                                         (iblock - le32_to_cpu(newex.ee_block));
1927                         goto out;
1928                 } else {
1929                         BUG();
1930                 }
1931         }
1932
1933         /* find extent for this block */
1934         path = ext4_ext_find_extent(inode, iblock, NULL);
1935         if (IS_ERR(path)) {
1936                 err = PTR_ERR(path);
1937                 path = NULL;
1938                 goto out2;
1939         }
1940
1941         depth = ext_depth(inode);
1942
1943         /*
1944          * consistent leaf must not be empty
1945          * this situations is possible, though, _during_ tree modification
1946          * this is why assert can't be put in ext4_ext_find_extent()
1947          */
1948         BUG_ON(path[depth].p_ext == NULL && depth != 0);
1949
1950         if ((ex = path[depth].p_ext)) {
1951                 unsigned long ee_block = le32_to_cpu(ex->ee_block);
1952                 ext4_fsblk_t ee_start = ext_pblock(ex);
1953                 unsigned short ee_len  = le16_to_cpu(ex->ee_len);
1954
1955                 /*
1956                  * Allow future support for preallocated extents to be added
1957                  * as an RO_COMPAT feature:
1958                  * Uninitialized extents are treated as holes, except that
1959                  * we avoid (fail) allocating new blocks during a write.
1960                  */
1961                 if (ee_len > EXT_MAX_LEN)
1962                         goto out2;
1963                 /* if found exent covers block, simple return it */
1964                 if (iblock >= ee_block && iblock < ee_block + ee_len) {
1965                         newblock = iblock - ee_block + ee_start;
1966                         /* number of remain blocks in the extent */
1967                         allocated = ee_len - (iblock - ee_block);
1968                         ext_debug("%d fit into %lu:%d -> "E3FSBLK"\n", (int) iblock,
1969                                         ee_block, ee_len, newblock);
1970                         ext4_ext_put_in_cache(inode, ee_block, ee_len,
1971                                                 ee_start, EXT4_EXT_CACHE_EXTENT);
1972                         goto out;
1973                 }
1974         }
1975
1976         /*
1977          * requested block isn't allocated yet
1978          * we couldn't try to create block if create flag is zero
1979          */
1980         if (!create) {
1981                 /* put just found gap into cache to speedup subsequest reqs */
1982                 ext4_ext_put_gap_in_cache(inode, path, iblock);
1983                 goto out2;
1984         }
1985         /*
1986          * Okay, we need to do block allocation.  Lazily initialize the block
1987          * allocation info here if necessary
1988         */
1989         if (S_ISREG(inode->i_mode) && (!EXT4_I(inode)->i_block_alloc_info))
1990                 ext4_init_block_alloc_info(inode);
1991
1992         /* allocate new block */
1993         goal = ext4_ext_find_goal(inode, path, iblock);
1994         allocated = max_blocks;
1995         newblock = ext4_new_blocks(handle, inode, goal, &allocated, &err);
1996         if (!newblock)
1997                 goto out2;
1998         ext_debug("allocate new block: goal "E3FSBLK", found "E3FSBLK"/%lu\n",
1999                         goal, newblock, allocated);
2000
2001         /* try to insert new extent into found leaf and return */
2002         newex.ee_block = cpu_to_le32(iblock);
2003         ext4_ext_store_pblock(&newex, newblock);
2004         newex.ee_len = cpu_to_le16(allocated);
2005         err = ext4_ext_insert_extent(handle, inode, path, &newex);
2006         if (err)
2007                 goto out2;
2008
2009         if (extend_disksize && inode->i_size > EXT4_I(inode)->i_disksize)
2010                 EXT4_I(inode)->i_disksize = inode->i_size;
2011
2012         /* previous routine could use block we allocated */
2013         newblock = ext_pblock(&newex);
2014         __set_bit(BH_New, &bh_result->b_state);
2015
2016         ext4_ext_put_in_cache(inode, iblock, allocated, newblock,
2017                                 EXT4_EXT_CACHE_EXTENT);
2018 out:
2019         if (allocated > max_blocks)
2020                 allocated = max_blocks;
2021         ext4_ext_show_leaf(inode, path);
2022         __set_bit(BH_Mapped, &bh_result->b_state);
2023         bh_result->b_bdev = inode->i_sb->s_bdev;
2024         bh_result->b_blocknr = newblock;
2025 out2:
2026         if (path) {
2027                 ext4_ext_drop_refs(path);
2028                 kfree(path);
2029         }
2030         mutex_unlock(&EXT4_I(inode)->truncate_mutex);
2031
2032         return err ? err : allocated;
2033 }
2034
2035 void ext4_ext_truncate(struct inode * inode, struct page *page)
2036 {
2037         struct address_space *mapping = inode->i_mapping;
2038         struct super_block *sb = inode->i_sb;
2039         unsigned long last_block;
2040         handle_t *handle;
2041         int err = 0;
2042
2043         /*
2044          * probably first extent we're gonna free will be last in block
2045          */
2046         err = ext4_writepage_trans_blocks(inode) + 3;
2047         handle = ext4_journal_start(inode, err);
2048         if (IS_ERR(handle)) {
2049                 if (page) {
2050                         clear_highpage(page);
2051                         flush_dcache_page(page);
2052                         unlock_page(page);
2053                         page_cache_release(page);
2054                 }
2055                 return;
2056         }
2057
2058         if (page)
2059                 ext4_block_truncate_page(handle, page, mapping, inode->i_size);
2060
2061         mutex_lock(&EXT4_I(inode)->truncate_mutex);
2062         ext4_ext_invalidate_cache(inode);
2063
2064         /*
2065          * TODO: optimization is possible here
2066          * probably we need not scaning at all,
2067          * because page truncation is enough
2068          */
2069         if (ext4_orphan_add(handle, inode))
2070                 goto out_stop;
2071
2072         /* we have to know where to truncate from in crash case */
2073         EXT4_I(inode)->i_disksize = inode->i_size;
2074         ext4_mark_inode_dirty(handle, inode);
2075
2076         last_block = (inode->i_size + sb->s_blocksize - 1)
2077                         >> EXT4_BLOCK_SIZE_BITS(sb);
2078         err = ext4_ext_remove_space(inode, last_block);
2079
2080         /* In a multi-transaction truncate, we only make the final
2081          * transaction synchronous */
2082         if (IS_SYNC(inode))
2083                 handle->h_sync = 1;
2084
2085 out_stop:
2086         /*
2087          * If this was a simple ftruncate(), and the file will remain alive
2088          * then we need to clear up the orphan record which we created above.
2089          * However, if this was a real unlink then we were called by
2090          * ext4_delete_inode(), and we allow that function to clean up the
2091          * orphan info for us.
2092          */
2093         if (inode->i_nlink)
2094                 ext4_orphan_del(handle, inode);
2095
2096         mutex_unlock(&EXT4_I(inode)->truncate_mutex);
2097         ext4_journal_stop(handle);
2098 }
2099
2100 /*
2101  * this routine calculate max number of blocks we could modify
2102  * in order to allocate new block for an inode
2103  */
2104 int ext4_ext_writepage_trans_blocks(struct inode *inode, int num)
2105 {
2106         int needed;
2107
2108         needed = ext4_ext_calc_credits_for_insert(inode, NULL);
2109
2110         /* caller want to allocate num blocks, but note it includes sb */
2111         needed = needed * num - (num - 1);
2112
2113 #ifdef CONFIG_QUOTA
2114         needed += 2 * EXT4_QUOTA_TRANS_BLOCKS(inode->i_sb);
2115 #endif
2116
2117         return needed;
2118 }
2119
2120 EXPORT_SYMBOL(ext4_mark_inode_dirty);
2121 EXPORT_SYMBOL(ext4_ext_invalidate_cache);
2122 EXPORT_SYMBOL(ext4_ext_insert_extent);
2123 EXPORT_SYMBOL(ext4_ext_walk_space);
2124 EXPORT_SYMBOL(ext4_ext_find_goal);
2125 EXPORT_SYMBOL(ext4_ext_calc_credits_for_insert);
2126