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