[PATCH] ext4 whitespace cleanups
[safe/jmp/linux-2.6] / fs / ext4 / extents.c
1 /*
2  * Copyright (c) 2003-2006, Cluster File Systems, Inc, info@clusterfs.com
3  * Written by Alex Tomas <alex@clusterfs.com>
4  *
5  * Architecture independence:
6  *   Copyright (c) 2005, Bull S.A.
7  *   Written by Pierre Peiffer <pierre.peiffer@bull.net>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License version 2 as
11  * published by the Free Software Foundation.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public Licens
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-
21  */
22
23 /*
24  * Extents support for EXT4
25  *
26  * TODO:
27  *   - ext4*_error() should be used in some situations
28  *   - analyze all BUG()/BUG_ON(), use -EIO where appropriate
29  *   - smart tree reduction
30  */
31
32 #include <linux/module.h>
33 #include <linux/fs.h>
34 #include <linux/time.h>
35 #include <linux/ext4_jbd2.h>
36 #include <linux/jbd.h>
37 #include <linux/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         if (err)
804                 goto cleanup;
805
806         err = ext4_ext_insert_index(handle, inode, path + at,
807                                     le32_to_cpu(border), newblock);
808
809 cleanup:
810         if (bh) {
811                 if (buffer_locked(bh))
812                         unlock_buffer(bh);
813                 brelse(bh);
814         }
815
816         if (err) {
817                 /* free all allocated blocks in error case */
818                 for (i = 0; i < depth; i++) {
819                         if (!ablocks[i])
820                                 continue;
821                         ext4_free_blocks(handle, inode, ablocks[i], 1);
822                 }
823         }
824         kfree(ablocks);
825
826         return err;
827 }
828
829 /*
830  * ext4_ext_grow_indepth:
831  * implements tree growing procedure:
832  * - allocates new block
833  * - moves top-level data (index block or leaf) into the new block
834  * - initializes new top-level, creating index that points to the
835  *   just created block
836  */
837 static int ext4_ext_grow_indepth(handle_t *handle, struct inode *inode,
838                                         struct ext4_ext_path *path,
839                                         struct ext4_extent *newext)
840 {
841         struct ext4_ext_path *curp = path;
842         struct ext4_extent_header *neh;
843         struct ext4_extent_idx *fidx;
844         struct buffer_head *bh;
845         ext4_fsblk_t newblock;
846         int err = 0;
847
848         newblock = ext4_ext_new_block(handle, inode, path, newext, &err);
849         if (newblock == 0)
850                 return err;
851
852         bh = sb_getblk(inode->i_sb, newblock);
853         if (!bh) {
854                 err = -EIO;
855                 ext4_std_error(inode->i_sb, err);
856                 return err;
857         }
858         lock_buffer(bh);
859
860         if ((err = ext4_journal_get_create_access(handle, bh))) {
861                 unlock_buffer(bh);
862                 goto out;
863         }
864
865         /* move top-level index/leaf into new block */
866         memmove(bh->b_data, curp->p_hdr, sizeof(EXT4_I(inode)->i_data));
867
868         /* set size of new block */
869         neh = ext_block_hdr(bh);
870         /* old root could have indexes or leaves
871          * so calculate e_max right way */
872         if (ext_depth(inode))
873           neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode));
874         else
875           neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode));
876         neh->eh_magic = EXT4_EXT_MAGIC;
877         set_buffer_uptodate(bh);
878         unlock_buffer(bh);
879
880         if ((err = ext4_journal_dirty_metadata(handle, bh)))
881                 goto out;
882
883         /* create index in new top-level index: num,max,pointer */
884         if ((err = ext4_ext_get_access(handle, inode, curp)))
885                 goto out;
886
887         curp->p_hdr->eh_magic = EXT4_EXT_MAGIC;
888         curp->p_hdr->eh_max = cpu_to_le16(ext4_ext_space_root_idx(inode));
889         curp->p_hdr->eh_entries = cpu_to_le16(1);
890         curp->p_idx = EXT_FIRST_INDEX(curp->p_hdr);
891         /* FIXME: it works, but actually path[0] can be index */
892         curp->p_idx->ei_block = EXT_FIRST_EXTENT(path[0].p_hdr)->ee_block;
893         ext4_idx_store_pblock(curp->p_idx, newblock);
894
895         neh = ext_inode_hdr(inode);
896         fidx = EXT_FIRST_INDEX(neh);
897         ext_debug("new root: num %d(%d), lblock %d, ptr %llu\n",
898                   le16_to_cpu(neh->eh_entries), le16_to_cpu(neh->eh_max),
899                   le32_to_cpu(fidx->ei_block), idx_pblock(fidx));
900
901         neh->eh_depth = cpu_to_le16(path->p_depth + 1);
902         err = ext4_ext_dirty(handle, inode, curp);
903 out:
904         brelse(bh);
905
906         return err;
907 }
908
909 /*
910  * ext4_ext_create_new_leaf:
911  * finds empty index and adds new leaf.
912  * if no free index is found, then it requests in-depth growing.
913  */
914 static int ext4_ext_create_new_leaf(handle_t *handle, struct inode *inode,
915                                         struct ext4_ext_path *path,
916                                         struct ext4_extent *newext)
917 {
918         struct ext4_ext_path *curp;
919         int depth, i, err = 0;
920
921 repeat:
922         i = depth = ext_depth(inode);
923
924         /* walk up to the tree and look for free index entry */
925         curp = path + depth;
926         while (i > 0 && !EXT_HAS_FREE_INDEX(curp)) {
927                 i--;
928                 curp--;
929         }
930
931         /* we use already allocated block for index block,
932          * so subsequent data blocks should be contiguous */
933         if (EXT_HAS_FREE_INDEX(curp)) {
934                 /* if we found index with free entry, then use that
935                  * entry: create all needed subtree and add new leaf */
936                 err = ext4_ext_split(handle, inode, path, newext, i);
937
938                 /* refill path */
939                 ext4_ext_drop_refs(path);
940                 path = ext4_ext_find_extent(inode,
941                                             le32_to_cpu(newext->ee_block),
942                                             path);
943                 if (IS_ERR(path))
944                         err = PTR_ERR(path);
945         } else {
946                 /* tree is full, time to grow in depth */
947                 err = ext4_ext_grow_indepth(handle, inode, path, newext);
948                 if (err)
949                         goto out;
950
951                 /* refill path */
952                 ext4_ext_drop_refs(path);
953                 path = ext4_ext_find_extent(inode,
954                                             le32_to_cpu(newext->ee_block),
955                                             path);
956                 if (IS_ERR(path)) {
957                         err = PTR_ERR(path);
958                         goto out;
959                 }
960
961                 /*
962                  * only first (depth 0 -> 1) produces free space;
963                  * in all other cases we have to split the grown tree
964                  */
965                 depth = ext_depth(inode);
966                 if (path[depth].p_hdr->eh_entries == path[depth].p_hdr->eh_max) {
967                         /* now we need to split */
968                         goto repeat;
969                 }
970         }
971
972 out:
973         return err;
974 }
975
976 /*
977  * ext4_ext_next_allocated_block:
978  * returns allocated block in subsequent extent or EXT_MAX_BLOCK.
979  * NOTE: it considers block number from index entry as
980  * allocated block. Thus, index entries have to be consistent
981  * with leaves.
982  */
983 static unsigned long
984 ext4_ext_next_allocated_block(struct ext4_ext_path *path)
985 {
986         int depth;
987
988         BUG_ON(path == NULL);
989         depth = path->p_depth;
990
991         if (depth == 0 && path->p_ext == NULL)
992                 return EXT_MAX_BLOCK;
993
994         while (depth >= 0) {
995                 if (depth == path->p_depth) {
996                         /* leaf */
997                         if (path[depth].p_ext !=
998                                         EXT_LAST_EXTENT(path[depth].p_hdr))
999                           return le32_to_cpu(path[depth].p_ext[1].ee_block);
1000                 } else {
1001                         /* index */
1002                         if (path[depth].p_idx !=
1003                                         EXT_LAST_INDEX(path[depth].p_hdr))
1004                           return le32_to_cpu(path[depth].p_idx[1].ei_block);
1005                 }
1006                 depth--;
1007         }
1008
1009         return EXT_MAX_BLOCK;
1010 }
1011
1012 /*
1013  * ext4_ext_next_leaf_block:
1014  * returns first allocated block from next leaf or EXT_MAX_BLOCK
1015  */
1016 static unsigned ext4_ext_next_leaf_block(struct inode *inode,
1017                                         struct ext4_ext_path *path)
1018 {
1019         int depth;
1020
1021         BUG_ON(path == NULL);
1022         depth = path->p_depth;
1023
1024         /* zero-tree has no leaf blocks at all */
1025         if (depth == 0)
1026                 return EXT_MAX_BLOCK;
1027
1028         /* go to index block */
1029         depth--;
1030
1031         while (depth >= 0) {
1032                 if (path[depth].p_idx !=
1033                                 EXT_LAST_INDEX(path[depth].p_hdr))
1034                   return le32_to_cpu(path[depth].p_idx[1].ei_block);
1035                 depth--;
1036         }
1037
1038         return EXT_MAX_BLOCK;
1039 }
1040
1041 /*
1042  * ext4_ext_correct_indexes:
1043  * if leaf gets modified and modified extent is first in the leaf,
1044  * then we have to correct all indexes above.
1045  * TODO: do we need to correct tree in all cases?
1046  */
1047 int ext4_ext_correct_indexes(handle_t *handle, struct inode *inode,
1048                                 struct ext4_ext_path *path)
1049 {
1050         struct ext4_extent_header *eh;
1051         int depth = ext_depth(inode);
1052         struct ext4_extent *ex;
1053         __le32 border;
1054         int k, err = 0;
1055
1056         eh = path[depth].p_hdr;
1057         ex = path[depth].p_ext;
1058         BUG_ON(ex == NULL);
1059         BUG_ON(eh == NULL);
1060
1061         if (depth == 0) {
1062                 /* there is no tree at all */
1063                 return 0;
1064         }
1065
1066         if (ex != EXT_FIRST_EXTENT(eh)) {
1067                 /* we correct tree if first leaf got modified only */
1068                 return 0;
1069         }
1070
1071         /*
1072          * TODO: we need correction if border is smaller than current one
1073          */
1074         k = depth - 1;
1075         border = path[depth].p_ext->ee_block;
1076         if ((err = ext4_ext_get_access(handle, inode, path + k)))
1077                 return err;
1078         path[k].p_idx->ei_block = border;
1079         if ((err = ext4_ext_dirty(handle, inode, path + k)))
1080                 return err;
1081
1082         while (k--) {
1083                 /* change all left-side indexes */
1084                 if (path[k+1].p_idx != EXT_FIRST_INDEX(path[k+1].p_hdr))
1085                         break;
1086                 if ((err = ext4_ext_get_access(handle, inode, path + k)))
1087                         break;
1088                 path[k].p_idx->ei_block = border;
1089                 if ((err = ext4_ext_dirty(handle, inode, path + k)))
1090                         break;
1091         }
1092
1093         return err;
1094 }
1095
1096 static int inline
1097 ext4_can_extents_be_merged(struct inode *inode, struct ext4_extent *ex1,
1098                                 struct ext4_extent *ex2)
1099 {
1100         if (le32_to_cpu(ex1->ee_block) + le16_to_cpu(ex1->ee_len) !=
1101                         le32_to_cpu(ex2->ee_block))
1102                 return 0;
1103
1104         /*
1105          * To allow future support for preallocated extents to be added
1106          * as an RO_COMPAT feature, refuse to merge to extents if
1107          * this can result in the top bit of ee_len being set.
1108          */
1109         if (le16_to_cpu(ex1->ee_len) + le16_to_cpu(ex2->ee_len) > EXT_MAX_LEN)
1110                 return 0;
1111 #ifdef AGRESSIVE_TEST
1112         if (le16_to_cpu(ex1->ee_len) >= 4)
1113                 return 0;
1114 #endif
1115
1116         if (ext_pblock(ex1) + le16_to_cpu(ex1->ee_len) == ext_pblock(ex2))
1117                 return 1;
1118         return 0;
1119 }
1120
1121 /*
1122  * ext4_ext_insert_extent:
1123  * tries to merge requsted extent into the existing extent or
1124  * inserts requested extent as new one into the tree,
1125  * creating new leaf in the no-space case.
1126  */
1127 int ext4_ext_insert_extent(handle_t *handle, struct inode *inode,
1128                                 struct ext4_ext_path *path,
1129                                 struct ext4_extent *newext)
1130 {
1131         struct ext4_extent_header * eh;
1132         struct ext4_extent *ex, *fex;
1133         struct ext4_extent *nearex; /* nearest extent */
1134         struct ext4_ext_path *npath = NULL;
1135         int depth, len, err, next;
1136
1137         BUG_ON(newext->ee_len == 0);
1138         depth = ext_depth(inode);
1139         ex = path[depth].p_ext;
1140         BUG_ON(path[depth].p_hdr == NULL);
1141
1142         /* try to insert block into found extent and return */
1143         if (ex && ext4_can_extents_be_merged(inode, ex, newext)) {
1144                 ext_debug("append %d block to %d:%d (from %llu)\n",
1145                                 le16_to_cpu(newext->ee_len),
1146                                 le32_to_cpu(ex->ee_block),
1147                                 le16_to_cpu(ex->ee_len), ext_pblock(ex));
1148                 if ((err = ext4_ext_get_access(handle, inode, path + depth)))
1149                         return err;
1150                 ex->ee_len = cpu_to_le16(le16_to_cpu(ex->ee_len)
1151                                          + le16_to_cpu(newext->ee_len));
1152                 eh = path[depth].p_hdr;
1153                 nearex = ex;
1154                 goto merge;
1155         }
1156
1157 repeat:
1158         depth = ext_depth(inode);
1159         eh = path[depth].p_hdr;
1160         if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max))
1161                 goto has_space;
1162
1163         /* probably next leaf has space for us? */
1164         fex = EXT_LAST_EXTENT(eh);
1165         next = ext4_ext_next_leaf_block(inode, path);
1166         if (le32_to_cpu(newext->ee_block) > le32_to_cpu(fex->ee_block)
1167             && next != EXT_MAX_BLOCK) {
1168                 ext_debug("next leaf block - %d\n", next);
1169                 BUG_ON(npath != NULL);
1170                 npath = ext4_ext_find_extent(inode, next, NULL);
1171                 if (IS_ERR(npath))
1172                         return PTR_ERR(npath);
1173                 BUG_ON(npath->p_depth != path->p_depth);
1174                 eh = npath[depth].p_hdr;
1175                 if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max)) {
1176                         ext_debug("next leaf isnt full(%d)\n",
1177                                   le16_to_cpu(eh->eh_entries));
1178                         path = npath;
1179                         goto repeat;
1180                 }
1181                 ext_debug("next leaf has no free space(%d,%d)\n",
1182                           le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
1183         }
1184
1185         /*
1186          * There is no free space in the found leaf.
1187          * We're gonna add a new leaf in the tree.
1188          */
1189         err = ext4_ext_create_new_leaf(handle, inode, path, newext);
1190         if (err)
1191                 goto cleanup;
1192         depth = ext_depth(inode);
1193         eh = path[depth].p_hdr;
1194
1195 has_space:
1196         nearex = path[depth].p_ext;
1197
1198         if ((err = ext4_ext_get_access(handle, inode, path + depth)))
1199                 goto cleanup;
1200
1201         if (!nearex) {
1202                 /* there is no extent in this leaf, create first one */
1203                 ext_debug("first extent in the leaf: %d:%llu:%d\n",
1204                                 le32_to_cpu(newext->ee_block),
1205                                 ext_pblock(newext),
1206                                 le16_to_cpu(newext->ee_len));
1207                 path[depth].p_ext = EXT_FIRST_EXTENT(eh);
1208         } else if (le32_to_cpu(newext->ee_block)
1209                            > le32_to_cpu(nearex->ee_block)) {
1210 /*              BUG_ON(newext->ee_block == nearex->ee_block); */
1211                 if (nearex != EXT_LAST_EXTENT(eh)) {
1212                         len = EXT_MAX_EXTENT(eh) - nearex;
1213                         len = (len - 1) * sizeof(struct ext4_extent);
1214                         len = len < 0 ? 0 : len;
1215                         ext_debug("insert %d:%llu:%d after: nearest 0x%p, "
1216                                         "move %d from 0x%p to 0x%p\n",
1217                                         le32_to_cpu(newext->ee_block),
1218                                         ext_pblock(newext),
1219                                         le16_to_cpu(newext->ee_len),
1220                                         nearex, len, nearex + 1, nearex + 2);
1221                         memmove(nearex + 2, nearex + 1, len);
1222                 }
1223                 path[depth].p_ext = nearex + 1;
1224         } else {
1225                 BUG_ON(newext->ee_block == nearex->ee_block);
1226                 len = (EXT_MAX_EXTENT(eh) - nearex) * sizeof(struct ext4_extent);
1227                 len = len < 0 ? 0 : len;
1228                 ext_debug("insert %d:%llu:%d before: nearest 0x%p, "
1229                                 "move %d from 0x%p to 0x%p\n",
1230                                 le32_to_cpu(newext->ee_block),
1231                                 ext_pblock(newext),
1232                                 le16_to_cpu(newext->ee_len),
1233                                 nearex, len, nearex + 1, nearex + 2);
1234                 memmove(nearex + 1, nearex, len);
1235                 path[depth].p_ext = nearex;
1236         }
1237
1238         eh->eh_entries = cpu_to_le16(le16_to_cpu(eh->eh_entries)+1);
1239         nearex = path[depth].p_ext;
1240         nearex->ee_block = newext->ee_block;
1241         nearex->ee_start = newext->ee_start;
1242         nearex->ee_start_hi = newext->ee_start_hi;
1243         nearex->ee_len = newext->ee_len;
1244
1245 merge:
1246         /* try to merge extents to the right */
1247         while (nearex < EXT_LAST_EXTENT(eh)) {
1248                 if (!ext4_can_extents_be_merged(inode, nearex, nearex + 1))
1249                         break;
1250                 /* merge with next extent! */
1251                 nearex->ee_len = cpu_to_le16(le16_to_cpu(nearex->ee_len)
1252                                              + le16_to_cpu(nearex[1].ee_len));
1253                 if (nearex + 1 < EXT_LAST_EXTENT(eh)) {
1254                         len = (EXT_LAST_EXTENT(eh) - nearex - 1)
1255                                         * sizeof(struct ext4_extent);
1256                         memmove(nearex + 1, nearex + 2, len);
1257                 }
1258                 eh->eh_entries = cpu_to_le16(le16_to_cpu(eh->eh_entries)-1);
1259                 BUG_ON(eh->eh_entries == 0);
1260         }
1261
1262         /* try to merge extents to the left */
1263
1264         /* time to correct all indexes above */
1265         err = ext4_ext_correct_indexes(handle, inode, path);
1266         if (err)
1267                 goto cleanup;
1268
1269         err = ext4_ext_dirty(handle, inode, path + depth);
1270
1271 cleanup:
1272         if (npath) {
1273                 ext4_ext_drop_refs(npath);
1274                 kfree(npath);
1275         }
1276         ext4_ext_tree_changed(inode);
1277         ext4_ext_invalidate_cache(inode);
1278         return err;
1279 }
1280
1281 int ext4_ext_walk_space(struct inode *inode, unsigned long block,
1282                         unsigned long num, ext_prepare_callback func,
1283                         void *cbdata)
1284 {
1285         struct ext4_ext_path *path = NULL;
1286         struct ext4_ext_cache cbex;
1287         struct ext4_extent *ex;
1288         unsigned long next, start = 0, end = 0;
1289         unsigned long last = block + num;
1290         int depth, exists, err = 0;
1291
1292         BUG_ON(func == NULL);
1293         BUG_ON(inode == NULL);
1294
1295         while (block < last && block != EXT_MAX_BLOCK) {
1296                 num = last - block;
1297                 /* find extent for this block */
1298                 path = ext4_ext_find_extent(inode, block, path);
1299                 if (IS_ERR(path)) {
1300                         err = PTR_ERR(path);
1301                         path = NULL;
1302                         break;
1303                 }
1304
1305                 depth = ext_depth(inode);
1306                 BUG_ON(path[depth].p_hdr == NULL);
1307                 ex = path[depth].p_ext;
1308                 next = ext4_ext_next_allocated_block(path);
1309
1310                 exists = 0;
1311                 if (!ex) {
1312                         /* there is no extent yet, so try to allocate
1313                          * all requested space */
1314                         start = block;
1315                         end = block + num;
1316                 } else if (le32_to_cpu(ex->ee_block) > block) {
1317                         /* need to allocate space before found extent */
1318                         start = block;
1319                         end = le32_to_cpu(ex->ee_block);
1320                         if (block + num < end)
1321                                 end = block + num;
1322                 } else if (block >=
1323                              le32_to_cpu(ex->ee_block) + le16_to_cpu(ex->ee_len)) {
1324                         /* need to allocate space after found extent */
1325                         start = block;
1326                         end = block + num;
1327                         if (end >= next)
1328                                 end = next;
1329                 } else if (block >= le32_to_cpu(ex->ee_block)) {
1330                         /*
1331                          * some part of requested space is covered
1332                          * by found extent
1333                          */
1334                         start = block;
1335                         end = le32_to_cpu(ex->ee_block) + le16_to_cpu(ex->ee_len);
1336                         if (block + num < end)
1337                                 end = block + num;
1338                         exists = 1;
1339                 } else {
1340                         BUG();
1341                 }
1342                 BUG_ON(end <= start);
1343
1344                 if (!exists) {
1345                         cbex.ec_block = start;
1346                         cbex.ec_len = end - start;
1347                         cbex.ec_start = 0;
1348                         cbex.ec_type = EXT4_EXT_CACHE_GAP;
1349                 } else {
1350                         cbex.ec_block = le32_to_cpu(ex->ee_block);
1351                         cbex.ec_len = le16_to_cpu(ex->ee_len);
1352                         cbex.ec_start = ext_pblock(ex);
1353                         cbex.ec_type = EXT4_EXT_CACHE_EXTENT;
1354                 }
1355
1356                 BUG_ON(cbex.ec_len == 0);
1357                 err = func(inode, path, &cbex, cbdata);
1358                 ext4_ext_drop_refs(path);
1359
1360                 if (err < 0)
1361                         break;
1362                 if (err == EXT_REPEAT)
1363                         continue;
1364                 else if (err == EXT_BREAK) {
1365                         err = 0;
1366                         break;
1367                 }
1368
1369                 if (ext_depth(inode) != depth) {
1370                         /* depth was changed. we have to realloc path */
1371                         kfree(path);
1372                         path = NULL;
1373                 }
1374
1375                 block = cbex.ec_block + cbex.ec_len;
1376         }
1377
1378         if (path) {
1379                 ext4_ext_drop_refs(path);
1380                 kfree(path);
1381         }
1382
1383         return err;
1384 }
1385
1386 static inline void
1387 ext4_ext_put_in_cache(struct inode *inode, __u32 block,
1388                         __u32 len, __u32 start, int type)
1389 {
1390         struct ext4_ext_cache *cex;
1391         BUG_ON(len == 0);
1392         cex = &EXT4_I(inode)->i_cached_extent;
1393         cex->ec_type = type;
1394         cex->ec_block = block;
1395         cex->ec_len = len;
1396         cex->ec_start = start;
1397 }
1398
1399 /*
1400  * ext4_ext_put_gap_in_cache:
1401  * calculate boundaries of the gap that the requested block fits into
1402  * and cache this gap
1403  */
1404 static inline void
1405 ext4_ext_put_gap_in_cache(struct inode *inode, struct ext4_ext_path *path,
1406                                 unsigned long block)
1407 {
1408         int depth = ext_depth(inode);
1409         unsigned long lblock, len;
1410         struct ext4_extent *ex;
1411
1412         ex = path[depth].p_ext;
1413         if (ex == NULL) {
1414                 /* there is no extent yet, so gap is [0;-] */
1415                 lblock = 0;
1416                 len = EXT_MAX_BLOCK;
1417                 ext_debug("cache gap(whole file):");
1418         } else if (block < le32_to_cpu(ex->ee_block)) {
1419                 lblock = block;
1420                 len = le32_to_cpu(ex->ee_block) - block;
1421                 ext_debug("cache gap(before): %lu [%lu:%lu]",
1422                                 (unsigned long) block,
1423                                 (unsigned long) le32_to_cpu(ex->ee_block),
1424                                 (unsigned long) le16_to_cpu(ex->ee_len));
1425         } else if (block >= le32_to_cpu(ex->ee_block)
1426                             + le16_to_cpu(ex->ee_len)) {
1427                 lblock = le32_to_cpu(ex->ee_block)
1428                          + le16_to_cpu(ex->ee_len);
1429                 len = ext4_ext_next_allocated_block(path);
1430                 ext_debug("cache gap(after): [%lu:%lu] %lu",
1431                                 (unsigned long) le32_to_cpu(ex->ee_block),
1432                                 (unsigned long) le16_to_cpu(ex->ee_len),
1433                                 (unsigned long) block);
1434                 BUG_ON(len == lblock);
1435                 len = len - lblock;
1436         } else {
1437                 lblock = len = 0;
1438                 BUG();
1439         }
1440
1441         ext_debug(" -> %lu:%lu\n", (unsigned long) lblock, len);
1442         ext4_ext_put_in_cache(inode, lblock, len, 0, EXT4_EXT_CACHE_GAP);
1443 }
1444
1445 static inline int
1446 ext4_ext_in_cache(struct inode *inode, unsigned long block,
1447                         struct ext4_extent *ex)
1448 {
1449         struct ext4_ext_cache *cex;
1450
1451         cex = &EXT4_I(inode)->i_cached_extent;
1452
1453         /* has cache valid data? */
1454         if (cex->ec_type == EXT4_EXT_CACHE_NO)
1455                 return EXT4_EXT_CACHE_NO;
1456
1457         BUG_ON(cex->ec_type != EXT4_EXT_CACHE_GAP &&
1458                         cex->ec_type != EXT4_EXT_CACHE_EXTENT);
1459         if (block >= cex->ec_block && block < cex->ec_block + cex->ec_len) {
1460                 ex->ee_block = cpu_to_le32(cex->ec_block);
1461                 ext4_ext_store_pblock(ex, cex->ec_start);
1462                 ex->ee_len = cpu_to_le16(cex->ec_len);
1463                 ext_debug("%lu cached by %lu:%lu:%llu\n",
1464                                 (unsigned long) block,
1465                                 (unsigned long) cex->ec_block,
1466                                 (unsigned long) cex->ec_len,
1467                                 cex->ec_start);
1468                 return cex->ec_type;
1469         }
1470
1471         /* not in cache */
1472         return EXT4_EXT_CACHE_NO;
1473 }
1474
1475 /*
1476  * ext4_ext_rm_idx:
1477  * removes index from the index block.
1478  * It's used in truncate case only, thus all requests are for
1479  * last index in the block only.
1480  */
1481 int ext4_ext_rm_idx(handle_t *handle, struct inode *inode,
1482                         struct ext4_ext_path *path)
1483 {
1484         struct buffer_head *bh;
1485         int err;
1486         ext4_fsblk_t leaf;
1487
1488         /* free index block */
1489         path--;
1490         leaf = idx_pblock(path->p_idx);
1491         BUG_ON(path->p_hdr->eh_entries == 0);
1492         if ((err = ext4_ext_get_access(handle, inode, path)))
1493                 return err;
1494         path->p_hdr->eh_entries = cpu_to_le16(le16_to_cpu(path->p_hdr->eh_entries)-1);
1495         if ((err = ext4_ext_dirty(handle, inode, path)))
1496                 return err;
1497         ext_debug("index is empty, remove it, free block %llu\n", leaf);
1498         bh = sb_find_get_block(inode->i_sb, leaf);
1499         ext4_forget(handle, 1, inode, bh, leaf);
1500         ext4_free_blocks(handle, inode, leaf, 1);
1501         return err;
1502 }
1503
1504 /*
1505  * ext4_ext_calc_credits_for_insert:
1506  * This routine returns max. credits that the extent tree can consume.
1507  * It should be OK for low-performance paths like ->writepage()
1508  * To allow many writing processes to fit into a single transaction,
1509  * the caller should calculate credits under truncate_mutex and
1510  * pass the actual path.
1511  */
1512 int inline ext4_ext_calc_credits_for_insert(struct inode *inode,
1513                                                 struct ext4_ext_path *path)
1514 {
1515         int depth, needed;
1516
1517         if (path) {
1518                 /* probably there is space in leaf? */
1519                 depth = ext_depth(inode);
1520                 if (le16_to_cpu(path[depth].p_hdr->eh_entries)
1521                                 < le16_to_cpu(path[depth].p_hdr->eh_max))
1522                         return 1;
1523         }
1524
1525         /*
1526          * given 32-bit logical block (4294967296 blocks), max. tree
1527          * can be 4 levels in depth -- 4 * 340^4 == 53453440000.
1528          * Let's also add one more level for imbalance.
1529          */
1530         depth = 5;
1531
1532         /* allocation of new data block(s) */
1533         needed = 2;
1534
1535         /*
1536          * tree can be full, so it would need to grow in depth:
1537          * allocation + old root + new root
1538          */
1539         needed += 2 + 1 + 1;
1540
1541         /*
1542          * Index split can happen, we would need:
1543          *    allocate intermediate indexes (bitmap + group)
1544          *  + change two blocks at each level, but root (already included)
1545          */
1546         needed = (depth * 2) + (depth * 2);
1547
1548         /* any allocation modifies superblock */
1549         needed += 1;
1550
1551         return needed;
1552 }
1553
1554 static int ext4_remove_blocks(handle_t *handle, struct inode *inode,
1555                                 struct ext4_extent *ex,
1556                                 unsigned long from, unsigned long to)
1557 {
1558         struct buffer_head *bh;
1559         int i;
1560
1561 #ifdef EXTENTS_STATS
1562         {
1563                 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1564                 unsigned short ee_len =  le16_to_cpu(ex->ee_len);
1565                 spin_lock(&sbi->s_ext_stats_lock);
1566                 sbi->s_ext_blocks += ee_len;
1567                 sbi->s_ext_extents++;
1568                 if (ee_len < sbi->s_ext_min)
1569                         sbi->s_ext_min = ee_len;
1570                 if (ee_len > sbi->s_ext_max)
1571                         sbi->s_ext_max = ee_len;
1572                 if (ext_depth(inode) > sbi->s_depth_max)
1573                         sbi->s_depth_max = ext_depth(inode);
1574                 spin_unlock(&sbi->s_ext_stats_lock);
1575         }
1576 #endif
1577         if (from >= le32_to_cpu(ex->ee_block)
1578             && to == le32_to_cpu(ex->ee_block) + le16_to_cpu(ex->ee_len) - 1) {
1579                 /* tail removal */
1580                 unsigned long num;
1581                 ext4_fsblk_t start;
1582                 num = le32_to_cpu(ex->ee_block) + le16_to_cpu(ex->ee_len) - from;
1583                 start = ext_pblock(ex) + le16_to_cpu(ex->ee_len) - num;
1584                 ext_debug("free last %lu blocks starting %llu\n", num, start);
1585                 for (i = 0; i < num; i++) {
1586                         bh = sb_find_get_block(inode->i_sb, start + i);
1587                         ext4_forget(handle, 0, inode, bh, start + i);
1588                 }
1589                 ext4_free_blocks(handle, inode, start, num);
1590         } else if (from == le32_to_cpu(ex->ee_block)
1591                    && to <= le32_to_cpu(ex->ee_block) + le16_to_cpu(ex->ee_len) - 1) {
1592                 printk("strange request: removal %lu-%lu from %u:%u\n",
1593                        from, to, le32_to_cpu(ex->ee_block), le16_to_cpu(ex->ee_len));
1594         } else {
1595                 printk("strange request: removal(2) %lu-%lu from %u:%u\n",
1596                        from, to, le32_to_cpu(ex->ee_block), le16_to_cpu(ex->ee_len));
1597         }
1598         return 0;
1599 }
1600
1601 static int
1602 ext4_ext_rm_leaf(handle_t *handle, struct inode *inode,
1603                 struct ext4_ext_path *path, unsigned long start)
1604 {
1605         int err = 0, correct_index = 0;
1606         int depth = ext_depth(inode), credits;
1607         struct ext4_extent_header *eh;
1608         unsigned a, b, block, num;
1609         unsigned long ex_ee_block;
1610         unsigned short ex_ee_len;
1611         struct ext4_extent *ex;
1612
1613         ext_debug("truncate since %lu in leaf\n", start);
1614         if (!path[depth].p_hdr)
1615                 path[depth].p_hdr = ext_block_hdr(path[depth].p_bh);
1616         eh = path[depth].p_hdr;
1617         BUG_ON(eh == NULL);
1618         BUG_ON(le16_to_cpu(eh->eh_entries) > le16_to_cpu(eh->eh_max));
1619         BUG_ON(eh->eh_magic != EXT4_EXT_MAGIC);
1620
1621         /* find where to start removing */
1622         ex = EXT_LAST_EXTENT(eh);
1623
1624         ex_ee_block = le32_to_cpu(ex->ee_block);
1625         ex_ee_len = le16_to_cpu(ex->ee_len);
1626
1627         while (ex >= EXT_FIRST_EXTENT(eh) &&
1628                         ex_ee_block + ex_ee_len > start) {
1629                 ext_debug("remove ext %lu:%u\n", ex_ee_block, ex_ee_len);
1630                 path[depth].p_ext = ex;
1631
1632                 a = ex_ee_block > start ? ex_ee_block : start;
1633                 b = ex_ee_block + ex_ee_len - 1 < EXT_MAX_BLOCK ?
1634                         ex_ee_block + ex_ee_len - 1 : EXT_MAX_BLOCK;
1635
1636                 ext_debug("  border %u:%u\n", a, b);
1637
1638                 if (a != ex_ee_block && b != ex_ee_block + ex_ee_len - 1) {
1639                         block = 0;
1640                         num = 0;
1641                         BUG();
1642                 } else if (a != ex_ee_block) {
1643                         /* remove tail of the extent */
1644                         block = ex_ee_block;
1645                         num = a - block;
1646                 } else if (b != ex_ee_block + ex_ee_len - 1) {
1647                         /* remove head of the extent */
1648                         block = a;
1649                         num = b - a;
1650                         /* there is no "make a hole" API yet */
1651                         BUG();
1652                 } else {
1653                         /* remove whole extent: excellent! */
1654                         block = ex_ee_block;
1655                         num = 0;
1656                         BUG_ON(a != ex_ee_block);
1657                         BUG_ON(b != ex_ee_block + ex_ee_len - 1);
1658                 }
1659
1660                 /* at present, extent can't cross block group: */
1661                 /* leaf + bitmap + group desc + sb + inode */
1662                 credits = 5;
1663                 if (ex == EXT_FIRST_EXTENT(eh)) {
1664                         correct_index = 1;
1665                         credits += (ext_depth(inode)) + 1;
1666                 }
1667 #ifdef CONFIG_QUOTA
1668                 credits += 2 * EXT4_QUOTA_TRANS_BLOCKS(inode->i_sb);
1669 #endif
1670
1671                 handle = ext4_ext_journal_restart(handle, credits);
1672                 if (IS_ERR(handle)) {
1673                         err = PTR_ERR(handle);
1674                         goto out;
1675                 }
1676
1677                 err = ext4_ext_get_access(handle, inode, path + depth);
1678                 if (err)
1679                         goto out;
1680
1681                 err = ext4_remove_blocks(handle, inode, ex, a, b);
1682                 if (err)
1683                         goto out;
1684
1685                 if (num == 0) {
1686                         /* this extent is removed; mark slot entirely unused */
1687                         ext4_ext_store_pblock(ex, 0);
1688                         eh->eh_entries = cpu_to_le16(le16_to_cpu(eh->eh_entries)-1);
1689                 }
1690
1691                 ex->ee_block = cpu_to_le32(block);
1692                 ex->ee_len = cpu_to_le16(num);
1693
1694                 err = ext4_ext_dirty(handle, inode, path + depth);
1695                 if (err)
1696                         goto out;
1697
1698                 ext_debug("new extent: %u:%u:%llu\n", block, num,
1699                                 ext_pblock(ex));
1700                 ex--;
1701                 ex_ee_block = le32_to_cpu(ex->ee_block);
1702                 ex_ee_len = le16_to_cpu(ex->ee_len);
1703         }
1704
1705         if (correct_index && eh->eh_entries)
1706                 err = ext4_ext_correct_indexes(handle, inode, path);
1707
1708         /* if this leaf is free, then we should
1709          * remove it from index block above */
1710         if (err == 0 && eh->eh_entries == 0 && path[depth].p_bh != NULL)
1711                 err = ext4_ext_rm_idx(handle, inode, path + depth);
1712
1713 out:
1714         return err;
1715 }
1716
1717 /*
1718  * ext4_ext_more_to_rm:
1719  * returns 1 if current index has to be freed (even partial)
1720  */
1721 static int inline
1722 ext4_ext_more_to_rm(struct ext4_ext_path *path)
1723 {
1724         BUG_ON(path->p_idx == NULL);
1725
1726         if (path->p_idx < EXT_FIRST_INDEX(path->p_hdr))
1727                 return 0;
1728
1729         /*
1730          * if truncate on deeper level happened, it wasn't partial,
1731          * so we have to consider current index for truncation
1732          */
1733         if (le16_to_cpu(path->p_hdr->eh_entries) == path->p_block)
1734                 return 0;
1735         return 1;
1736 }
1737
1738 int ext4_ext_remove_space(struct inode *inode, unsigned long start)
1739 {
1740         struct super_block *sb = inode->i_sb;
1741         int depth = ext_depth(inode);
1742         struct ext4_ext_path *path;
1743         handle_t *handle;
1744         int i = 0, err = 0;
1745
1746         ext_debug("truncate since %lu\n", start);
1747
1748         /* probably first extent we're gonna free will be last in block */
1749         handle = ext4_journal_start(inode, depth + 1);
1750         if (IS_ERR(handle))
1751                 return PTR_ERR(handle);
1752
1753         ext4_ext_invalidate_cache(inode);
1754
1755         /*
1756          * We start scanning from right side, freeing all the blocks
1757          * after i_size and walking into the tree depth-wise.
1758          */
1759         path = kmalloc(sizeof(struct ext4_ext_path) * (depth + 1), GFP_KERNEL);
1760         if (path == NULL) {
1761                 ext4_journal_stop(handle);
1762                 return -ENOMEM;
1763         }
1764         memset(path, 0, sizeof(struct ext4_ext_path) * (depth + 1));
1765         path[0].p_hdr = ext_inode_hdr(inode);
1766         if (ext4_ext_check_header(__FUNCTION__, inode, path[0].p_hdr)) {
1767                 err = -EIO;
1768                 goto out;
1769         }
1770         path[0].p_depth = depth;
1771
1772         while (i >= 0 && err == 0) {
1773                 if (i == depth) {
1774                         /* this is leaf block */
1775                         err = ext4_ext_rm_leaf(handle, inode, path, start);
1776                         /* root level has p_bh == NULL, brelse() eats this */
1777                         brelse(path[i].p_bh);
1778                         path[i].p_bh = NULL;
1779                         i--;
1780                         continue;
1781                 }
1782
1783                 /* this is index block */
1784                 if (!path[i].p_hdr) {
1785                         ext_debug("initialize header\n");
1786                         path[i].p_hdr = ext_block_hdr(path[i].p_bh);
1787                         if (ext4_ext_check_header(__FUNCTION__, inode,
1788                                                         path[i].p_hdr)) {
1789                                 err = -EIO;
1790                                 goto out;
1791                         }
1792                 }
1793
1794                 BUG_ON(le16_to_cpu(path[i].p_hdr->eh_entries)
1795                            > le16_to_cpu(path[i].p_hdr->eh_max));
1796                 BUG_ON(path[i].p_hdr->eh_magic != EXT4_EXT_MAGIC);
1797
1798                 if (!path[i].p_idx) {
1799                         /* this level hasn't been touched yet */
1800                         path[i].p_idx = EXT_LAST_INDEX(path[i].p_hdr);
1801                         path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries)+1;
1802                         ext_debug("init index ptr: hdr 0x%p, num %d\n",
1803                                   path[i].p_hdr,
1804                                   le16_to_cpu(path[i].p_hdr->eh_entries));
1805                 } else {
1806                         /* we were already here, see at next index */
1807                         path[i].p_idx--;
1808                 }
1809
1810                 ext_debug("level %d - index, first 0x%p, cur 0x%p\n",
1811                                 i, EXT_FIRST_INDEX(path[i].p_hdr),
1812                                 path[i].p_idx);
1813                 if (ext4_ext_more_to_rm(path + i)) {
1814                         /* go to the next level */
1815                         ext_debug("move to level %d (block %llu)\n",
1816                                   i + 1, idx_pblock(path[i].p_idx));
1817                         memset(path + i + 1, 0, sizeof(*path));
1818                         path[i+1].p_bh =
1819                                 sb_bread(sb, idx_pblock(path[i].p_idx));
1820                         if (!path[i+1].p_bh) {
1821                                 /* should we reset i_size? */
1822                                 err = -EIO;
1823                                 break;
1824                         }
1825
1826                         /* save actual number of indexes since this
1827                          * number is changed at the next iteration */
1828                         path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries);
1829                         i++;
1830                 } else {
1831                         /* we finished processing this index, go up */
1832                         if (path[i].p_hdr->eh_entries == 0 && i > 0) {
1833                                 /* index is empty, remove it;
1834                                  * handle must be already prepared by the
1835                                  * truncatei_leaf() */
1836                                 err = ext4_ext_rm_idx(handle, inode, path + i);
1837                         }
1838                         /* root level has p_bh == NULL, brelse() eats this */
1839                         brelse(path[i].p_bh);
1840                         path[i].p_bh = NULL;
1841                         i--;
1842                         ext_debug("return to level %d\n", i);
1843                 }
1844         }
1845
1846         /* TODO: flexible tree reduction should be here */
1847         if (path->p_hdr->eh_entries == 0) {
1848                 /*
1849                  * truncate to zero freed all the tree,
1850                  * so we need to correct eh_depth
1851                  */
1852                 err = ext4_ext_get_access(handle, inode, path);
1853                 if (err == 0) {
1854                         ext_inode_hdr(inode)->eh_depth = 0;
1855                         ext_inode_hdr(inode)->eh_max =
1856                                 cpu_to_le16(ext4_ext_space_root(inode));
1857                         err = ext4_ext_dirty(handle, inode, path);
1858                 }
1859         }
1860 out:
1861         ext4_ext_tree_changed(inode);
1862         ext4_ext_drop_refs(path);
1863         kfree(path);
1864         ext4_journal_stop(handle);
1865
1866         return err;
1867 }
1868
1869 /*
1870  * called at mount time
1871  */
1872 void ext4_ext_init(struct super_block *sb)
1873 {
1874         /*
1875          * possible initialization would be here
1876          */
1877
1878         if (test_opt(sb, EXTENTS)) {
1879                 printk("EXT4-fs: file extents enabled");
1880 #ifdef AGRESSIVE_TEST
1881                 printk(", agressive tests");
1882 #endif
1883 #ifdef CHECK_BINSEARCH
1884                 printk(", check binsearch");
1885 #endif
1886 #ifdef EXTENTS_STATS
1887                 printk(", stats");
1888 #endif
1889                 printk("\n");
1890 #ifdef EXTENTS_STATS
1891                 spin_lock_init(&EXT4_SB(sb)->s_ext_stats_lock);
1892                 EXT4_SB(sb)->s_ext_min = 1 << 30;
1893                 EXT4_SB(sb)->s_ext_max = 0;
1894 #endif
1895         }
1896 }
1897
1898 /*
1899  * called at umount time
1900  */
1901 void ext4_ext_release(struct super_block *sb)
1902 {
1903         if (!test_opt(sb, EXTENTS))
1904                 return;
1905
1906 #ifdef EXTENTS_STATS
1907         if (EXT4_SB(sb)->s_ext_blocks && EXT4_SB(sb)->s_ext_extents) {
1908                 struct ext4_sb_info *sbi = EXT4_SB(sb);
1909                 printk(KERN_ERR "EXT4-fs: %lu blocks in %lu extents (%lu ave)\n",
1910                         sbi->s_ext_blocks, sbi->s_ext_extents,
1911                         sbi->s_ext_blocks / sbi->s_ext_extents);
1912                 printk(KERN_ERR "EXT4-fs: extents: %lu min, %lu max, max depth %lu\n",
1913                         sbi->s_ext_min, sbi->s_ext_max, sbi->s_depth_max);
1914         }
1915 #endif
1916 }
1917
1918 int ext4_ext_get_blocks(handle_t *handle, struct inode *inode,
1919                         ext4_fsblk_t iblock,
1920                         unsigned long max_blocks, struct buffer_head *bh_result,
1921                         int create, int extend_disksize)
1922 {
1923         struct ext4_ext_path *path = NULL;
1924         struct ext4_extent newex, *ex;
1925         ext4_fsblk_t goal, newblock;
1926         int err = 0, depth;
1927         unsigned long allocated = 0;
1928
1929         __clear_bit(BH_New, &bh_result->b_state);
1930         ext_debug("blocks %d/%lu requested for inode %u\n", (int) iblock,
1931                         max_blocks, (unsigned) inode->i_ino);
1932         mutex_lock(&EXT4_I(inode)->truncate_mutex);
1933
1934         /* check in cache */
1935         if ((goal = ext4_ext_in_cache(inode, iblock, &newex))) {
1936                 if (goal == EXT4_EXT_CACHE_GAP) {
1937                         if (!create) {
1938                                 /* block isn't allocated yet and
1939                                  * user doesn't want to allocate it */
1940                                 goto out2;
1941                         }
1942                         /* we should allocate requested block */
1943                 } else if (goal == EXT4_EXT_CACHE_EXTENT) {
1944                         /* block is already allocated */
1945                         newblock = iblock
1946                                    - le32_to_cpu(newex.ee_block)
1947                                    + ext_pblock(&newex);
1948                         /* number of remaining blocks in the extent */
1949                         allocated = le16_to_cpu(newex.ee_len) -
1950                                         (iblock - le32_to_cpu(newex.ee_block));
1951                         goto out;
1952                 } else {
1953                         BUG();
1954                 }
1955         }
1956
1957         /* find extent for this block */
1958         path = ext4_ext_find_extent(inode, iblock, NULL);
1959         if (IS_ERR(path)) {
1960                 err = PTR_ERR(path);
1961                 path = NULL;
1962                 goto out2;
1963         }
1964
1965         depth = ext_depth(inode);
1966
1967         /*
1968          * consistent leaf must not be empty;
1969          * this situation is possible, though, _during_ tree modification;
1970          * this is why assert can't be put in ext4_ext_find_extent()
1971          */
1972         BUG_ON(path[depth].p_ext == NULL && depth != 0);
1973
1974         if ((ex = path[depth].p_ext)) {
1975                 unsigned long ee_block = le32_to_cpu(ex->ee_block);
1976                 ext4_fsblk_t ee_start = ext_pblock(ex);
1977                 unsigned short ee_len  = le16_to_cpu(ex->ee_len);
1978
1979                 /*
1980                  * Allow future support for preallocated extents to be added
1981                  * as an RO_COMPAT feature:
1982                  * Uninitialized extents are treated as holes, except that
1983                  * we avoid (fail) allocating new blocks during a write.
1984                  */
1985                 if (ee_len > EXT_MAX_LEN)
1986                         goto out2;
1987                 /* if found extent covers block, simply return it */
1988                 if (iblock >= ee_block && iblock < ee_block + ee_len) {
1989                         newblock = iblock - ee_block + ee_start;
1990                         /* number of remaining blocks in the extent */
1991                         allocated = ee_len - (iblock - ee_block);
1992                         ext_debug("%d fit into %lu:%d -> %llu\n", (int) iblock,
1993                                         ee_block, ee_len, newblock);
1994                         ext4_ext_put_in_cache(inode, ee_block, ee_len,
1995                                                 ee_start, EXT4_EXT_CACHE_EXTENT);
1996                         goto out;
1997                 }
1998         }
1999
2000         /*
2001          * requested block isn't allocated yet;
2002          * we couldn't try to create block if create flag is zero
2003          */
2004         if (!create) {
2005                 /* put just found gap into cache to speed up
2006                  * subsequent requests */
2007                 ext4_ext_put_gap_in_cache(inode, path, iblock);
2008                 goto out2;
2009         }
2010         /*
2011          * Okay, we need to do block allocation.  Lazily initialize the block
2012          * allocation info here if necessary.
2013          */
2014         if (S_ISREG(inode->i_mode) && (!EXT4_I(inode)->i_block_alloc_info))
2015                 ext4_init_block_alloc_info(inode);
2016
2017         /* allocate new block */
2018         goal = ext4_ext_find_goal(inode, path, iblock);
2019         allocated = max_blocks;
2020         newblock = ext4_new_blocks(handle, inode, goal, &allocated, &err);
2021         if (!newblock)
2022                 goto out2;
2023         ext_debug("allocate new block: goal %llu, found %llu/%lu\n",
2024                         goal, newblock, allocated);
2025
2026         /* try to insert new extent into found leaf and return */
2027         newex.ee_block = cpu_to_le32(iblock);
2028         ext4_ext_store_pblock(&newex, newblock);
2029         newex.ee_len = cpu_to_le16(allocated);
2030         err = ext4_ext_insert_extent(handle, inode, path, &newex);
2031         if (err)
2032                 goto out2;
2033
2034         if (extend_disksize && inode->i_size > EXT4_I(inode)->i_disksize)
2035                 EXT4_I(inode)->i_disksize = inode->i_size;
2036
2037         /* previous routine could use block we allocated */
2038         newblock = ext_pblock(&newex);
2039         __set_bit(BH_New, &bh_result->b_state);
2040
2041         ext4_ext_put_in_cache(inode, iblock, allocated, newblock,
2042                                 EXT4_EXT_CACHE_EXTENT);
2043 out:
2044         if (allocated > max_blocks)
2045                 allocated = max_blocks;
2046         ext4_ext_show_leaf(inode, path);
2047         __set_bit(BH_Mapped, &bh_result->b_state);
2048         bh_result->b_bdev = inode->i_sb->s_bdev;
2049         bh_result->b_blocknr = newblock;
2050 out2:
2051         if (path) {
2052                 ext4_ext_drop_refs(path);
2053                 kfree(path);
2054         }
2055         mutex_unlock(&EXT4_I(inode)->truncate_mutex);
2056
2057         return err ? err : allocated;
2058 }
2059
2060 void ext4_ext_truncate(struct inode * inode, struct page *page)
2061 {
2062         struct address_space *mapping = inode->i_mapping;
2063         struct super_block *sb = inode->i_sb;
2064         unsigned long last_block;
2065         handle_t *handle;
2066         int err = 0;
2067
2068         /*
2069          * probably first extent we're gonna free will be last in block
2070          */
2071         err = ext4_writepage_trans_blocks(inode) + 3;
2072         handle = ext4_journal_start(inode, err);
2073         if (IS_ERR(handle)) {
2074                 if (page) {
2075                         clear_highpage(page);
2076                         flush_dcache_page(page);
2077                         unlock_page(page);
2078                         page_cache_release(page);
2079                 }
2080                 return;
2081         }
2082
2083         if (page)
2084                 ext4_block_truncate_page(handle, page, mapping, inode->i_size);
2085
2086         mutex_lock(&EXT4_I(inode)->truncate_mutex);
2087         ext4_ext_invalidate_cache(inode);
2088
2089         /*
2090          * TODO: optimization is possible here.
2091          * Probably we need not scan at all,
2092          * because page truncation is enough.
2093          */
2094         if (ext4_orphan_add(handle, inode))
2095                 goto out_stop;
2096
2097         /* we have to know where to truncate from in crash case */
2098         EXT4_I(inode)->i_disksize = inode->i_size;
2099         ext4_mark_inode_dirty(handle, inode);
2100
2101         last_block = (inode->i_size + sb->s_blocksize - 1)
2102                         >> EXT4_BLOCK_SIZE_BITS(sb);
2103         err = ext4_ext_remove_space(inode, last_block);
2104
2105         /* In a multi-transaction truncate, we only make the final
2106          * transaction synchronous. */
2107         if (IS_SYNC(inode))
2108                 handle->h_sync = 1;
2109
2110 out_stop:
2111         /*
2112          * If this was a simple ftruncate() and the file will remain alive,
2113          * then we need to clear up the orphan record which we created above.
2114          * However, if this was a real unlink then we were called by
2115          * ext4_delete_inode(), and we allow that function to clean up the
2116          * orphan info for us.
2117          */
2118         if (inode->i_nlink)
2119                 ext4_orphan_del(handle, inode);
2120
2121         mutex_unlock(&EXT4_I(inode)->truncate_mutex);
2122         ext4_journal_stop(handle);
2123 }
2124
2125 /*
2126  * ext4_ext_writepage_trans_blocks:
2127  * calculate max number of blocks we could modify
2128  * in order to allocate new block for an inode
2129  */
2130 int ext4_ext_writepage_trans_blocks(struct inode *inode, int num)
2131 {
2132         int needed;
2133
2134         needed = ext4_ext_calc_credits_for_insert(inode, NULL);
2135
2136         /* caller wants to allocate num blocks, but note it includes sb */
2137         needed = needed * num - (num - 1);
2138
2139 #ifdef CONFIG_QUOTA
2140         needed += 2 * EXT4_QUOTA_TRANS_BLOCKS(inode->i_sb);
2141 #endif
2142
2143         return needed;
2144 }
2145
2146 EXPORT_SYMBOL(ext4_mark_inode_dirty);
2147 EXPORT_SYMBOL(ext4_ext_invalidate_cache);
2148 EXPORT_SYMBOL(ext4_ext_insert_extent);
2149 EXPORT_SYMBOL(ext4_ext_walk_space);
2150 EXPORT_SYMBOL(ext4_ext_find_goal);
2151 EXPORT_SYMBOL(ext4_ext_calc_credits_for_insert);
2152