Fix compilation with EXT_DEBUG, also fix leXX_to_cpu conversions.
[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/highuid.h>
38 #include <linux/pagemap.h>
39 #include <linux/quotaops.h>
40 #include <linux/string.h>
41 #include <linux/slab.h>
42 #include <linux/falloc.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 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 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 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 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 handle_t *ext4_ext_journal_restart(handle_t *handle, int needed)
96 {
97         int err;
98
99         if (handle->h_buffer_credits > needed)
100                 return handle;
101         if (!ext4_journal_extend(handle, needed))
102                 return handle;
103         err = ext4_journal_restart(handle, needed);
104
105         return handle;
106 }
107
108 /*
109  * could return:
110  *  - EROFS
111  *  - ENOMEM
112  */
113 static int ext4_ext_get_access(handle_t *handle, struct inode *inode,
114                                 struct ext4_ext_path *path)
115 {
116         if (path->p_bh) {
117                 /* path points to block */
118                 return ext4_journal_get_write_access(handle, path->p_bh);
119         }
120         /* path points to leaf/index in inode body */
121         /* we use in-core data, no need to protect them */
122         return 0;
123 }
124
125 /*
126  * could return:
127  *  - EROFS
128  *  - ENOMEM
129  *  - EIO
130  */
131 static int ext4_ext_dirty(handle_t *handle, struct inode *inode,
132                                 struct ext4_ext_path *path)
133 {
134         int err;
135         if (path->p_bh) {
136                 /* path points to block */
137                 err = ext4_journal_dirty_metadata(handle, path->p_bh);
138         } else {
139                 /* path points to leaf/index in inode body */
140                 err = ext4_mark_inode_dirty(handle, inode);
141         }
142         return err;
143 }
144
145 static ext4_fsblk_t ext4_ext_find_goal(struct inode *inode,
146                               struct ext4_ext_path *path,
147                               ext4_fsblk_t block)
148 {
149         struct ext4_inode_info *ei = EXT4_I(inode);
150         ext4_fsblk_t bg_start;
151         ext4_grpblk_t colour;
152         int depth;
153
154         if (path) {
155                 struct ext4_extent *ex;
156                 depth = path->p_depth;
157
158                 /* try to predict block placement */
159                 ex = path[depth].p_ext;
160                 if (ex)
161                         return ext_pblock(ex)+(block-le32_to_cpu(ex->ee_block));
162
163                 /* it looks like index is empty;
164                  * try to find starting block from index itself */
165                 if (path[depth].p_bh)
166                         return path[depth].p_bh->b_blocknr;
167         }
168
169         /* OK. use inode's group */
170         bg_start = (ei->i_block_group * EXT4_BLOCKS_PER_GROUP(inode->i_sb)) +
171                 le32_to_cpu(EXT4_SB(inode->i_sb)->s_es->s_first_data_block);
172         colour = (current->pid % 16) *
173                         (EXT4_BLOCKS_PER_GROUP(inode->i_sb) / 16);
174         return bg_start + colour + block;
175 }
176
177 static ext4_fsblk_t
178 ext4_ext_new_block(handle_t *handle, struct inode *inode,
179                         struct ext4_ext_path *path,
180                         struct ext4_extent *ex, int *err)
181 {
182         ext4_fsblk_t goal, newblock;
183
184         goal = ext4_ext_find_goal(inode, path, le32_to_cpu(ex->ee_block));
185         newblock = ext4_new_block(handle, inode, goal, err);
186         return newblock;
187 }
188
189 static int ext4_ext_space_block(struct inode *inode)
190 {
191         int size;
192
193         size = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
194                         / sizeof(struct ext4_extent);
195 #ifdef AGGRESSIVE_TEST
196         if (size > 6)
197                 size = 6;
198 #endif
199         return size;
200 }
201
202 static int ext4_ext_space_block_idx(struct inode *inode)
203 {
204         int size;
205
206         size = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
207                         / sizeof(struct ext4_extent_idx);
208 #ifdef AGGRESSIVE_TEST
209         if (size > 5)
210                 size = 5;
211 #endif
212         return size;
213 }
214
215 static int ext4_ext_space_root(struct inode *inode)
216 {
217         int size;
218
219         size = sizeof(EXT4_I(inode)->i_data);
220         size -= sizeof(struct ext4_extent_header);
221         size /= sizeof(struct ext4_extent);
222 #ifdef AGGRESSIVE_TEST
223         if (size > 3)
224                 size = 3;
225 #endif
226         return size;
227 }
228
229 static int ext4_ext_space_root_idx(struct inode *inode)
230 {
231         int size;
232
233         size = sizeof(EXT4_I(inode)->i_data);
234         size -= sizeof(struct ext4_extent_header);
235         size /= sizeof(struct ext4_extent_idx);
236 #ifdef AGGRESSIVE_TEST
237         if (size > 4)
238                 size = 4;
239 #endif
240         return size;
241 }
242
243 static int
244 ext4_ext_max_entries(struct inode *inode, int depth)
245 {
246         int max;
247
248         if (depth == ext_depth(inode)) {
249                 if (depth == 0)
250                         max = ext4_ext_space_root(inode);
251                 else
252                         max = ext4_ext_space_root_idx(inode);
253         } else {
254                 if (depth == 0)
255                         max = ext4_ext_space_block(inode);
256                 else
257                         max = ext4_ext_space_block_idx(inode);
258         }
259
260         return max;
261 }
262
263 static int __ext4_ext_check_header(const char *function, struct inode *inode,
264                                         struct ext4_extent_header *eh,
265                                         int depth)
266 {
267         const char *error_msg;
268         int max = 0;
269
270         if (unlikely(eh->eh_magic != EXT4_EXT_MAGIC)) {
271                 error_msg = "invalid magic";
272                 goto corrupted;
273         }
274         if (unlikely(le16_to_cpu(eh->eh_depth) != depth)) {
275                 error_msg = "unexpected eh_depth";
276                 goto corrupted;
277         }
278         if (unlikely(eh->eh_max == 0)) {
279                 error_msg = "invalid eh_max";
280                 goto corrupted;
281         }
282         max = ext4_ext_max_entries(inode, depth);
283         if (unlikely(le16_to_cpu(eh->eh_max) > max)) {
284                 error_msg = "too large eh_max";
285                 goto corrupted;
286         }
287         if (unlikely(le16_to_cpu(eh->eh_entries) > le16_to_cpu(eh->eh_max))) {
288                 error_msg = "invalid eh_entries";
289                 goto corrupted;
290         }
291         return 0;
292
293 corrupted:
294         ext4_error(inode->i_sb, function,
295                         "bad header in inode #%lu: %s - magic %x, "
296                         "entries %u, max %u(%u), depth %u(%u)",
297                         inode->i_ino, error_msg, le16_to_cpu(eh->eh_magic),
298                         le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max),
299                         max, le16_to_cpu(eh->eh_depth), depth);
300
301         return -EIO;
302 }
303
304 #define ext4_ext_check_header(inode, eh, depth) \
305         __ext4_ext_check_header(__FUNCTION__, inode, eh, depth)
306
307 #ifdef EXT_DEBUG
308 static void ext4_ext_show_path(struct inode *inode, struct ext4_ext_path *path)
309 {
310         int k, l = path->p_depth;
311
312         ext_debug("path:");
313         for (k = 0; k <= l; k++, path++) {
314                 if (path->p_idx) {
315                   ext_debug("  %d->%llu", le32_to_cpu(path->p_idx->ei_block),
316                             idx_pblock(path->p_idx));
317                 } else if (path->p_ext) {
318                         ext_debug("  %d:%d:%llu ",
319                                   le32_to_cpu(path->p_ext->ee_block),
320                                   ext4_ext_get_actual_len(path->p_ext),
321                                   ext_pblock(path->p_ext));
322                 } else
323                         ext_debug("  []");
324         }
325         ext_debug("\n");
326 }
327
328 static void ext4_ext_show_leaf(struct inode *inode, struct ext4_ext_path *path)
329 {
330         int depth = ext_depth(inode);
331         struct ext4_extent_header *eh;
332         struct ext4_extent *ex;
333         int i;
334
335         if (!path)
336                 return;
337
338         eh = path[depth].p_hdr;
339         ex = EXT_FIRST_EXTENT(eh);
340
341         for (i = 0; i < le16_to_cpu(eh->eh_entries); i++, ex++) {
342                 ext_debug("%d:%d:%llu ", le32_to_cpu(ex->ee_block),
343                           ext4_ext_get_actual_len(ex), ext_pblock(ex));
344         }
345         ext_debug("\n");
346 }
347 #else
348 #define ext4_ext_show_path(inode,path)
349 #define ext4_ext_show_leaf(inode,path)
350 #endif
351
352 static void ext4_ext_drop_refs(struct ext4_ext_path *path)
353 {
354         int depth = path->p_depth;
355         int i;
356
357         for (i = 0; i <= depth; i++, path++)
358                 if (path->p_bh) {
359                         brelse(path->p_bh);
360                         path->p_bh = NULL;
361                 }
362 }
363
364 /*
365  * ext4_ext_binsearch_idx:
366  * binary search for the closest index of the given block
367  * the header must be checked before calling this
368  */
369 static void
370 ext4_ext_binsearch_idx(struct inode *inode, struct ext4_ext_path *path, int block)
371 {
372         struct ext4_extent_header *eh = path->p_hdr;
373         struct ext4_extent_idx *r, *l, *m;
374
375
376         ext_debug("binsearch for %d(idx):  ", block);
377
378         l = EXT_FIRST_INDEX(eh) + 1;
379         r = EXT_FIRST_INDEX(eh) + le16_to_cpu(eh->eh_entries) - 1;
380         while (l <= r) {
381                 m = l + (r - l) / 2;
382                 if (block < le32_to_cpu(m->ei_block))
383                         r = m - 1;
384                 else
385                         l = m + 1;
386                 ext_debug("%p(%u):%p(%u):%p(%u) ", l, le32_to_cpu(l->ei_block),
387                                 m, le32_to_cpu(m->ei_block),
388                                 r, le32_to_cpu(r->ei_block));
389         }
390
391         path->p_idx = l - 1;
392         ext_debug("  -> %d->%lld ", le32_to_cpu(path->p_idx->ei_block),
393                   idx_pblock(path->p_idx));
394
395 #ifdef CHECK_BINSEARCH
396         {
397                 struct ext4_extent_idx *chix, *ix;
398                 int k;
399
400                 chix = ix = EXT_FIRST_INDEX(eh);
401                 for (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ix++) {
402                   if (k != 0 &&
403                       le32_to_cpu(ix->ei_block) <= le32_to_cpu(ix[-1].ei_block)) {
404                                 printk("k=%d, ix=0x%p, first=0x%p\n", k,
405                                         ix, EXT_FIRST_INDEX(eh));
406                                 printk("%u <= %u\n",
407                                        le32_to_cpu(ix->ei_block),
408                                        le32_to_cpu(ix[-1].ei_block));
409                         }
410                         BUG_ON(k && le32_to_cpu(ix->ei_block)
411                                            <= le32_to_cpu(ix[-1].ei_block));
412                         if (block < le32_to_cpu(ix->ei_block))
413                                 break;
414                         chix = ix;
415                 }
416                 BUG_ON(chix != path->p_idx);
417         }
418 #endif
419
420 }
421
422 /*
423  * ext4_ext_binsearch:
424  * binary search for closest extent of the given block
425  * the header must be checked before calling this
426  */
427 static void
428 ext4_ext_binsearch(struct inode *inode, struct ext4_ext_path *path, int block)
429 {
430         struct ext4_extent_header *eh = path->p_hdr;
431         struct ext4_extent *r, *l, *m;
432
433         if (eh->eh_entries == 0) {
434                 /*
435                  * this leaf is empty:
436                  * we get such a leaf in split/add case
437                  */
438                 return;
439         }
440
441         ext_debug("binsearch for %d:  ", block);
442
443         l = EXT_FIRST_EXTENT(eh) + 1;
444         r = EXT_FIRST_EXTENT(eh) + le16_to_cpu(eh->eh_entries) - 1;
445
446         while (l <= r) {
447                 m = l + (r - l) / 2;
448                 if (block < le32_to_cpu(m->ee_block))
449                         r = m - 1;
450                 else
451                         l = m + 1;
452                 ext_debug("%p(%u):%p(%u):%p(%u) ", l, le32_to_cpu(l->ee_block),
453                                 m, le32_to_cpu(m->ee_block),
454                                 r, le32_to_cpu(r->ee_block));
455         }
456
457         path->p_ext = l - 1;
458         ext_debug("  -> %d:%llu:%d ",
459                         le32_to_cpu(path->p_ext->ee_block),
460                         ext_pblock(path->p_ext),
461                         ext4_ext_get_actual_len(path->p_ext));
462
463 #ifdef CHECK_BINSEARCH
464         {
465                 struct ext4_extent *chex, *ex;
466                 int k;
467
468                 chex = ex = EXT_FIRST_EXTENT(eh);
469                 for (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ex++) {
470                         BUG_ON(k && le32_to_cpu(ex->ee_block)
471                                           <= le32_to_cpu(ex[-1].ee_block));
472                         if (block < le32_to_cpu(ex->ee_block))
473                                 break;
474                         chex = ex;
475                 }
476                 BUG_ON(chex != path->p_ext);
477         }
478 #endif
479
480 }
481
482 int ext4_ext_tree_init(handle_t *handle, struct inode *inode)
483 {
484         struct ext4_extent_header *eh;
485
486         eh = ext_inode_hdr(inode);
487         eh->eh_depth = 0;
488         eh->eh_entries = 0;
489         eh->eh_magic = EXT4_EXT_MAGIC;
490         eh->eh_max = cpu_to_le16(ext4_ext_space_root(inode));
491         ext4_mark_inode_dirty(handle, inode);
492         ext4_ext_invalidate_cache(inode);
493         return 0;
494 }
495
496 struct ext4_ext_path *
497 ext4_ext_find_extent(struct inode *inode, int block, struct ext4_ext_path *path)
498 {
499         struct ext4_extent_header *eh;
500         struct buffer_head *bh;
501         short int depth, i, ppos = 0, alloc = 0;
502
503         eh = ext_inode_hdr(inode);
504         depth = ext_depth(inode);
505         if (ext4_ext_check_header(inode, eh, depth))
506                 return ERR_PTR(-EIO);
507
508
509         /* account possible depth increase */
510         if (!path) {
511                 path = kzalloc(sizeof(struct ext4_ext_path) * (depth + 2),
512                                 GFP_NOFS);
513                 if (!path)
514                         return ERR_PTR(-ENOMEM);
515                 alloc = 1;
516         }
517         path[0].p_hdr = eh;
518
519         i = depth;
520         /* walk through the tree */
521         while (i) {
522                 ext_debug("depth %d: num %d, max %d\n",
523                           ppos, le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
524
525                 ext4_ext_binsearch_idx(inode, path + ppos, block);
526                 path[ppos].p_block = idx_pblock(path[ppos].p_idx);
527                 path[ppos].p_depth = i;
528                 path[ppos].p_ext = NULL;
529
530                 bh = sb_bread(inode->i_sb, path[ppos].p_block);
531                 if (!bh)
532                         goto err;
533
534                 eh = ext_block_hdr(bh);
535                 ppos++;
536                 BUG_ON(ppos > depth);
537                 path[ppos].p_bh = bh;
538                 path[ppos].p_hdr = eh;
539                 i--;
540
541                 if (ext4_ext_check_header(inode, eh, i))
542                         goto err;
543         }
544
545         path[ppos].p_depth = i;
546         path[ppos].p_hdr = eh;
547         path[ppos].p_ext = NULL;
548         path[ppos].p_idx = NULL;
549
550         /* find extent */
551         ext4_ext_binsearch(inode, path + ppos, block);
552
553         ext4_ext_show_path(inode, path);
554
555         return path;
556
557 err:
558         ext4_ext_drop_refs(path);
559         if (alloc)
560                 kfree(path);
561         return ERR_PTR(-EIO);
562 }
563
564 /*
565  * ext4_ext_insert_index:
566  * insert new index [@logical;@ptr] into the block at @curp;
567  * check where to insert: before @curp or after @curp
568  */
569 static int ext4_ext_insert_index(handle_t *handle, struct inode *inode,
570                                 struct ext4_ext_path *curp,
571                                 int logical, ext4_fsblk_t ptr)
572 {
573         struct ext4_extent_idx *ix;
574         int len, err;
575
576         err = ext4_ext_get_access(handle, inode, curp);
577         if (err)
578                 return err;
579
580         BUG_ON(logical == le32_to_cpu(curp->p_idx->ei_block));
581         len = EXT_MAX_INDEX(curp->p_hdr) - curp->p_idx;
582         if (logical > le32_to_cpu(curp->p_idx->ei_block)) {
583                 /* insert after */
584                 if (curp->p_idx != EXT_LAST_INDEX(curp->p_hdr)) {
585                         len = (len - 1) * sizeof(struct ext4_extent_idx);
586                         len = len < 0 ? 0 : len;
587                         ext_debug("insert new index %d after: %llu. "
588                                         "move %d from 0x%p to 0x%p\n",
589                                         logical, ptr, len,
590                                         (curp->p_idx + 1), (curp->p_idx + 2));
591                         memmove(curp->p_idx + 2, curp->p_idx + 1, len);
592                 }
593                 ix = curp->p_idx + 1;
594         } else {
595                 /* insert before */
596                 len = len * sizeof(struct ext4_extent_idx);
597                 len = len < 0 ? 0 : len;
598                 ext_debug("insert new index %d before: %llu. "
599                                 "move %d from 0x%p to 0x%p\n",
600                                 logical, ptr, len,
601                                 curp->p_idx, (curp->p_idx + 1));
602                 memmove(curp->p_idx + 1, curp->p_idx, len);
603                 ix = curp->p_idx;
604         }
605
606         ix->ei_block = cpu_to_le32(logical);
607         ext4_idx_store_pblock(ix, ptr);
608         curp->p_hdr->eh_entries = cpu_to_le16(le16_to_cpu(curp->p_hdr->eh_entries)+1);
609
610         BUG_ON(le16_to_cpu(curp->p_hdr->eh_entries)
611                              > le16_to_cpu(curp->p_hdr->eh_max));
612         BUG_ON(ix > EXT_LAST_INDEX(curp->p_hdr));
613
614         err = ext4_ext_dirty(handle, inode, curp);
615         ext4_std_error(inode->i_sb, err);
616
617         return err;
618 }
619
620 /*
621  * ext4_ext_split:
622  * inserts new subtree into the path, using free index entry
623  * at depth @at:
624  * - allocates all needed blocks (new leaf and all intermediate index blocks)
625  * - makes decision where to split
626  * - moves remaining extents and index entries (right to the split point)
627  *   into the newly allocated blocks
628  * - initializes subtree
629  */
630 static int ext4_ext_split(handle_t *handle, struct inode *inode,
631                                 struct ext4_ext_path *path,
632                                 struct ext4_extent *newext, int at)
633 {
634         struct buffer_head *bh = NULL;
635         int depth = ext_depth(inode);
636         struct ext4_extent_header *neh;
637         struct ext4_extent_idx *fidx;
638         struct ext4_extent *ex;
639         int i = at, k, m, a;
640         ext4_fsblk_t newblock, oldblock;
641         __le32 border;
642         ext4_fsblk_t *ablocks = NULL; /* array of allocated blocks */
643         int err = 0;
644
645         /* make decision: where to split? */
646         /* FIXME: now decision is simplest: at current extent */
647
648         /* if current leaf will be split, then we should use
649          * border from split point */
650         BUG_ON(path[depth].p_ext > EXT_MAX_EXTENT(path[depth].p_hdr));
651         if (path[depth].p_ext != EXT_MAX_EXTENT(path[depth].p_hdr)) {
652                 border = path[depth].p_ext[1].ee_block;
653                 ext_debug("leaf will be split."
654                                 " next leaf starts at %d\n",
655                                   le32_to_cpu(border));
656         } else {
657                 border = newext->ee_block;
658                 ext_debug("leaf will be added."
659                                 " next leaf starts at %d\n",
660                                 le32_to_cpu(border));
661         }
662
663         /*
664          * If error occurs, then we break processing
665          * and mark filesystem read-only. index won't
666          * be inserted and tree will be in consistent
667          * state. Next mount will repair buffers too.
668          */
669
670         /*
671          * Get array to track all allocated blocks.
672          * We need this to handle errors and free blocks
673          * upon them.
674          */
675         ablocks = kzalloc(sizeof(ext4_fsblk_t) * depth, GFP_NOFS);
676         if (!ablocks)
677                 return -ENOMEM;
678
679         /* allocate all needed blocks */
680         ext_debug("allocate %d blocks for indexes/leaf\n", depth - at);
681         for (a = 0; a < depth - at; a++) {
682                 newblock = ext4_ext_new_block(handle, inode, path, newext, &err);
683                 if (newblock == 0)
684                         goto cleanup;
685                 ablocks[a] = newblock;
686         }
687
688         /* initialize new leaf */
689         newblock = ablocks[--a];
690         BUG_ON(newblock == 0);
691         bh = sb_getblk(inode->i_sb, newblock);
692         if (!bh) {
693                 err = -EIO;
694                 goto cleanup;
695         }
696         lock_buffer(bh);
697
698         err = ext4_journal_get_create_access(handle, bh);
699         if (err)
700                 goto cleanup;
701
702         neh = ext_block_hdr(bh);
703         neh->eh_entries = 0;
704         neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode));
705         neh->eh_magic = EXT4_EXT_MAGIC;
706         neh->eh_depth = 0;
707         ex = EXT_FIRST_EXTENT(neh);
708
709         /* move remainder of path[depth] to the new leaf */
710         BUG_ON(path[depth].p_hdr->eh_entries != path[depth].p_hdr->eh_max);
711         /* start copy from next extent */
712         /* TODO: we could do it by single memmove */
713         m = 0;
714         path[depth].p_ext++;
715         while (path[depth].p_ext <=
716                         EXT_MAX_EXTENT(path[depth].p_hdr)) {
717                 ext_debug("move %d:%llu:%d in new leaf %llu\n",
718                                 le32_to_cpu(path[depth].p_ext->ee_block),
719                                 ext_pblock(path[depth].p_ext),
720                                 ext4_ext_get_actual_len(path[depth].p_ext),
721                                 newblock);
722                 /*memmove(ex++, path[depth].p_ext++,
723                                 sizeof(struct ext4_extent));
724                 neh->eh_entries++;*/
725                 path[depth].p_ext++;
726                 m++;
727         }
728         if (m) {
729                 memmove(ex, path[depth].p_ext-m, sizeof(struct ext4_extent)*m);
730                 neh->eh_entries = cpu_to_le16(le16_to_cpu(neh->eh_entries)+m);
731         }
732
733         set_buffer_uptodate(bh);
734         unlock_buffer(bh);
735
736         err = ext4_journal_dirty_metadata(handle, bh);
737         if (err)
738                 goto cleanup;
739         brelse(bh);
740         bh = NULL;
741
742         /* correct old leaf */
743         if (m) {
744                 err = ext4_ext_get_access(handle, inode, path + depth);
745                 if (err)
746                         goto cleanup;
747                 path[depth].p_hdr->eh_entries =
748                      cpu_to_le16(le16_to_cpu(path[depth].p_hdr->eh_entries)-m);
749                 err = ext4_ext_dirty(handle, inode, path + depth);
750                 if (err)
751                         goto cleanup;
752
753         }
754
755         /* create intermediate indexes */
756         k = depth - at - 1;
757         BUG_ON(k < 0);
758         if (k)
759                 ext_debug("create %d intermediate indices\n", k);
760         /* insert new index into current index block */
761         /* current depth stored in i var */
762         i = depth - 1;
763         while (k--) {
764                 oldblock = newblock;
765                 newblock = ablocks[--a];
766                 bh = sb_getblk(inode->i_sb, (ext4_fsblk_t)newblock);
767                 if (!bh) {
768                         err = -EIO;
769                         goto cleanup;
770                 }
771                 lock_buffer(bh);
772
773                 err = ext4_journal_get_create_access(handle, bh);
774                 if (err)
775                         goto cleanup;
776
777                 neh = ext_block_hdr(bh);
778                 neh->eh_entries = cpu_to_le16(1);
779                 neh->eh_magic = EXT4_EXT_MAGIC;
780                 neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode));
781                 neh->eh_depth = cpu_to_le16(depth - i);
782                 fidx = EXT_FIRST_INDEX(neh);
783                 fidx->ei_block = border;
784                 ext4_idx_store_pblock(fidx, oldblock);
785
786                 ext_debug("int.index at %d (block %llu): %lu -> %llu\n", i,
787                                 newblock, (unsigned long) le32_to_cpu(border),
788                                 oldblock);
789                 /* copy indexes */
790                 m = 0;
791                 path[i].p_idx++;
792
793                 ext_debug("cur 0x%p, last 0x%p\n", path[i].p_idx,
794                                 EXT_MAX_INDEX(path[i].p_hdr));
795                 BUG_ON(EXT_MAX_INDEX(path[i].p_hdr) !=
796                                 EXT_LAST_INDEX(path[i].p_hdr));
797                 while (path[i].p_idx <= EXT_MAX_INDEX(path[i].p_hdr)) {
798                         ext_debug("%d: move %d:%llu in new index %llu\n", i,
799                                         le32_to_cpu(path[i].p_idx->ei_block),
800                                         idx_pblock(path[i].p_idx),
801                                         newblock);
802                         /*memmove(++fidx, path[i].p_idx++,
803                                         sizeof(struct ext4_extent_idx));
804                         neh->eh_entries++;
805                         BUG_ON(neh->eh_entries > neh->eh_max);*/
806                         path[i].p_idx++;
807                         m++;
808                 }
809                 if (m) {
810                         memmove(++fidx, path[i].p_idx - m,
811                                 sizeof(struct ext4_extent_idx) * m);
812                         neh->eh_entries =
813                                 cpu_to_le16(le16_to_cpu(neh->eh_entries) + m);
814                 }
815                 set_buffer_uptodate(bh);
816                 unlock_buffer(bh);
817
818                 err = ext4_journal_dirty_metadata(handle, bh);
819                 if (err)
820                         goto cleanup;
821                 brelse(bh);
822                 bh = NULL;
823
824                 /* correct old index */
825                 if (m) {
826                         err = ext4_ext_get_access(handle, inode, path + i);
827                         if (err)
828                                 goto cleanup;
829                         path[i].p_hdr->eh_entries = cpu_to_le16(le16_to_cpu(path[i].p_hdr->eh_entries)-m);
830                         err = ext4_ext_dirty(handle, inode, path + i);
831                         if (err)
832                                 goto cleanup;
833                 }
834
835                 i--;
836         }
837
838         /* insert new index */
839         err = ext4_ext_insert_index(handle, inode, path + at,
840                                     le32_to_cpu(border), newblock);
841
842 cleanup:
843         if (bh) {
844                 if (buffer_locked(bh))
845                         unlock_buffer(bh);
846                 brelse(bh);
847         }
848
849         if (err) {
850                 /* free all allocated blocks in error case */
851                 for (i = 0; i < depth; i++) {
852                         if (!ablocks[i])
853                                 continue;
854                         ext4_free_blocks(handle, inode, ablocks[i], 1);
855                 }
856         }
857         kfree(ablocks);
858
859         return err;
860 }
861
862 /*
863  * ext4_ext_grow_indepth:
864  * implements tree growing procedure:
865  * - allocates new block
866  * - moves top-level data (index block or leaf) into the new block
867  * - initializes new top-level, creating index that points to the
868  *   just created block
869  */
870 static int ext4_ext_grow_indepth(handle_t *handle, struct inode *inode,
871                                         struct ext4_ext_path *path,
872                                         struct ext4_extent *newext)
873 {
874         struct ext4_ext_path *curp = path;
875         struct ext4_extent_header *neh;
876         struct ext4_extent_idx *fidx;
877         struct buffer_head *bh;
878         ext4_fsblk_t newblock;
879         int err = 0;
880
881         newblock = ext4_ext_new_block(handle, inode, path, newext, &err);
882         if (newblock == 0)
883                 return err;
884
885         bh = sb_getblk(inode->i_sb, newblock);
886         if (!bh) {
887                 err = -EIO;
888                 ext4_std_error(inode->i_sb, err);
889                 return err;
890         }
891         lock_buffer(bh);
892
893         err = ext4_journal_get_create_access(handle, bh);
894         if (err) {
895                 unlock_buffer(bh);
896                 goto out;
897         }
898
899         /* move top-level index/leaf into new block */
900         memmove(bh->b_data, curp->p_hdr, sizeof(EXT4_I(inode)->i_data));
901
902         /* set size of new block */
903         neh = ext_block_hdr(bh);
904         /* old root could have indexes or leaves
905          * so calculate e_max right way */
906         if (ext_depth(inode))
907           neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode));
908         else
909           neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode));
910         neh->eh_magic = EXT4_EXT_MAGIC;
911         set_buffer_uptodate(bh);
912         unlock_buffer(bh);
913
914         err = ext4_journal_dirty_metadata(handle, bh);
915         if (err)
916                 goto out;
917
918         /* create index in new top-level index: num,max,pointer */
919         err = ext4_ext_get_access(handle, inode, curp);
920         if (err)
921                 goto out;
922
923         curp->p_hdr->eh_magic = EXT4_EXT_MAGIC;
924         curp->p_hdr->eh_max = cpu_to_le16(ext4_ext_space_root_idx(inode));
925         curp->p_hdr->eh_entries = cpu_to_le16(1);
926         curp->p_idx = EXT_FIRST_INDEX(curp->p_hdr);
927         /* FIXME: it works, but actually path[0] can be index */
928         curp->p_idx->ei_block = EXT_FIRST_EXTENT(path[0].p_hdr)->ee_block;
929         ext4_idx_store_pblock(curp->p_idx, newblock);
930
931         neh = ext_inode_hdr(inode);
932         fidx = EXT_FIRST_INDEX(neh);
933         ext_debug("new root: num %d(%d), lblock %d, ptr %llu\n",
934                   le16_to_cpu(neh->eh_entries), le16_to_cpu(neh->eh_max),
935                   le32_to_cpu(fidx->ei_block), idx_pblock(fidx));
936
937         neh->eh_depth = cpu_to_le16(path->p_depth + 1);
938         err = ext4_ext_dirty(handle, inode, curp);
939 out:
940         brelse(bh);
941
942         return err;
943 }
944
945 /*
946  * ext4_ext_create_new_leaf:
947  * finds empty index and adds new leaf.
948  * if no free index is found, then it requests in-depth growing.
949  */
950 static int ext4_ext_create_new_leaf(handle_t *handle, struct inode *inode,
951                                         struct ext4_ext_path *path,
952                                         struct ext4_extent *newext)
953 {
954         struct ext4_ext_path *curp;
955         int depth, i, err = 0;
956
957 repeat:
958         i = depth = ext_depth(inode);
959
960         /* walk up to the tree and look for free index entry */
961         curp = path + depth;
962         while (i > 0 && !EXT_HAS_FREE_INDEX(curp)) {
963                 i--;
964                 curp--;
965         }
966
967         /* we use already allocated block for index block,
968          * so subsequent data blocks should be contiguous */
969         if (EXT_HAS_FREE_INDEX(curp)) {
970                 /* if we found index with free entry, then use that
971                  * entry: create all needed subtree and add new leaf */
972                 err = ext4_ext_split(handle, inode, path, newext, i);
973
974                 /* refill path */
975                 ext4_ext_drop_refs(path);
976                 path = ext4_ext_find_extent(inode,
977                                             le32_to_cpu(newext->ee_block),
978                                             path);
979                 if (IS_ERR(path))
980                         err = PTR_ERR(path);
981         } else {
982                 /* tree is full, time to grow in depth */
983                 err = ext4_ext_grow_indepth(handle, inode, path, newext);
984                 if (err)
985                         goto out;
986
987                 /* refill path */
988                 ext4_ext_drop_refs(path);
989                 path = ext4_ext_find_extent(inode,
990                                             le32_to_cpu(newext->ee_block),
991                                             path);
992                 if (IS_ERR(path)) {
993                         err = PTR_ERR(path);
994                         goto out;
995                 }
996
997                 /*
998                  * only first (depth 0 -> 1) produces free space;
999                  * in all other cases we have to split the grown tree
1000                  */
1001                 depth = ext_depth(inode);
1002                 if (path[depth].p_hdr->eh_entries == path[depth].p_hdr->eh_max) {
1003                         /* now we need to split */
1004                         goto repeat;
1005                 }
1006         }
1007
1008 out:
1009         return err;
1010 }
1011
1012 /*
1013  * ext4_ext_next_allocated_block:
1014  * returns allocated block in subsequent extent or EXT_MAX_BLOCK.
1015  * NOTE: it considers block number from index entry as
1016  * allocated block. Thus, index entries have to be consistent
1017  * with leaves.
1018  */
1019 static unsigned long
1020 ext4_ext_next_allocated_block(struct ext4_ext_path *path)
1021 {
1022         int depth;
1023
1024         BUG_ON(path == NULL);
1025         depth = path->p_depth;
1026
1027         if (depth == 0 && path->p_ext == NULL)
1028                 return EXT_MAX_BLOCK;
1029
1030         while (depth >= 0) {
1031                 if (depth == path->p_depth) {
1032                         /* leaf */
1033                         if (path[depth].p_ext !=
1034                                         EXT_LAST_EXTENT(path[depth].p_hdr))
1035                           return le32_to_cpu(path[depth].p_ext[1].ee_block);
1036                 } else {
1037                         /* index */
1038                         if (path[depth].p_idx !=
1039                                         EXT_LAST_INDEX(path[depth].p_hdr))
1040                           return le32_to_cpu(path[depth].p_idx[1].ei_block);
1041                 }
1042                 depth--;
1043         }
1044
1045         return EXT_MAX_BLOCK;
1046 }
1047
1048 /*
1049  * ext4_ext_next_leaf_block:
1050  * returns first allocated block from next leaf or EXT_MAX_BLOCK
1051  */
1052 static unsigned ext4_ext_next_leaf_block(struct inode *inode,
1053                                         struct ext4_ext_path *path)
1054 {
1055         int depth;
1056
1057         BUG_ON(path == NULL);
1058         depth = path->p_depth;
1059
1060         /* zero-tree has no leaf blocks at all */
1061         if (depth == 0)
1062                 return EXT_MAX_BLOCK;
1063
1064         /* go to index block */
1065         depth--;
1066
1067         while (depth >= 0) {
1068                 if (path[depth].p_idx !=
1069                                 EXT_LAST_INDEX(path[depth].p_hdr))
1070                   return le32_to_cpu(path[depth].p_idx[1].ei_block);
1071                 depth--;
1072         }
1073
1074         return EXT_MAX_BLOCK;
1075 }
1076
1077 /*
1078  * ext4_ext_correct_indexes:
1079  * if leaf gets modified and modified extent is first in the leaf,
1080  * then we have to correct all indexes above.
1081  * TODO: do we need to correct tree in all cases?
1082  */
1083 int ext4_ext_correct_indexes(handle_t *handle, struct inode *inode,
1084                                 struct ext4_ext_path *path)
1085 {
1086         struct ext4_extent_header *eh;
1087         int depth = ext_depth(inode);
1088         struct ext4_extent *ex;
1089         __le32 border;
1090         int k, err = 0;
1091
1092         eh = path[depth].p_hdr;
1093         ex = path[depth].p_ext;
1094         BUG_ON(ex == NULL);
1095         BUG_ON(eh == NULL);
1096
1097         if (depth == 0) {
1098                 /* there is no tree at all */
1099                 return 0;
1100         }
1101
1102         if (ex != EXT_FIRST_EXTENT(eh)) {
1103                 /* we correct tree if first leaf got modified only */
1104                 return 0;
1105         }
1106
1107         /*
1108          * TODO: we need correction if border is smaller than current one
1109          */
1110         k = depth - 1;
1111         border = path[depth].p_ext->ee_block;
1112         err = ext4_ext_get_access(handle, inode, path + k);
1113         if (err)
1114                 return err;
1115         path[k].p_idx->ei_block = border;
1116         err = ext4_ext_dirty(handle, inode, path + k);
1117         if (err)
1118                 return err;
1119
1120         while (k--) {
1121                 /* change all left-side indexes */
1122                 if (path[k+1].p_idx != EXT_FIRST_INDEX(path[k+1].p_hdr))
1123                         break;
1124                 err = ext4_ext_get_access(handle, inode, path + k);
1125                 if (err)
1126                         break;
1127                 path[k].p_idx->ei_block = border;
1128                 err = ext4_ext_dirty(handle, inode, path + k);
1129                 if (err)
1130                         break;
1131         }
1132
1133         return err;
1134 }
1135
1136 static int
1137 ext4_can_extents_be_merged(struct inode *inode, struct ext4_extent *ex1,
1138                                 struct ext4_extent *ex2)
1139 {
1140         unsigned short ext1_ee_len, ext2_ee_len, max_len;
1141
1142         /*
1143          * Make sure that either both extents are uninitialized, or
1144          * both are _not_.
1145          */
1146         if (ext4_ext_is_uninitialized(ex1) ^ ext4_ext_is_uninitialized(ex2))
1147                 return 0;
1148
1149         if (ext4_ext_is_uninitialized(ex1))
1150                 max_len = EXT_UNINIT_MAX_LEN;
1151         else
1152                 max_len = EXT_INIT_MAX_LEN;
1153
1154         ext1_ee_len = ext4_ext_get_actual_len(ex1);
1155         ext2_ee_len = ext4_ext_get_actual_len(ex2);
1156
1157         if (le32_to_cpu(ex1->ee_block) + ext1_ee_len !=
1158                         le32_to_cpu(ex2->ee_block))
1159                 return 0;
1160
1161         /*
1162          * To allow future support for preallocated extents to be added
1163          * as an RO_COMPAT feature, refuse to merge to extents if
1164          * this can result in the top bit of ee_len being set.
1165          */
1166         if (ext1_ee_len + ext2_ee_len > max_len)
1167                 return 0;
1168 #ifdef AGGRESSIVE_TEST
1169         if (le16_to_cpu(ex1->ee_len) >= 4)
1170                 return 0;
1171 #endif
1172
1173         if (ext_pblock(ex1) + ext1_ee_len == ext_pblock(ex2))
1174                 return 1;
1175         return 0;
1176 }
1177
1178 /*
1179  * This function tries to merge the "ex" extent to the next extent in the tree.
1180  * It always tries to merge towards right. If you want to merge towards
1181  * left, pass "ex - 1" as argument instead of "ex".
1182  * Returns 0 if the extents (ex and ex+1) were _not_ merged and returns
1183  * 1 if they got merged.
1184  */
1185 int ext4_ext_try_to_merge(struct inode *inode,
1186                           struct ext4_ext_path *path,
1187                           struct ext4_extent *ex)
1188 {
1189         struct ext4_extent_header *eh;
1190         unsigned int depth, len;
1191         int merge_done = 0;
1192         int uninitialized = 0;
1193
1194         depth = ext_depth(inode);
1195         BUG_ON(path[depth].p_hdr == NULL);
1196         eh = path[depth].p_hdr;
1197
1198         while (ex < EXT_LAST_EXTENT(eh)) {
1199                 if (!ext4_can_extents_be_merged(inode, ex, ex + 1))
1200                         break;
1201                 /* merge with next extent! */
1202                 if (ext4_ext_is_uninitialized(ex))
1203                         uninitialized = 1;
1204                 ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
1205                                 + ext4_ext_get_actual_len(ex + 1));
1206                 if (uninitialized)
1207                         ext4_ext_mark_uninitialized(ex);
1208
1209                 if (ex + 1 < EXT_LAST_EXTENT(eh)) {
1210                         len = (EXT_LAST_EXTENT(eh) - ex - 1)
1211                                 * sizeof(struct ext4_extent);
1212                         memmove(ex + 1, ex + 2, len);
1213                 }
1214                 eh->eh_entries = cpu_to_le16(le16_to_cpu(eh->eh_entries) - 1);
1215                 merge_done = 1;
1216                 WARN_ON(eh->eh_entries == 0);
1217                 if (!eh->eh_entries)
1218                         ext4_error(inode->i_sb, "ext4_ext_try_to_merge",
1219                            "inode#%lu, eh->eh_entries = 0!", inode->i_ino);
1220         }
1221
1222         return merge_done;
1223 }
1224
1225 /*
1226  * check if a portion of the "newext" extent overlaps with an
1227  * existing extent.
1228  *
1229  * If there is an overlap discovered, it updates the length of the newext
1230  * such that there will be no overlap, and then returns 1.
1231  * If there is no overlap found, it returns 0.
1232  */
1233 unsigned int ext4_ext_check_overlap(struct inode *inode,
1234                                     struct ext4_extent *newext,
1235                                     struct ext4_ext_path *path)
1236 {
1237         unsigned long b1, b2;
1238         unsigned int depth, len1;
1239         unsigned int ret = 0;
1240
1241         b1 = le32_to_cpu(newext->ee_block);
1242         len1 = ext4_ext_get_actual_len(newext);
1243         depth = ext_depth(inode);
1244         if (!path[depth].p_ext)
1245                 goto out;
1246         b2 = le32_to_cpu(path[depth].p_ext->ee_block);
1247
1248         /*
1249          * get the next allocated block if the extent in the path
1250          * is before the requested block(s) 
1251          */
1252         if (b2 < b1) {
1253                 b2 = ext4_ext_next_allocated_block(path);
1254                 if (b2 == EXT_MAX_BLOCK)
1255                         goto out;
1256         }
1257
1258         /* check for wrap through zero */
1259         if (b1 + len1 < b1) {
1260                 len1 = EXT_MAX_BLOCK - b1;
1261                 newext->ee_len = cpu_to_le16(len1);
1262                 ret = 1;
1263         }
1264
1265         /* check for overlap */
1266         if (b1 + len1 > b2) {
1267                 newext->ee_len = cpu_to_le16(b2 - b1);
1268                 ret = 1;
1269         }
1270 out:
1271         return ret;
1272 }
1273
1274 /*
1275  * ext4_ext_insert_extent:
1276  * tries to merge requsted extent into the existing extent or
1277  * inserts requested extent as new one into the tree,
1278  * creating new leaf in the no-space case.
1279  */
1280 int ext4_ext_insert_extent(handle_t *handle, struct inode *inode,
1281                                 struct ext4_ext_path *path,
1282                                 struct ext4_extent *newext)
1283 {
1284         struct ext4_extent_header * eh;
1285         struct ext4_extent *ex, *fex;
1286         struct ext4_extent *nearex; /* nearest extent */
1287         struct ext4_ext_path *npath = NULL;
1288         int depth, len, err, next;
1289         unsigned uninitialized = 0;
1290
1291         BUG_ON(ext4_ext_get_actual_len(newext) == 0);
1292         depth = ext_depth(inode);
1293         ex = path[depth].p_ext;
1294         BUG_ON(path[depth].p_hdr == NULL);
1295
1296         /* try to insert block into found extent and return */
1297         if (ex && ext4_can_extents_be_merged(inode, ex, newext)) {
1298                 ext_debug("append %d block to %d:%d (from %llu)\n",
1299                                 ext4_ext_get_actual_len(newext),
1300                                 le32_to_cpu(ex->ee_block),
1301                                 ext4_ext_get_actual_len(ex), ext_pblock(ex));
1302                 err = ext4_ext_get_access(handle, inode, path + depth);
1303                 if (err)
1304                         return err;
1305
1306                 /*
1307                  * ext4_can_extents_be_merged should have checked that either
1308                  * both extents are uninitialized, or both aren't. Thus we
1309                  * need to check only one of them here.
1310                  */
1311                 if (ext4_ext_is_uninitialized(ex))
1312                         uninitialized = 1;
1313                 ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
1314                                         + ext4_ext_get_actual_len(newext));
1315                 if (uninitialized)
1316                         ext4_ext_mark_uninitialized(ex);
1317                 eh = path[depth].p_hdr;
1318                 nearex = ex;
1319                 goto merge;
1320         }
1321
1322 repeat:
1323         depth = ext_depth(inode);
1324         eh = path[depth].p_hdr;
1325         if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max))
1326                 goto has_space;
1327
1328         /* probably next leaf has space for us? */
1329         fex = EXT_LAST_EXTENT(eh);
1330         next = ext4_ext_next_leaf_block(inode, path);
1331         if (le32_to_cpu(newext->ee_block) > le32_to_cpu(fex->ee_block)
1332             && next != EXT_MAX_BLOCK) {
1333                 ext_debug("next leaf block - %d\n", next);
1334                 BUG_ON(npath != NULL);
1335                 npath = ext4_ext_find_extent(inode, next, NULL);
1336                 if (IS_ERR(npath))
1337                         return PTR_ERR(npath);
1338                 BUG_ON(npath->p_depth != path->p_depth);
1339                 eh = npath[depth].p_hdr;
1340                 if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max)) {
1341                         ext_debug("next leaf isnt full(%d)\n",
1342                                   le16_to_cpu(eh->eh_entries));
1343                         path = npath;
1344                         goto repeat;
1345                 }
1346                 ext_debug("next leaf has no free space(%d,%d)\n",
1347                           le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
1348         }
1349
1350         /*
1351          * There is no free space in the found leaf.
1352          * We're gonna add a new leaf in the tree.
1353          */
1354         err = ext4_ext_create_new_leaf(handle, inode, path, newext);
1355         if (err)
1356                 goto cleanup;
1357         depth = ext_depth(inode);
1358         eh = path[depth].p_hdr;
1359
1360 has_space:
1361         nearex = path[depth].p_ext;
1362
1363         err = ext4_ext_get_access(handle, inode, path + depth);
1364         if (err)
1365                 goto cleanup;
1366
1367         if (!nearex) {
1368                 /* there is no extent in this leaf, create first one */
1369                 ext_debug("first extent in the leaf: %d:%llu:%d\n",
1370                                 le32_to_cpu(newext->ee_block),
1371                                 ext_pblock(newext),
1372                                 ext4_ext_get_actual_len(newext));
1373                 path[depth].p_ext = EXT_FIRST_EXTENT(eh);
1374         } else if (le32_to_cpu(newext->ee_block)
1375                            > le32_to_cpu(nearex->ee_block)) {
1376 /*              BUG_ON(newext->ee_block == nearex->ee_block); */
1377                 if (nearex != EXT_LAST_EXTENT(eh)) {
1378                         len = EXT_MAX_EXTENT(eh) - nearex;
1379                         len = (len - 1) * sizeof(struct ext4_extent);
1380                         len = len < 0 ? 0 : len;
1381                         ext_debug("insert %d:%llu:%d after: nearest 0x%p, "
1382                                         "move %d from 0x%p to 0x%p\n",
1383                                         le32_to_cpu(newext->ee_block),
1384                                         ext_pblock(newext),
1385                                         ext4_ext_get_actual_len(newext),
1386                                         nearex, len, nearex + 1, nearex + 2);
1387                         memmove(nearex + 2, nearex + 1, len);
1388                 }
1389                 path[depth].p_ext = nearex + 1;
1390         } else {
1391                 BUG_ON(newext->ee_block == nearex->ee_block);
1392                 len = (EXT_MAX_EXTENT(eh) - nearex) * sizeof(struct ext4_extent);
1393                 len = len < 0 ? 0 : len;
1394                 ext_debug("insert %d:%llu:%d before: nearest 0x%p, "
1395                                 "move %d from 0x%p to 0x%p\n",
1396                                 le32_to_cpu(newext->ee_block),
1397                                 ext_pblock(newext),
1398                                 ext4_ext_get_actual_len(newext),
1399                                 nearex, len, nearex + 1, nearex + 2);
1400                 memmove(nearex + 1, nearex, len);
1401                 path[depth].p_ext = nearex;
1402         }
1403
1404         eh->eh_entries = cpu_to_le16(le16_to_cpu(eh->eh_entries)+1);
1405         nearex = path[depth].p_ext;
1406         nearex->ee_block = newext->ee_block;
1407         nearex->ee_start = newext->ee_start;
1408         nearex->ee_start_hi = newext->ee_start_hi;
1409         nearex->ee_len = newext->ee_len;
1410
1411 merge:
1412         /* try to merge extents to the right */
1413         ext4_ext_try_to_merge(inode, path, nearex);
1414
1415         /* try to merge extents to the left */
1416
1417         /* time to correct all indexes above */
1418         err = ext4_ext_correct_indexes(handle, inode, path);
1419         if (err)
1420                 goto cleanup;
1421
1422         err = ext4_ext_dirty(handle, inode, path + depth);
1423
1424 cleanup:
1425         if (npath) {
1426                 ext4_ext_drop_refs(npath);
1427                 kfree(npath);
1428         }
1429         ext4_ext_tree_changed(inode);
1430         ext4_ext_invalidate_cache(inode);
1431         return err;
1432 }
1433
1434 int ext4_ext_walk_space(struct inode *inode, unsigned long block,
1435                         unsigned long num, ext_prepare_callback func,
1436                         void *cbdata)
1437 {
1438         struct ext4_ext_path *path = NULL;
1439         struct ext4_ext_cache cbex;
1440         struct ext4_extent *ex;
1441         unsigned long next, start = 0, end = 0;
1442         unsigned long last = block + num;
1443         int depth, exists, err = 0;
1444
1445         BUG_ON(func == NULL);
1446         BUG_ON(inode == NULL);
1447
1448         while (block < last && block != EXT_MAX_BLOCK) {
1449                 num = last - block;
1450                 /* find extent for this block */
1451                 path = ext4_ext_find_extent(inode, block, path);
1452                 if (IS_ERR(path)) {
1453                         err = PTR_ERR(path);
1454                         path = NULL;
1455                         break;
1456                 }
1457
1458                 depth = ext_depth(inode);
1459                 BUG_ON(path[depth].p_hdr == NULL);
1460                 ex = path[depth].p_ext;
1461                 next = ext4_ext_next_allocated_block(path);
1462
1463                 exists = 0;
1464                 if (!ex) {
1465                         /* there is no extent yet, so try to allocate
1466                          * all requested space */
1467                         start = block;
1468                         end = block + num;
1469                 } else if (le32_to_cpu(ex->ee_block) > block) {
1470                         /* need to allocate space before found extent */
1471                         start = block;
1472                         end = le32_to_cpu(ex->ee_block);
1473                         if (block + num < end)
1474                                 end = block + num;
1475                 } else if (block >= le32_to_cpu(ex->ee_block)
1476                                         + ext4_ext_get_actual_len(ex)) {
1477                         /* need to allocate space after found extent */
1478                         start = block;
1479                         end = block + num;
1480                         if (end >= next)
1481                                 end = next;
1482                 } else if (block >= le32_to_cpu(ex->ee_block)) {
1483                         /*
1484                          * some part of requested space is covered
1485                          * by found extent
1486                          */
1487                         start = block;
1488                         end = le32_to_cpu(ex->ee_block)
1489                                 + ext4_ext_get_actual_len(ex);
1490                         if (block + num < end)
1491                                 end = block + num;
1492                         exists = 1;
1493                 } else {
1494                         BUG();
1495                 }
1496                 BUG_ON(end <= start);
1497
1498                 if (!exists) {
1499                         cbex.ec_block = start;
1500                         cbex.ec_len = end - start;
1501                         cbex.ec_start = 0;
1502                         cbex.ec_type = EXT4_EXT_CACHE_GAP;
1503                 } else {
1504                         cbex.ec_block = le32_to_cpu(ex->ee_block);
1505                         cbex.ec_len = ext4_ext_get_actual_len(ex);
1506                         cbex.ec_start = ext_pblock(ex);
1507                         cbex.ec_type = EXT4_EXT_CACHE_EXTENT;
1508                 }
1509
1510                 BUG_ON(cbex.ec_len == 0);
1511                 err = func(inode, path, &cbex, cbdata);
1512                 ext4_ext_drop_refs(path);
1513
1514                 if (err < 0)
1515                         break;
1516                 if (err == EXT_REPEAT)
1517                         continue;
1518                 else if (err == EXT_BREAK) {
1519                         err = 0;
1520                         break;
1521                 }
1522
1523                 if (ext_depth(inode) != depth) {
1524                         /* depth was changed. we have to realloc path */
1525                         kfree(path);
1526                         path = NULL;
1527                 }
1528
1529                 block = cbex.ec_block + cbex.ec_len;
1530         }
1531
1532         if (path) {
1533                 ext4_ext_drop_refs(path);
1534                 kfree(path);
1535         }
1536
1537         return err;
1538 }
1539
1540 static void
1541 ext4_ext_put_in_cache(struct inode *inode, __u32 block,
1542                         __u32 len, __u32 start, int type)
1543 {
1544         struct ext4_ext_cache *cex;
1545         BUG_ON(len == 0);
1546         cex = &EXT4_I(inode)->i_cached_extent;
1547         cex->ec_type = type;
1548         cex->ec_block = block;
1549         cex->ec_len = len;
1550         cex->ec_start = start;
1551 }
1552
1553 /*
1554  * ext4_ext_put_gap_in_cache:
1555  * calculate boundaries of the gap that the requested block fits into
1556  * and cache this gap
1557  */
1558 static void
1559 ext4_ext_put_gap_in_cache(struct inode *inode, struct ext4_ext_path *path,
1560                                 unsigned long block)
1561 {
1562         int depth = ext_depth(inode);
1563         unsigned long lblock, len;
1564         struct ext4_extent *ex;
1565
1566         ex = path[depth].p_ext;
1567         if (ex == NULL) {
1568                 /* there is no extent yet, so gap is [0;-] */
1569                 lblock = 0;
1570                 len = EXT_MAX_BLOCK;
1571                 ext_debug("cache gap(whole file):");
1572         } else if (block < le32_to_cpu(ex->ee_block)) {
1573                 lblock = block;
1574                 len = le32_to_cpu(ex->ee_block) - block;
1575                 ext_debug("cache gap(before): %lu [%lu:%lu]",
1576                                 (unsigned long) block,
1577                                 (unsigned long) le32_to_cpu(ex->ee_block),
1578                                 (unsigned long) ext4_ext_get_actual_len(ex));
1579         } else if (block >= le32_to_cpu(ex->ee_block)
1580                         + ext4_ext_get_actual_len(ex)) {
1581                 lblock = le32_to_cpu(ex->ee_block)
1582                         + ext4_ext_get_actual_len(ex);
1583                 len = ext4_ext_next_allocated_block(path);
1584                 ext_debug("cache gap(after): [%lu:%lu] %lu",
1585                                 (unsigned long) le32_to_cpu(ex->ee_block),
1586                                 (unsigned long) ext4_ext_get_actual_len(ex),
1587                                 (unsigned long) block);
1588                 BUG_ON(len == lblock);
1589                 len = len - lblock;
1590         } else {
1591                 lblock = len = 0;
1592                 BUG();
1593         }
1594
1595         ext_debug(" -> %lu:%lu\n", (unsigned long) lblock, len);
1596         ext4_ext_put_in_cache(inode, lblock, len, 0, EXT4_EXT_CACHE_GAP);
1597 }
1598
1599 static int
1600 ext4_ext_in_cache(struct inode *inode, unsigned long block,
1601                         struct ext4_extent *ex)
1602 {
1603         struct ext4_ext_cache *cex;
1604
1605         cex = &EXT4_I(inode)->i_cached_extent;
1606
1607         /* has cache valid data? */
1608         if (cex->ec_type == EXT4_EXT_CACHE_NO)
1609                 return EXT4_EXT_CACHE_NO;
1610
1611         BUG_ON(cex->ec_type != EXT4_EXT_CACHE_GAP &&
1612                         cex->ec_type != EXT4_EXT_CACHE_EXTENT);
1613         if (block >= cex->ec_block && block < cex->ec_block + cex->ec_len) {
1614                 ex->ee_block = cpu_to_le32(cex->ec_block);
1615                 ext4_ext_store_pblock(ex, cex->ec_start);
1616                 ex->ee_len = cpu_to_le16(cex->ec_len);
1617                 ext_debug("%lu cached by %lu:%lu:%llu\n",
1618                                 (unsigned long) block,
1619                                 (unsigned long) cex->ec_block,
1620                                 (unsigned long) cex->ec_len,
1621                                 cex->ec_start);
1622                 return cex->ec_type;
1623         }
1624
1625         /* not in cache */
1626         return EXT4_EXT_CACHE_NO;
1627 }
1628
1629 /*
1630  * ext4_ext_rm_idx:
1631  * removes index from the index block.
1632  * It's used in truncate case only, thus all requests are for
1633  * last index in the block only.
1634  */
1635 int ext4_ext_rm_idx(handle_t *handle, struct inode *inode,
1636                         struct ext4_ext_path *path)
1637 {
1638         struct buffer_head *bh;
1639         int err;
1640         ext4_fsblk_t leaf;
1641
1642         /* free index block */
1643         path--;
1644         leaf = idx_pblock(path->p_idx);
1645         BUG_ON(path->p_hdr->eh_entries == 0);
1646         err = ext4_ext_get_access(handle, inode, path);
1647         if (err)
1648                 return err;
1649         path->p_hdr->eh_entries = cpu_to_le16(le16_to_cpu(path->p_hdr->eh_entries)-1);
1650         err = ext4_ext_dirty(handle, inode, path);
1651         if (err)
1652                 return err;
1653         ext_debug("index is empty, remove it, free block %llu\n", leaf);
1654         bh = sb_find_get_block(inode->i_sb, leaf);
1655         ext4_forget(handle, 1, inode, bh, leaf);
1656         ext4_free_blocks(handle, inode, leaf, 1);
1657         return err;
1658 }
1659
1660 /*
1661  * ext4_ext_calc_credits_for_insert:
1662  * This routine returns max. credits that the extent tree can consume.
1663  * It should be OK for low-performance paths like ->writepage()
1664  * To allow many writing processes to fit into a single transaction,
1665  * the caller should calculate credits under truncate_mutex and
1666  * pass the actual path.
1667  */
1668 int ext4_ext_calc_credits_for_insert(struct inode *inode,
1669                                                 struct ext4_ext_path *path)
1670 {
1671         int depth, needed;
1672
1673         if (path) {
1674                 /* probably there is space in leaf? */
1675                 depth = ext_depth(inode);
1676                 if (le16_to_cpu(path[depth].p_hdr->eh_entries)
1677                                 < le16_to_cpu(path[depth].p_hdr->eh_max))
1678                         return 1;
1679         }
1680
1681         /*
1682          * given 32-bit logical block (4294967296 blocks), max. tree
1683          * can be 4 levels in depth -- 4 * 340^4 == 53453440000.
1684          * Let's also add one more level for imbalance.
1685          */
1686         depth = 5;
1687
1688         /* allocation of new data block(s) */
1689         needed = 2;
1690
1691         /*
1692          * tree can be full, so it would need to grow in depth:
1693          * we need one credit to modify old root, credits for
1694          * new root will be added in split accounting
1695          */
1696         needed += 1;
1697
1698         /*
1699          * Index split can happen, we would need:
1700          *    allocate intermediate indexes (bitmap + group)
1701          *  + change two blocks at each level, but root (already included)
1702          */
1703         needed += (depth * 2) + (depth * 2);
1704
1705         /* any allocation modifies superblock */
1706         needed += 1;
1707
1708         return needed;
1709 }
1710
1711 static int ext4_remove_blocks(handle_t *handle, struct inode *inode,
1712                                 struct ext4_extent *ex,
1713                                 unsigned long from, unsigned long to)
1714 {
1715         struct buffer_head *bh;
1716         unsigned short ee_len =  ext4_ext_get_actual_len(ex);
1717         int i;
1718
1719 #ifdef EXTENTS_STATS
1720         {
1721                 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1722                 spin_lock(&sbi->s_ext_stats_lock);
1723                 sbi->s_ext_blocks += ee_len;
1724                 sbi->s_ext_extents++;
1725                 if (ee_len < sbi->s_ext_min)
1726                         sbi->s_ext_min = ee_len;
1727                 if (ee_len > sbi->s_ext_max)
1728                         sbi->s_ext_max = ee_len;
1729                 if (ext_depth(inode) > sbi->s_depth_max)
1730                         sbi->s_depth_max = ext_depth(inode);
1731                 spin_unlock(&sbi->s_ext_stats_lock);
1732         }
1733 #endif
1734         if (from >= le32_to_cpu(ex->ee_block)
1735             && to == le32_to_cpu(ex->ee_block) + ee_len - 1) {
1736                 /* tail removal */
1737                 unsigned long num;
1738                 ext4_fsblk_t start;
1739                 num = le32_to_cpu(ex->ee_block) + ee_len - from;
1740                 start = ext_pblock(ex) + ee_len - num;
1741                 ext_debug("free last %lu blocks starting %llu\n", num, start);
1742                 for (i = 0; i < num; i++) {
1743                         bh = sb_find_get_block(inode->i_sb, start + i);
1744                         ext4_forget(handle, 0, inode, bh, start + i);
1745                 }
1746                 ext4_free_blocks(handle, inode, start, num);
1747         } else if (from == le32_to_cpu(ex->ee_block)
1748                    && to <= le32_to_cpu(ex->ee_block) + ee_len - 1) {
1749                 printk("strange request: removal %lu-%lu from %u:%u\n",
1750                         from, to, le32_to_cpu(ex->ee_block), ee_len);
1751         } else {
1752                 printk("strange request: removal(2) %lu-%lu from %u:%u\n",
1753                         from, to, le32_to_cpu(ex->ee_block), ee_len);
1754         }
1755         return 0;
1756 }
1757
1758 static int
1759 ext4_ext_rm_leaf(handle_t *handle, struct inode *inode,
1760                 struct ext4_ext_path *path, unsigned long start)
1761 {
1762         int err = 0, correct_index = 0;
1763         int depth = ext_depth(inode), credits;
1764         struct ext4_extent_header *eh;
1765         unsigned a, b, block, num;
1766         unsigned long ex_ee_block;
1767         unsigned short ex_ee_len;
1768         unsigned uninitialized = 0;
1769         struct ext4_extent *ex;
1770
1771         /* the header must be checked already in ext4_ext_remove_space() */
1772         ext_debug("truncate since %lu in leaf\n", start);
1773         if (!path[depth].p_hdr)
1774                 path[depth].p_hdr = ext_block_hdr(path[depth].p_bh);
1775         eh = path[depth].p_hdr;
1776         BUG_ON(eh == NULL);
1777
1778         /* find where to start removing */
1779         ex = EXT_LAST_EXTENT(eh);
1780
1781         ex_ee_block = le32_to_cpu(ex->ee_block);
1782         if (ext4_ext_is_uninitialized(ex))
1783                 uninitialized = 1;
1784         ex_ee_len = ext4_ext_get_actual_len(ex);
1785
1786         while (ex >= EXT_FIRST_EXTENT(eh) &&
1787                         ex_ee_block + ex_ee_len > start) {
1788                 ext_debug("remove ext %lu:%u\n", ex_ee_block, ex_ee_len);
1789                 path[depth].p_ext = ex;
1790
1791                 a = ex_ee_block > start ? ex_ee_block : start;
1792                 b = ex_ee_block + ex_ee_len - 1 < EXT_MAX_BLOCK ?
1793                         ex_ee_block + ex_ee_len - 1 : EXT_MAX_BLOCK;
1794
1795                 ext_debug("  border %u:%u\n", a, b);
1796
1797                 if (a != ex_ee_block && b != ex_ee_block + ex_ee_len - 1) {
1798                         block = 0;
1799                         num = 0;
1800                         BUG();
1801                 } else if (a != ex_ee_block) {
1802                         /* remove tail of the extent */
1803                         block = ex_ee_block;
1804                         num = a - block;
1805                 } else if (b != ex_ee_block + ex_ee_len - 1) {
1806                         /* remove head of the extent */
1807                         block = a;
1808                         num = b - a;
1809                         /* there is no "make a hole" API yet */
1810                         BUG();
1811                 } else {
1812                         /* remove whole extent: excellent! */
1813                         block = ex_ee_block;
1814                         num = 0;
1815                         BUG_ON(a != ex_ee_block);
1816                         BUG_ON(b != ex_ee_block + ex_ee_len - 1);
1817                 }
1818
1819                 /* at present, extent can't cross block group: */
1820                 /* leaf + bitmap + group desc + sb + inode */
1821                 credits = 5;
1822                 if (ex == EXT_FIRST_EXTENT(eh)) {
1823                         correct_index = 1;
1824                         credits += (ext_depth(inode)) + 1;
1825                 }
1826 #ifdef CONFIG_QUOTA
1827                 credits += 2 * EXT4_QUOTA_TRANS_BLOCKS(inode->i_sb);
1828 #endif
1829
1830                 handle = ext4_ext_journal_restart(handle, credits);
1831                 if (IS_ERR(handle)) {
1832                         err = PTR_ERR(handle);
1833                         goto out;
1834                 }
1835
1836                 err = ext4_ext_get_access(handle, inode, path + depth);
1837                 if (err)
1838                         goto out;
1839
1840                 err = ext4_remove_blocks(handle, inode, ex, a, b);
1841                 if (err)
1842                         goto out;
1843
1844                 if (num == 0) {
1845                         /* this extent is removed; mark slot entirely unused */
1846                         ext4_ext_store_pblock(ex, 0);
1847                         eh->eh_entries = cpu_to_le16(le16_to_cpu(eh->eh_entries)-1);
1848                 }
1849
1850                 ex->ee_block = cpu_to_le32(block);
1851                 ex->ee_len = cpu_to_le16(num);
1852                 /*
1853                  * Do not mark uninitialized if all the blocks in the
1854                  * extent have been removed.
1855                  */
1856                 if (uninitialized && num)
1857                         ext4_ext_mark_uninitialized(ex);
1858
1859                 err = ext4_ext_dirty(handle, inode, path + depth);
1860                 if (err)
1861                         goto out;
1862
1863                 ext_debug("new extent: %u:%u:%llu\n", block, num,
1864                                 ext_pblock(ex));
1865                 ex--;
1866                 ex_ee_block = le32_to_cpu(ex->ee_block);
1867                 ex_ee_len = ext4_ext_get_actual_len(ex);
1868         }
1869
1870         if (correct_index && eh->eh_entries)
1871                 err = ext4_ext_correct_indexes(handle, inode, path);
1872
1873         /* if this leaf is free, then we should
1874          * remove it from index block above */
1875         if (err == 0 && eh->eh_entries == 0 && path[depth].p_bh != NULL)
1876                 err = ext4_ext_rm_idx(handle, inode, path + depth);
1877
1878 out:
1879         return err;
1880 }
1881
1882 /*
1883  * ext4_ext_more_to_rm:
1884  * returns 1 if current index has to be freed (even partial)
1885  */
1886 static int
1887 ext4_ext_more_to_rm(struct ext4_ext_path *path)
1888 {
1889         BUG_ON(path->p_idx == NULL);
1890
1891         if (path->p_idx < EXT_FIRST_INDEX(path->p_hdr))
1892                 return 0;
1893
1894         /*
1895          * if truncate on deeper level happened, it wasn't partial,
1896          * so we have to consider current index for truncation
1897          */
1898         if (le16_to_cpu(path->p_hdr->eh_entries) == path->p_block)
1899                 return 0;
1900         return 1;
1901 }
1902
1903 int ext4_ext_remove_space(struct inode *inode, unsigned long start)
1904 {
1905         struct super_block *sb = inode->i_sb;
1906         int depth = ext_depth(inode);
1907         struct ext4_ext_path *path;
1908         handle_t *handle;
1909         int i = 0, err = 0;
1910
1911         ext_debug("truncate since %lu\n", start);
1912
1913         /* probably first extent we're gonna free will be last in block */
1914         handle = ext4_journal_start(inode, depth + 1);
1915         if (IS_ERR(handle))
1916                 return PTR_ERR(handle);
1917
1918         ext4_ext_invalidate_cache(inode);
1919
1920         /*
1921          * We start scanning from right side, freeing all the blocks
1922          * after i_size and walking into the tree depth-wise.
1923          */
1924         path = kzalloc(sizeof(struct ext4_ext_path) * (depth + 1), GFP_KERNEL);
1925         if (path == NULL) {
1926                 ext4_journal_stop(handle);
1927                 return -ENOMEM;
1928         }
1929         path[0].p_hdr = ext_inode_hdr(inode);
1930         if (ext4_ext_check_header(inode, path[0].p_hdr, depth)) {
1931                 err = -EIO;
1932                 goto out;
1933         }
1934         path[0].p_depth = depth;
1935
1936         while (i >= 0 && err == 0) {
1937                 if (i == depth) {
1938                         /* this is leaf block */
1939                         err = ext4_ext_rm_leaf(handle, inode, path, start);
1940                         /* root level has p_bh == NULL, brelse() eats this */
1941                         brelse(path[i].p_bh);
1942                         path[i].p_bh = NULL;
1943                         i--;
1944                         continue;
1945                 }
1946
1947                 /* this is index block */
1948                 if (!path[i].p_hdr) {
1949                         ext_debug("initialize header\n");
1950                         path[i].p_hdr = ext_block_hdr(path[i].p_bh);
1951                 }
1952
1953                 if (!path[i].p_idx) {
1954                         /* this level hasn't been touched yet */
1955                         path[i].p_idx = EXT_LAST_INDEX(path[i].p_hdr);
1956                         path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries)+1;
1957                         ext_debug("init index ptr: hdr 0x%p, num %d\n",
1958                                   path[i].p_hdr,
1959                                   le16_to_cpu(path[i].p_hdr->eh_entries));
1960                 } else {
1961                         /* we were already here, see at next index */
1962                         path[i].p_idx--;
1963                 }
1964
1965                 ext_debug("level %d - index, first 0x%p, cur 0x%p\n",
1966                                 i, EXT_FIRST_INDEX(path[i].p_hdr),
1967                                 path[i].p_idx);
1968                 if (ext4_ext_more_to_rm(path + i)) {
1969                         struct buffer_head *bh;
1970                         /* go to the next level */
1971                         ext_debug("move to level %d (block %llu)\n",
1972                                   i + 1, idx_pblock(path[i].p_idx));
1973                         memset(path + i + 1, 0, sizeof(*path));
1974                         bh = sb_bread(sb, idx_pblock(path[i].p_idx));
1975                         if (!bh) {
1976                                 /* should we reset i_size? */
1977                                 err = -EIO;
1978                                 break;
1979                         }
1980                         if (WARN_ON(i + 1 > depth)) {
1981                                 err = -EIO;
1982                                 break;
1983                         }
1984                         if (ext4_ext_check_header(inode, ext_block_hdr(bh),
1985                                                         depth - i - 1)) {
1986                                 err = -EIO;
1987                                 break;
1988                         }
1989                         path[i + 1].p_bh = bh;
1990
1991                         /* save actual number of indexes since this
1992                          * number is changed at the next iteration */
1993                         path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries);
1994                         i++;
1995                 } else {
1996                         /* we finished processing this index, go up */
1997                         if (path[i].p_hdr->eh_entries == 0 && i > 0) {
1998                                 /* index is empty, remove it;
1999                                  * handle must be already prepared by the
2000                                  * truncatei_leaf() */
2001                                 err = ext4_ext_rm_idx(handle, inode, path + i);
2002                         }
2003                         /* root level has p_bh == NULL, brelse() eats this */
2004                         brelse(path[i].p_bh);
2005                         path[i].p_bh = NULL;
2006                         i--;
2007                         ext_debug("return to level %d\n", i);
2008                 }
2009         }
2010
2011         /* TODO: flexible tree reduction should be here */
2012         if (path->p_hdr->eh_entries == 0) {
2013                 /*
2014                  * truncate to zero freed all the tree,
2015                  * so we need to correct eh_depth
2016                  */
2017                 err = ext4_ext_get_access(handle, inode, path);
2018                 if (err == 0) {
2019                         ext_inode_hdr(inode)->eh_depth = 0;
2020                         ext_inode_hdr(inode)->eh_max =
2021                                 cpu_to_le16(ext4_ext_space_root(inode));
2022                         err = ext4_ext_dirty(handle, inode, path);
2023                 }
2024         }
2025 out:
2026         ext4_ext_tree_changed(inode);
2027         ext4_ext_drop_refs(path);
2028         kfree(path);
2029         ext4_journal_stop(handle);
2030
2031         return err;
2032 }
2033
2034 /*
2035  * called at mount time
2036  */
2037 void ext4_ext_init(struct super_block *sb)
2038 {
2039         /*
2040          * possible initialization would be here
2041          */
2042
2043         if (test_opt(sb, EXTENTS)) {
2044                 printk("EXT4-fs: file extents enabled");
2045 #ifdef AGGRESSIVE_TEST
2046                 printk(", aggressive tests");
2047 #endif
2048 #ifdef CHECK_BINSEARCH
2049                 printk(", check binsearch");
2050 #endif
2051 #ifdef EXTENTS_STATS
2052                 printk(", stats");
2053 #endif
2054                 printk("\n");
2055 #ifdef EXTENTS_STATS
2056                 spin_lock_init(&EXT4_SB(sb)->s_ext_stats_lock);
2057                 EXT4_SB(sb)->s_ext_min = 1 << 30;
2058                 EXT4_SB(sb)->s_ext_max = 0;
2059 #endif
2060         }
2061 }
2062
2063 /*
2064  * called at umount time
2065  */
2066 void ext4_ext_release(struct super_block *sb)
2067 {
2068         if (!test_opt(sb, EXTENTS))
2069                 return;
2070
2071 #ifdef EXTENTS_STATS
2072         if (EXT4_SB(sb)->s_ext_blocks && EXT4_SB(sb)->s_ext_extents) {
2073                 struct ext4_sb_info *sbi = EXT4_SB(sb);
2074                 printk(KERN_ERR "EXT4-fs: %lu blocks in %lu extents (%lu ave)\n",
2075                         sbi->s_ext_blocks, sbi->s_ext_extents,
2076                         sbi->s_ext_blocks / sbi->s_ext_extents);
2077                 printk(KERN_ERR "EXT4-fs: extents: %lu min, %lu max, max depth %lu\n",
2078                         sbi->s_ext_min, sbi->s_ext_max, sbi->s_depth_max);
2079         }
2080 #endif
2081 }
2082
2083 /*
2084  * This function is called by ext4_ext_get_blocks() if someone tries to write
2085  * to an uninitialized extent. It may result in splitting the uninitialized
2086  * extent into multiple extents (upto three - one initialized and two
2087  * uninitialized).
2088  * There are three possibilities:
2089  *   a> There is no split required: Entire extent should be initialized
2090  *   b> Splits in two extents: Write is happening at either end of the extent
2091  *   c> Splits in three extents: Somone is writing in middle of the extent
2092  */
2093 int ext4_ext_convert_to_initialized(handle_t *handle, struct inode *inode,
2094                                         struct ext4_ext_path *path,
2095                                         ext4_fsblk_t iblock,
2096                                         unsigned long max_blocks)
2097 {
2098         struct ext4_extent *ex, newex;
2099         struct ext4_extent *ex1 = NULL;
2100         struct ext4_extent *ex2 = NULL;
2101         struct ext4_extent *ex3 = NULL;
2102         struct ext4_extent_header *eh;
2103         unsigned int allocated, ee_block, ee_len, depth;
2104         ext4_fsblk_t newblock;
2105         int err = 0;
2106         int ret = 0;
2107
2108         depth = ext_depth(inode);
2109         eh = path[depth].p_hdr;
2110         ex = path[depth].p_ext;
2111         ee_block = le32_to_cpu(ex->ee_block);
2112         ee_len = ext4_ext_get_actual_len(ex);
2113         allocated = ee_len - (iblock - ee_block);
2114         newblock = iblock - ee_block + ext_pblock(ex);
2115         ex2 = ex;
2116
2117         /* ex1: ee_block to iblock - 1 : uninitialized */
2118         if (iblock > ee_block) {
2119                 ex1 = ex;
2120                 ex1->ee_len = cpu_to_le16(iblock - ee_block);
2121                 ext4_ext_mark_uninitialized(ex1);
2122                 ex2 = &newex;
2123         }
2124         /*
2125          * for sanity, update the length of the ex2 extent before
2126          * we insert ex3, if ex1 is NULL. This is to avoid temporary
2127          * overlap of blocks.
2128          */
2129         if (!ex1 && allocated > max_blocks)
2130                 ex2->ee_len = cpu_to_le16(max_blocks);
2131         /* ex3: to ee_block + ee_len : uninitialised */
2132         if (allocated > max_blocks) {
2133                 unsigned int newdepth;
2134                 ex3 = &newex;
2135                 ex3->ee_block = cpu_to_le32(iblock + max_blocks);
2136                 ext4_ext_store_pblock(ex3, newblock + max_blocks);
2137                 ex3->ee_len = cpu_to_le16(allocated - max_blocks);
2138                 ext4_ext_mark_uninitialized(ex3);
2139                 err = ext4_ext_insert_extent(handle, inode, path, ex3);
2140                 if (err)
2141                         goto out;
2142                 /*
2143                  * The depth, and hence eh & ex might change
2144                  * as part of the insert above.
2145                  */
2146                 newdepth = ext_depth(inode);
2147                 if (newdepth != depth) {
2148                         depth = newdepth;
2149                         path = ext4_ext_find_extent(inode, iblock, NULL);
2150                         if (IS_ERR(path)) {
2151                                 err = PTR_ERR(path);
2152                                 path = NULL;
2153                                 goto out;
2154                         }
2155                         eh = path[depth].p_hdr;
2156                         ex = path[depth].p_ext;
2157                         if (ex2 != &newex)
2158                                 ex2 = ex;
2159                 }
2160                 allocated = max_blocks;
2161         }
2162         /*
2163          * If there was a change of depth as part of the
2164          * insertion of ex3 above, we need to update the length
2165          * of the ex1 extent again here
2166          */
2167         if (ex1 && ex1 != ex) {
2168                 ex1 = ex;
2169                 ex1->ee_len = cpu_to_le16(iblock - ee_block);
2170                 ext4_ext_mark_uninitialized(ex1);
2171                 ex2 = &newex;
2172         }
2173         /* ex2: iblock to iblock + maxblocks-1 : initialised */
2174         ex2->ee_block = cpu_to_le32(iblock);
2175         ex2->ee_start = cpu_to_le32(newblock);
2176         ext4_ext_store_pblock(ex2, newblock);
2177         ex2->ee_len = cpu_to_le16(allocated);
2178         if (ex2 != ex)
2179                 goto insert;
2180         err = ext4_ext_get_access(handle, inode, path + depth);
2181         if (err)
2182                 goto out;
2183         /*
2184          * New (initialized) extent starts from the first block
2185          * in the current extent. i.e., ex2 == ex
2186          * We have to see if it can be merged with the extent
2187          * on the left.
2188          */
2189         if (ex2 > EXT_FIRST_EXTENT(eh)) {
2190                 /*
2191                  * To merge left, pass "ex2 - 1" to try_to_merge(),
2192                  * since it merges towards right _only_.
2193                  */
2194                 ret = ext4_ext_try_to_merge(inode, path, ex2 - 1);
2195                 if (ret) {
2196                         err = ext4_ext_correct_indexes(handle, inode, path);
2197                         if (err)
2198                                 goto out;
2199                         depth = ext_depth(inode);
2200                         ex2--;
2201                 }
2202         }
2203         /*
2204          * Try to Merge towards right. This might be required
2205          * only when the whole extent is being written to.
2206          * i.e. ex2 == ex and ex3 == NULL.
2207          */
2208         if (!ex3) {
2209                 ret = ext4_ext_try_to_merge(inode, path, ex2);
2210                 if (ret) {
2211                         err = ext4_ext_correct_indexes(handle, inode, path);
2212                         if (err)
2213                                 goto out;
2214                 }
2215         }
2216         /* Mark modified extent as dirty */
2217         err = ext4_ext_dirty(handle, inode, path + depth);
2218         goto out;
2219 insert:
2220         err = ext4_ext_insert_extent(handle, inode, path, &newex);
2221 out:
2222         return err ? err : allocated;
2223 }
2224
2225 int ext4_ext_get_blocks(handle_t *handle, struct inode *inode,
2226                         ext4_fsblk_t iblock,
2227                         unsigned long max_blocks, struct buffer_head *bh_result,
2228                         int create, int extend_disksize)
2229 {
2230         struct ext4_ext_path *path = NULL;
2231         struct ext4_extent_header *eh;
2232         struct ext4_extent newex, *ex;
2233         ext4_fsblk_t goal, newblock;
2234         int err = 0, depth, ret;
2235         unsigned long allocated = 0;
2236
2237         __clear_bit(BH_New, &bh_result->b_state);
2238         ext_debug("blocks %d/%lu requested for inode %u\n", (int) iblock,
2239                         max_blocks, (unsigned) inode->i_ino);
2240         mutex_lock(&EXT4_I(inode)->truncate_mutex);
2241
2242         /* check in cache */
2243         goal = ext4_ext_in_cache(inode, iblock, &newex);
2244         if (goal) {
2245                 if (goal == EXT4_EXT_CACHE_GAP) {
2246                         if (!create) {
2247                                 /*
2248                                  * block isn't allocated yet and
2249                                  * user doesn't want to allocate it
2250                                  */
2251                                 goto out2;
2252                         }
2253                         /* we should allocate requested block */
2254                 } else if (goal == EXT4_EXT_CACHE_EXTENT) {
2255                         /* block is already allocated */
2256                         newblock = iblock
2257                                    - le32_to_cpu(newex.ee_block)
2258                                    + ext_pblock(&newex);
2259                         /* number of remaining blocks in the extent */
2260                         allocated = le16_to_cpu(newex.ee_len) -
2261                                         (iblock - le32_to_cpu(newex.ee_block));
2262                         goto out;
2263                 } else {
2264                         BUG();
2265                 }
2266         }
2267
2268         /* find extent for this block */
2269         path = ext4_ext_find_extent(inode, iblock, NULL);
2270         if (IS_ERR(path)) {
2271                 err = PTR_ERR(path);
2272                 path = NULL;
2273                 goto out2;
2274         }
2275
2276         depth = ext_depth(inode);
2277
2278         /*
2279          * consistent leaf must not be empty;
2280          * this situation is possible, though, _during_ tree modification;
2281          * this is why assert can't be put in ext4_ext_find_extent()
2282          */
2283         BUG_ON(path[depth].p_ext == NULL && depth != 0);
2284         eh = path[depth].p_hdr;
2285
2286         ex = path[depth].p_ext;
2287         if (ex) {
2288                 unsigned long ee_block = le32_to_cpu(ex->ee_block);
2289                 ext4_fsblk_t ee_start = ext_pblock(ex);
2290                 unsigned short ee_len;
2291
2292                 /*
2293                  * Uninitialized extents are treated as holes, except that
2294                  * we split out initialized portions during a write.
2295                  */
2296                 ee_len = ext4_ext_get_actual_len(ex);
2297                 /* if found extent covers block, simply return it */
2298                 if (iblock >= ee_block && iblock < ee_block + ee_len) {
2299                         newblock = iblock - ee_block + ee_start;
2300                         /* number of remaining blocks in the extent */
2301                         allocated = ee_len - (iblock - ee_block);
2302                         ext_debug("%d fit into %lu:%d -> %llu\n", (int) iblock,
2303                                         ee_block, ee_len, newblock);
2304
2305                         /* Do not put uninitialized extent in the cache */
2306                         if (!ext4_ext_is_uninitialized(ex)) {
2307                                 ext4_ext_put_in_cache(inode, ee_block,
2308                                                         ee_len, ee_start,
2309                                                         EXT4_EXT_CACHE_EXTENT);
2310                                 goto out;
2311                         }
2312                         if (create == EXT4_CREATE_UNINITIALIZED_EXT)
2313                                 goto out;
2314                         if (!create)
2315                                 goto out2;
2316
2317                         ret = ext4_ext_convert_to_initialized(handle, inode,
2318                                                                 path, iblock,
2319                                                                 max_blocks);
2320                         if (ret <= 0)
2321                                 goto out2;
2322                         else
2323                                 allocated = ret;
2324                         goto outnew;
2325                 }
2326         }
2327
2328         /*
2329          * requested block isn't allocated yet;
2330          * we couldn't try to create block if create flag is zero
2331          */
2332         if (!create) {
2333                 /*
2334                  * put just found gap into cache to speed up
2335                  * subsequent requests
2336                  */
2337                 ext4_ext_put_gap_in_cache(inode, path, iblock);
2338                 goto out2;
2339         }
2340         /*
2341          * Okay, we need to do block allocation.  Lazily initialize the block
2342          * allocation info here if necessary.
2343          */
2344         if (S_ISREG(inode->i_mode) && (!EXT4_I(inode)->i_block_alloc_info))
2345                 ext4_init_block_alloc_info(inode);
2346
2347         /* allocate new block */
2348         goal = ext4_ext_find_goal(inode, path, iblock);
2349
2350         /*
2351          * See if request is beyond maximum number of blocks we can have in
2352          * a single extent. For an initialized extent this limit is
2353          * EXT_INIT_MAX_LEN and for an uninitialized extent this limit is
2354          * EXT_UNINIT_MAX_LEN.
2355          */
2356         if (max_blocks > EXT_INIT_MAX_LEN &&
2357             create != EXT4_CREATE_UNINITIALIZED_EXT)
2358                 max_blocks = EXT_INIT_MAX_LEN;
2359         else if (max_blocks > EXT_UNINIT_MAX_LEN &&
2360                  create == EXT4_CREATE_UNINITIALIZED_EXT)
2361                 max_blocks = EXT_UNINIT_MAX_LEN;
2362
2363         /* Check if we can really insert (iblock)::(iblock+max_blocks) extent */
2364         newex.ee_block = cpu_to_le32(iblock);
2365         newex.ee_len = cpu_to_le16(max_blocks);
2366         err = ext4_ext_check_overlap(inode, &newex, path);
2367         if (err)
2368                 allocated = le16_to_cpu(newex.ee_len);
2369         else
2370                 allocated = max_blocks;
2371         newblock = ext4_new_blocks(handle, inode, goal, &allocated, &err);
2372         if (!newblock)
2373                 goto out2;
2374         ext_debug("allocate new block: goal %llu, found %llu/%lu\n",
2375                         goal, newblock, allocated);
2376
2377         /* try to insert new extent into found leaf and return */
2378         ext4_ext_store_pblock(&newex, newblock);
2379         newex.ee_len = cpu_to_le16(allocated);
2380         if (create == EXT4_CREATE_UNINITIALIZED_EXT)  /* Mark uninitialized */
2381                 ext4_ext_mark_uninitialized(&newex);
2382         err = ext4_ext_insert_extent(handle, inode, path, &newex);
2383         if (err) {
2384                 /* free data blocks we just allocated */
2385                 ext4_free_blocks(handle, inode, ext_pblock(&newex),
2386                                         le16_to_cpu(newex.ee_len));
2387                 goto out2;
2388         }
2389
2390         if (extend_disksize && inode->i_size > EXT4_I(inode)->i_disksize)
2391                 EXT4_I(inode)->i_disksize = inode->i_size;
2392
2393         /* previous routine could use block we allocated */
2394         newblock = ext_pblock(&newex);
2395 outnew:
2396         __set_bit(BH_New, &bh_result->b_state);
2397
2398         /* Cache only when it is _not_ an uninitialized extent */
2399         if (create != EXT4_CREATE_UNINITIALIZED_EXT)
2400                 ext4_ext_put_in_cache(inode, iblock, allocated, newblock,
2401                                                 EXT4_EXT_CACHE_EXTENT);
2402 out:
2403         if (allocated > max_blocks)
2404                 allocated = max_blocks;
2405         ext4_ext_show_leaf(inode, path);
2406         __set_bit(BH_Mapped, &bh_result->b_state);
2407         bh_result->b_bdev = inode->i_sb->s_bdev;
2408         bh_result->b_blocknr = newblock;
2409 out2:
2410         if (path) {
2411                 ext4_ext_drop_refs(path);
2412                 kfree(path);
2413         }
2414         mutex_unlock(&EXT4_I(inode)->truncate_mutex);
2415
2416         return err ? err : allocated;
2417 }
2418
2419 void ext4_ext_truncate(struct inode * inode, struct page *page)
2420 {
2421         struct address_space *mapping = inode->i_mapping;
2422         struct super_block *sb = inode->i_sb;
2423         unsigned long last_block;
2424         handle_t *handle;
2425         int err = 0;
2426
2427         /*
2428          * probably first extent we're gonna free will be last in block
2429          */
2430         err = ext4_writepage_trans_blocks(inode) + 3;
2431         handle = ext4_journal_start(inode, err);
2432         if (IS_ERR(handle)) {
2433                 if (page) {
2434                         clear_highpage(page);
2435                         flush_dcache_page(page);
2436                         unlock_page(page);
2437                         page_cache_release(page);
2438                 }
2439                 return;
2440         }
2441
2442         if (page)
2443                 ext4_block_truncate_page(handle, page, mapping, inode->i_size);
2444
2445         mutex_lock(&EXT4_I(inode)->truncate_mutex);
2446         ext4_ext_invalidate_cache(inode);
2447
2448         /*
2449          * TODO: optimization is possible here.
2450          * Probably we need not scan at all,
2451          * because page truncation is enough.
2452          */
2453         if (ext4_orphan_add(handle, inode))
2454                 goto out_stop;
2455
2456         /* we have to know where to truncate from in crash case */
2457         EXT4_I(inode)->i_disksize = inode->i_size;
2458         ext4_mark_inode_dirty(handle, inode);
2459
2460         last_block = (inode->i_size + sb->s_blocksize - 1)
2461                         >> EXT4_BLOCK_SIZE_BITS(sb);
2462         err = ext4_ext_remove_space(inode, last_block);
2463
2464         /* In a multi-transaction truncate, we only make the final
2465          * transaction synchronous.
2466          */
2467         if (IS_SYNC(inode))
2468                 handle->h_sync = 1;
2469
2470 out_stop:
2471         /*
2472          * If this was a simple ftruncate() and the file will remain alive,
2473          * then we need to clear up the orphan record which we created above.
2474          * However, if this was a real unlink then we were called by
2475          * ext4_delete_inode(), and we allow that function to clean up the
2476          * orphan info for us.
2477          */
2478         if (inode->i_nlink)
2479                 ext4_orphan_del(handle, inode);
2480
2481         mutex_unlock(&EXT4_I(inode)->truncate_mutex);
2482         ext4_journal_stop(handle);
2483 }
2484
2485 /*
2486  * ext4_ext_writepage_trans_blocks:
2487  * calculate max number of blocks we could modify
2488  * in order to allocate new block for an inode
2489  */
2490 int ext4_ext_writepage_trans_blocks(struct inode *inode, int num)
2491 {
2492         int needed;
2493
2494         needed = ext4_ext_calc_credits_for_insert(inode, NULL);
2495
2496         /* caller wants to allocate num blocks, but note it includes sb */
2497         needed = needed * num - (num - 1);
2498
2499 #ifdef CONFIG_QUOTA
2500         needed += 2 * EXT4_QUOTA_TRANS_BLOCKS(inode->i_sb);
2501 #endif
2502
2503         return needed;
2504 }
2505
2506 /*
2507  * preallocate space for a file. This implements ext4's fallocate inode
2508  * operation, which gets called from sys_fallocate system call.
2509  * For block-mapped files, posix_fallocate should fall back to the method
2510  * of writing zeroes to the required new blocks (the same behavior which is
2511  * expected for file systems which do not support fallocate() system call).
2512  */
2513 long ext4_fallocate(struct inode *inode, int mode, loff_t offset, loff_t len)
2514 {
2515         handle_t *handle;
2516         ext4_fsblk_t block, max_blocks;
2517         ext4_fsblk_t nblocks = 0;
2518         int ret = 0;
2519         int ret2 = 0;
2520         int retries = 0;
2521         struct buffer_head map_bh;
2522         unsigned int credits, blkbits = inode->i_blkbits;
2523
2524         /*
2525          * currently supporting (pre)allocate mode for extent-based
2526          * files _only_
2527          */
2528         if (!(EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL))
2529                 return -EOPNOTSUPP;
2530
2531         /* preallocation to directories is currently not supported */
2532         if (S_ISDIR(inode->i_mode))
2533                 return -ENODEV;
2534
2535         block = offset >> blkbits;
2536         max_blocks = (EXT4_BLOCK_ALIGN(len + offset, blkbits) >> blkbits)
2537                         - block;
2538
2539         /*
2540          * credits to insert 1 extent into extent tree + buffers to be able to
2541          * modify 1 super block, 1 block bitmap and 1 group descriptor.
2542          */
2543         credits = EXT4_DATA_TRANS_BLOCKS(inode->i_sb) + 3;
2544 retry:
2545         while (ret >= 0 && ret < max_blocks) {
2546                 block = block + ret;
2547                 max_blocks = max_blocks - ret;
2548                 handle = ext4_journal_start(inode, credits);
2549                 if (IS_ERR(handle)) {
2550                         ret = PTR_ERR(handle);
2551                         break;
2552                 }
2553
2554                 ret = ext4_ext_get_blocks(handle, inode, block,
2555                                           max_blocks, &map_bh,
2556                                           EXT4_CREATE_UNINITIALIZED_EXT, 0);
2557                 WARN_ON(!ret);
2558                 if (!ret) {
2559                         ext4_error(inode->i_sb, "ext4_fallocate",
2560                                    "ext4_ext_get_blocks returned 0! inode#%lu"
2561                                    ", block=%llu, max_blocks=%llu",
2562                                    inode->i_ino, block, max_blocks);
2563                         ret = -EIO;
2564                         ext4_mark_inode_dirty(handle, inode);
2565                         ret2 = ext4_journal_stop(handle);
2566                         break;
2567                 }
2568                 if (ret > 0) {
2569                         /* check wrap through sign-bit/zero here */
2570                         if ((block + ret) < 0 || (block + ret) < block) {
2571                                 ret = -EIO;
2572                                 ext4_mark_inode_dirty(handle, inode);
2573                                 ret2 = ext4_journal_stop(handle);
2574                                 break;
2575                         }
2576                         if (buffer_new(&map_bh) && ((block + ret) >
2577                             (EXT4_BLOCK_ALIGN(i_size_read(inode), blkbits)
2578                             >> blkbits)))
2579                                         nblocks = nblocks + ret;
2580                 }
2581
2582                 /* Update ctime if new blocks get allocated */
2583                 if (nblocks) {
2584                         struct timespec now;
2585
2586                         now = current_fs_time(inode->i_sb);
2587                         if (!timespec_equal(&inode->i_ctime, &now))
2588                                 inode->i_ctime = now;
2589                 }
2590
2591                 ext4_mark_inode_dirty(handle, inode);
2592                 ret2 = ext4_journal_stop(handle);
2593                 if (ret2)
2594                         break;
2595         }
2596
2597         if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
2598                 goto retry;
2599
2600         /*
2601          * Time to update the file size.
2602          * Update only when preallocation was requested beyond the file size.
2603          */
2604         if (!(mode & FALLOC_FL_KEEP_SIZE) &&
2605             (offset + len) > i_size_read(inode)) {
2606                 if (ret > 0) {
2607                         /*
2608                          * if no error, we assume preallocation succeeded
2609                          * completely
2610                          */
2611                         mutex_lock(&inode->i_mutex);
2612                         i_size_write(inode, offset + len);
2613                         EXT4_I(inode)->i_disksize = i_size_read(inode);
2614                         mutex_unlock(&inode->i_mutex);
2615                 } else if (ret < 0 && nblocks) {
2616                         /* Handle partial allocation scenario */
2617                         loff_t newsize;
2618
2619                         mutex_lock(&inode->i_mutex);
2620                         newsize  = (nblocks << blkbits) + i_size_read(inode);
2621                         i_size_write(inode, EXT4_BLOCK_ALIGN(newsize, blkbits));
2622                         EXT4_I(inode)->i_disksize = i_size_read(inode);
2623                         mutex_unlock(&inode->i_mutex);
2624                 }
2625         }
2626
2627         return ret > 0 ? ret2 : ret;
2628 }