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