ext4: fix fdatasync(2) after extent manipulation operations
[pandora-kernel.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/jbd2.h>
36 #include <linux/highuid.h>
37 #include <linux/pagemap.h>
38 #include <linux/quotaops.h>
39 #include <linux/string.h>
40 #include <linux/slab.h>
41 #include <linux/falloc.h>
42 #include <asm/uaccess.h>
43 #include <linux/fiemap.h>
44 #include "ext4_jbd2.h"
45
46 #include <trace/events/ext4.h>
47
48 /*
49  * used by extent splitting.
50  */
51 #define EXT4_EXT_MAY_ZEROOUT    0x1  /* safe to zeroout if split fails \
52                                         due to ENOSPC */
53 #define EXT4_EXT_MARK_UNINIT1   0x2  /* mark first half uninitialized */
54 #define EXT4_EXT_MARK_UNINIT2   0x4  /* mark second half uninitialized */
55
56 #define EXT4_EXT_DATA_VALID1    0x8  /* first half contains valid data */
57 #define EXT4_EXT_DATA_VALID2    0x10 /* second half contains valid data */
58
59 static int ext4_split_extent(handle_t *handle,
60                                 struct inode *inode,
61                                 struct ext4_ext_path *path,
62                                 struct ext4_map_blocks *map,
63                                 int split_flag,
64                                 int flags);
65
66 static int ext4_split_extent_at(handle_t *handle,
67                              struct inode *inode,
68                              struct ext4_ext_path *path,
69                              ext4_lblk_t split,
70                              int split_flag,
71                              int flags);
72
73 static int ext4_ext_truncate_extend_restart(handle_t *handle,
74                                             struct inode *inode,
75                                             int needed)
76 {
77         int err;
78
79         if (!ext4_handle_valid(handle))
80                 return 0;
81         if (handle->h_buffer_credits > needed)
82                 return 0;
83         err = ext4_journal_extend(handle, needed);
84         if (err <= 0)
85                 return err;
86         err = ext4_truncate_restart_trans(handle, inode, needed);
87         if (err == 0)
88                 err = -EAGAIN;
89
90         return err;
91 }
92
93 /*
94  * could return:
95  *  - EROFS
96  *  - ENOMEM
97  */
98 static int ext4_ext_get_access(handle_t *handle, struct inode *inode,
99                                 struct ext4_ext_path *path)
100 {
101         if (path->p_bh) {
102                 /* path points to block */
103                 return ext4_journal_get_write_access(handle, path->p_bh);
104         }
105         /* path points to leaf/index in inode body */
106         /* we use in-core data, no need to protect them */
107         return 0;
108 }
109
110 /*
111  * could return:
112  *  - EROFS
113  *  - ENOMEM
114  *  - EIO
115  */
116 #define ext4_ext_dirty(handle, inode, path) \
117                 __ext4_ext_dirty(__func__, __LINE__, (handle), (inode), (path))
118 static int __ext4_ext_dirty(const char *where, unsigned int line,
119                             handle_t *handle, struct inode *inode,
120                             struct ext4_ext_path *path)
121 {
122         int err;
123         if (path->p_bh) {
124                 /* path points to block */
125                 err = __ext4_handle_dirty_metadata(where, line, handle,
126                                                    inode, path->p_bh);
127         } else {
128                 /* path points to leaf/index in inode body */
129                 err = ext4_mark_inode_dirty(handle, inode);
130         }
131         return err;
132 }
133
134 static ext4_fsblk_t ext4_ext_find_goal(struct inode *inode,
135                               struct ext4_ext_path *path,
136                               ext4_lblk_t block)
137 {
138         if (path) {
139                 int depth = path->p_depth;
140                 struct ext4_extent *ex;
141
142                 /*
143                  * Try to predict block placement assuming that we are
144                  * filling in a file which will eventually be
145                  * non-sparse --- i.e., in the case of libbfd writing
146                  * an ELF object sections out-of-order but in a way
147                  * the eventually results in a contiguous object or
148                  * executable file, or some database extending a table
149                  * space file.  However, this is actually somewhat
150                  * non-ideal if we are writing a sparse file such as
151                  * qemu or KVM writing a raw image file that is going
152                  * to stay fairly sparse, since it will end up
153                  * fragmenting the file system's free space.  Maybe we
154                  * should have some hueristics or some way to allow
155                  * userspace to pass a hint to file system,
156                  * especially if the latter case turns out to be
157                  * common.
158                  */
159                 ex = path[depth].p_ext;
160                 if (ex) {
161                         ext4_fsblk_t ext_pblk = ext4_ext_pblock(ex);
162                         ext4_lblk_t ext_block = le32_to_cpu(ex->ee_block);
163
164                         if (block > ext_block)
165                                 return ext_pblk + (block - ext_block);
166                         else
167                                 return ext_pblk - (ext_block - block);
168                 }
169
170                 /* it looks like index is empty;
171                  * try to find starting block from index itself */
172                 if (path[depth].p_bh)
173                         return path[depth].p_bh->b_blocknr;
174         }
175
176         /* OK. use inode's group */
177         return ext4_inode_to_goal_block(inode);
178 }
179
180 /*
181  * Allocation for a meta data block
182  */
183 static ext4_fsblk_t
184 ext4_ext_new_meta_block(handle_t *handle, struct inode *inode,
185                         struct ext4_ext_path *path,
186                         struct ext4_extent *ex, int *err, unsigned int flags)
187 {
188         ext4_fsblk_t goal, newblock;
189
190         goal = ext4_ext_find_goal(inode, path, le32_to_cpu(ex->ee_block));
191         newblock = ext4_new_meta_blocks(handle, inode, goal, flags,
192                                         NULL, err);
193         return newblock;
194 }
195
196 static inline int ext4_ext_space_block(struct inode *inode, int check)
197 {
198         int size;
199
200         size = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
201                         / sizeof(struct ext4_extent);
202 #ifdef AGGRESSIVE_TEST
203         if (!check && size > 6)
204                 size = 6;
205 #endif
206         return size;
207 }
208
209 static inline int ext4_ext_space_block_idx(struct inode *inode, int check)
210 {
211         int size;
212
213         size = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
214                         / sizeof(struct ext4_extent_idx);
215 #ifdef AGGRESSIVE_TEST
216         if (!check && size > 5)
217                 size = 5;
218 #endif
219         return size;
220 }
221
222 static inline int ext4_ext_space_root(struct inode *inode, int check)
223 {
224         int size;
225
226         size = sizeof(EXT4_I(inode)->i_data);
227         size -= sizeof(struct ext4_extent_header);
228         size /= sizeof(struct ext4_extent);
229 #ifdef AGGRESSIVE_TEST
230         if (!check && size > 3)
231                 size = 3;
232 #endif
233         return size;
234 }
235
236 static inline int ext4_ext_space_root_idx(struct inode *inode, int check)
237 {
238         int size;
239
240         size = sizeof(EXT4_I(inode)->i_data);
241         size -= sizeof(struct ext4_extent_header);
242         size /= sizeof(struct ext4_extent_idx);
243 #ifdef AGGRESSIVE_TEST
244         if (!check && size > 4)
245                 size = 4;
246 #endif
247         return size;
248 }
249
250 /*
251  * Calculate the number of metadata blocks needed
252  * to allocate @blocks
253  * Worse case is one block per extent
254  */
255 int ext4_ext_calc_metadata_amount(struct inode *inode, ext4_lblk_t lblock)
256 {
257         struct ext4_inode_info *ei = EXT4_I(inode);
258         int idxs;
259
260         idxs = ((inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
261                 / sizeof(struct ext4_extent_idx));
262
263         /*
264          * If the new delayed allocation block is contiguous with the
265          * previous da block, it can share index blocks with the
266          * previous block, so we only need to allocate a new index
267          * block every idxs leaf blocks.  At ldxs**2 blocks, we need
268          * an additional index block, and at ldxs**3 blocks, yet
269          * another index blocks.
270          */
271         if (ei->i_da_metadata_calc_len &&
272             ei->i_da_metadata_calc_last_lblock+1 == lblock) {
273                 int num = 0;
274
275                 if ((ei->i_da_metadata_calc_len % idxs) == 0)
276                         num++;
277                 if ((ei->i_da_metadata_calc_len % (idxs*idxs)) == 0)
278                         num++;
279                 if ((ei->i_da_metadata_calc_len % (idxs*idxs*idxs)) == 0) {
280                         num++;
281                         ei->i_da_metadata_calc_len = 0;
282                 } else
283                         ei->i_da_metadata_calc_len++;
284                 ei->i_da_metadata_calc_last_lblock++;
285                 return num;
286         }
287
288         /*
289          * In the worst case we need a new set of index blocks at
290          * every level of the inode's extent tree.
291          */
292         ei->i_da_metadata_calc_len = 1;
293         ei->i_da_metadata_calc_last_lblock = lblock;
294         return ext_depth(inode) + 1;
295 }
296
297 static int
298 ext4_ext_max_entries(struct inode *inode, int depth)
299 {
300         int max;
301
302         if (depth == ext_depth(inode)) {
303                 if (depth == 0)
304                         max = ext4_ext_space_root(inode, 1);
305                 else
306                         max = ext4_ext_space_root_idx(inode, 1);
307         } else {
308                 if (depth == 0)
309                         max = ext4_ext_space_block(inode, 1);
310                 else
311                         max = ext4_ext_space_block_idx(inode, 1);
312         }
313
314         return max;
315 }
316
317 static int ext4_valid_extent(struct inode *inode, struct ext4_extent *ext)
318 {
319         ext4_fsblk_t block = ext4_ext_pblock(ext);
320         int len = ext4_ext_get_actual_len(ext);
321         ext4_lblk_t lblock = le32_to_cpu(ext->ee_block);
322
323         /*
324          * We allow neither:
325          *  - zero length
326          *  - overflow/wrap-around
327          */
328         if (lblock + len <= lblock)
329                 return 0;
330         return ext4_data_block_valid(EXT4_SB(inode->i_sb), block, len);
331 }
332
333 static int ext4_valid_extent_idx(struct inode *inode,
334                                 struct ext4_extent_idx *ext_idx)
335 {
336         ext4_fsblk_t block = ext4_idx_pblock(ext_idx);
337
338         return ext4_data_block_valid(EXT4_SB(inode->i_sb), block, 1);
339 }
340
341 static int ext4_valid_extent_entries(struct inode *inode,
342                                 struct ext4_extent_header *eh,
343                                 int depth)
344 {
345         unsigned short entries;
346         if (eh->eh_entries == 0)
347                 return 1;
348
349         entries = le16_to_cpu(eh->eh_entries);
350
351         if (depth == 0) {
352                 /* leaf entries */
353                 struct ext4_extent *ext = EXT_FIRST_EXTENT(eh);
354                 struct ext4_super_block *es = EXT4_SB(inode->i_sb)->s_es;
355                 ext4_fsblk_t pblock = 0;
356                 ext4_lblk_t lblock = 0;
357                 ext4_lblk_t prev = 0;
358                 int len = 0;
359                 while (entries) {
360                         if (!ext4_valid_extent(inode, ext))
361                                 return 0;
362
363                         /* Check for overlapping extents */
364                         lblock = le32_to_cpu(ext->ee_block);
365                         len = ext4_ext_get_actual_len(ext);
366                         if ((lblock <= prev) && prev) {
367                                 pblock = ext4_ext_pblock(ext);
368                                 es->s_last_error_block = cpu_to_le64(pblock);
369                                 return 0;
370                         }
371                         ext++;
372                         entries--;
373                         prev = lblock + len - 1;
374                 }
375         } else {
376                 struct ext4_extent_idx *ext_idx = EXT_FIRST_INDEX(eh);
377                 while (entries) {
378                         if (!ext4_valid_extent_idx(inode, ext_idx))
379                                 return 0;
380                         ext_idx++;
381                         entries--;
382                 }
383         }
384         return 1;
385 }
386
387 static int __ext4_ext_check(const char *function, unsigned int line,
388                             struct inode *inode, struct ext4_extent_header *eh,
389                             int depth)
390 {
391         const char *error_msg;
392         int max = 0;
393
394         if (unlikely(eh->eh_magic != EXT4_EXT_MAGIC)) {
395                 error_msg = "invalid magic";
396                 goto corrupted;
397         }
398         if (unlikely(le16_to_cpu(eh->eh_depth) != depth)) {
399                 error_msg = "unexpected eh_depth";
400                 goto corrupted;
401         }
402         if (unlikely(eh->eh_max == 0)) {
403                 error_msg = "invalid eh_max";
404                 goto corrupted;
405         }
406         max = ext4_ext_max_entries(inode, depth);
407         if (unlikely(le16_to_cpu(eh->eh_max) > max)) {
408                 error_msg = "too large eh_max";
409                 goto corrupted;
410         }
411         if (unlikely(le16_to_cpu(eh->eh_entries) > le16_to_cpu(eh->eh_max))) {
412                 error_msg = "invalid eh_entries";
413                 goto corrupted;
414         }
415         if (!ext4_valid_extent_entries(inode, eh, depth)) {
416                 error_msg = "invalid extent entries";
417                 goto corrupted;
418         }
419         return 0;
420
421 corrupted:
422         ext4_error_inode(inode, function, line, 0,
423                         "bad header/extent: %s - magic %x, "
424                         "entries %u, max %u(%u), depth %u(%u)",
425                         error_msg, le16_to_cpu(eh->eh_magic),
426                         le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max),
427                         max, le16_to_cpu(eh->eh_depth), depth);
428
429         return -EIO;
430 }
431
432 #define ext4_ext_check(inode, eh, depth)        \
433         __ext4_ext_check(__func__, __LINE__, inode, eh, depth)
434
435 int ext4_ext_check_inode(struct inode *inode)
436 {
437         return ext4_ext_check(inode, ext_inode_hdr(inode), ext_depth(inode));
438 }
439
440 #ifdef EXT_DEBUG
441 static void ext4_ext_show_path(struct inode *inode, struct ext4_ext_path *path)
442 {
443         int k, l = path->p_depth;
444
445         ext_debug("path:");
446         for (k = 0; k <= l; k++, path++) {
447                 if (path->p_idx) {
448                   ext_debug("  %d->%llu", le32_to_cpu(path->p_idx->ei_block),
449                             ext4_idx_pblock(path->p_idx));
450                 } else if (path->p_ext) {
451                         ext_debug("  %d:[%d]%d:%llu ",
452                                   le32_to_cpu(path->p_ext->ee_block),
453                                   ext4_ext_is_uninitialized(path->p_ext),
454                                   ext4_ext_get_actual_len(path->p_ext),
455                                   ext4_ext_pblock(path->p_ext));
456                 } else
457                         ext_debug("  []");
458         }
459         ext_debug("\n");
460 }
461
462 static void ext4_ext_show_leaf(struct inode *inode, struct ext4_ext_path *path)
463 {
464         int depth = ext_depth(inode);
465         struct ext4_extent_header *eh;
466         struct ext4_extent *ex;
467         int i;
468
469         if (!path)
470                 return;
471
472         eh = path[depth].p_hdr;
473         ex = EXT_FIRST_EXTENT(eh);
474
475         ext_debug("Displaying leaf extents for inode %lu\n", inode->i_ino);
476
477         for (i = 0; i < le16_to_cpu(eh->eh_entries); i++, ex++) {
478                 ext_debug("%d:[%d]%d:%llu ", le32_to_cpu(ex->ee_block),
479                           ext4_ext_is_uninitialized(ex),
480                           ext4_ext_get_actual_len(ex), ext4_ext_pblock(ex));
481         }
482         ext_debug("\n");
483 }
484
485 static void ext4_ext_show_move(struct inode *inode, struct ext4_ext_path *path,
486                         ext4_fsblk_t newblock, int level)
487 {
488         int depth = ext_depth(inode);
489         struct ext4_extent *ex;
490
491         if (depth != level) {
492                 struct ext4_extent_idx *idx;
493                 idx = path[level].p_idx;
494                 while (idx <= EXT_MAX_INDEX(path[level].p_hdr)) {
495                         ext_debug("%d: move %d:%llu in new index %llu\n", level,
496                                         le32_to_cpu(idx->ei_block),
497                                         ext4_idx_pblock(idx),
498                                         newblock);
499                         idx++;
500                 }
501
502                 return;
503         }
504
505         ex = path[depth].p_ext;
506         while (ex <= EXT_MAX_EXTENT(path[depth].p_hdr)) {
507                 ext_debug("move %d:%llu:[%d]%d in new leaf %llu\n",
508                                 le32_to_cpu(ex->ee_block),
509                                 ext4_ext_pblock(ex),
510                                 ext4_ext_is_uninitialized(ex),
511                                 ext4_ext_get_actual_len(ex),
512                                 newblock);
513                 ex++;
514         }
515 }
516
517 #else
518 #define ext4_ext_show_path(inode, path)
519 #define ext4_ext_show_leaf(inode, path)
520 #define ext4_ext_show_move(inode, path, newblock, level)
521 #endif
522
523 void ext4_ext_drop_refs(struct ext4_ext_path *path)
524 {
525         int depth = path->p_depth;
526         int i;
527
528         for (i = 0; i <= depth; i++, path++)
529                 if (path->p_bh) {
530                         brelse(path->p_bh);
531                         path->p_bh = NULL;
532                 }
533 }
534
535 /*
536  * ext4_ext_binsearch_idx:
537  * binary search for the closest index of the given block
538  * the header must be checked before calling this
539  */
540 static void
541 ext4_ext_binsearch_idx(struct inode *inode,
542                         struct ext4_ext_path *path, ext4_lblk_t block)
543 {
544         struct ext4_extent_header *eh = path->p_hdr;
545         struct ext4_extent_idx *r, *l, *m;
546
547
548         ext_debug("binsearch for %u(idx):  ", block);
549
550         l = EXT_FIRST_INDEX(eh) + 1;
551         r = EXT_LAST_INDEX(eh);
552         while (l <= r) {
553                 m = l + (r - l) / 2;
554                 if (block < le32_to_cpu(m->ei_block))
555                         r = m - 1;
556                 else
557                         l = m + 1;
558                 ext_debug("%p(%u):%p(%u):%p(%u) ", l, le32_to_cpu(l->ei_block),
559                                 m, le32_to_cpu(m->ei_block),
560                                 r, le32_to_cpu(r->ei_block));
561         }
562
563         path->p_idx = l - 1;
564         ext_debug("  -> %d->%lld ", le32_to_cpu(path->p_idx->ei_block),
565                   ext4_idx_pblock(path->p_idx));
566
567 #ifdef CHECK_BINSEARCH
568         {
569                 struct ext4_extent_idx *chix, *ix;
570                 int k;
571
572                 chix = ix = EXT_FIRST_INDEX(eh);
573                 for (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ix++) {
574                   if (k != 0 &&
575                       le32_to_cpu(ix->ei_block) <= le32_to_cpu(ix[-1].ei_block)) {
576                                 printk(KERN_DEBUG "k=%d, ix=0x%p, "
577                                        "first=0x%p\n", k,
578                                        ix, EXT_FIRST_INDEX(eh));
579                                 printk(KERN_DEBUG "%u <= %u\n",
580                                        le32_to_cpu(ix->ei_block),
581                                        le32_to_cpu(ix[-1].ei_block));
582                         }
583                         BUG_ON(k && le32_to_cpu(ix->ei_block)
584                                            <= le32_to_cpu(ix[-1].ei_block));
585                         if (block < le32_to_cpu(ix->ei_block))
586                                 break;
587                         chix = ix;
588                 }
589                 BUG_ON(chix != path->p_idx);
590         }
591 #endif
592
593 }
594
595 /*
596  * ext4_ext_binsearch:
597  * binary search for closest extent of the given block
598  * the header must be checked before calling this
599  */
600 static void
601 ext4_ext_binsearch(struct inode *inode,
602                 struct ext4_ext_path *path, ext4_lblk_t block)
603 {
604         struct ext4_extent_header *eh = path->p_hdr;
605         struct ext4_extent *r, *l, *m;
606
607         if (eh->eh_entries == 0) {
608                 /*
609                  * this leaf is empty:
610                  * we get such a leaf in split/add case
611                  */
612                 return;
613         }
614
615         ext_debug("binsearch for %u:  ", block);
616
617         l = EXT_FIRST_EXTENT(eh) + 1;
618         r = EXT_LAST_EXTENT(eh);
619
620         while (l <= r) {
621                 m = l + (r - l) / 2;
622                 if (block < le32_to_cpu(m->ee_block))
623                         r = m - 1;
624                 else
625                         l = m + 1;
626                 ext_debug("%p(%u):%p(%u):%p(%u) ", l, le32_to_cpu(l->ee_block),
627                                 m, le32_to_cpu(m->ee_block),
628                                 r, le32_to_cpu(r->ee_block));
629         }
630
631         path->p_ext = l - 1;
632         ext_debug("  -> %d:%llu:[%d]%d ",
633                         le32_to_cpu(path->p_ext->ee_block),
634                         ext4_ext_pblock(path->p_ext),
635                         ext4_ext_is_uninitialized(path->p_ext),
636                         ext4_ext_get_actual_len(path->p_ext));
637
638 #ifdef CHECK_BINSEARCH
639         {
640                 struct ext4_extent *chex, *ex;
641                 int k;
642
643                 chex = ex = EXT_FIRST_EXTENT(eh);
644                 for (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ex++) {
645                         BUG_ON(k && le32_to_cpu(ex->ee_block)
646                                           <= le32_to_cpu(ex[-1].ee_block));
647                         if (block < le32_to_cpu(ex->ee_block))
648                                 break;
649                         chex = ex;
650                 }
651                 BUG_ON(chex != path->p_ext);
652         }
653 #endif
654
655 }
656
657 int ext4_ext_tree_init(handle_t *handle, struct inode *inode)
658 {
659         struct ext4_extent_header *eh;
660
661         eh = ext_inode_hdr(inode);
662         eh->eh_depth = 0;
663         eh->eh_entries = 0;
664         eh->eh_magic = EXT4_EXT_MAGIC;
665         eh->eh_max = cpu_to_le16(ext4_ext_space_root(inode, 0));
666         ext4_mark_inode_dirty(handle, inode);
667         ext4_ext_invalidate_cache(inode);
668         return 0;
669 }
670
671 struct ext4_ext_path *
672 ext4_ext_find_extent(struct inode *inode, ext4_lblk_t block,
673                                         struct ext4_ext_path *path)
674 {
675         struct ext4_extent_header *eh;
676         struct buffer_head *bh;
677         short int depth, i, ppos = 0, alloc = 0;
678         int ret;
679
680         eh = ext_inode_hdr(inode);
681         depth = ext_depth(inode);
682
683         /* account possible depth increase */
684         if (!path) {
685                 path = kzalloc(sizeof(struct ext4_ext_path) * (depth + 2),
686                                 GFP_NOFS);
687                 if (!path)
688                         return ERR_PTR(-ENOMEM);
689                 alloc = 1;
690         }
691         path[0].p_hdr = eh;
692         path[0].p_bh = NULL;
693
694         i = depth;
695         /* walk through the tree */
696         while (i) {
697                 int need_to_validate = 0;
698
699                 ext_debug("depth %d: num %d, max %d\n",
700                           ppos, le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
701
702                 ext4_ext_binsearch_idx(inode, path + ppos, block);
703                 path[ppos].p_block = ext4_idx_pblock(path[ppos].p_idx);
704                 path[ppos].p_depth = i;
705                 path[ppos].p_ext = NULL;
706
707                 bh = sb_getblk_gfp(inode->i_sb, path[ppos].p_block,
708                                    __GFP_MOVABLE | GFP_NOFS);
709                 if (unlikely(!bh)) {
710                         ret = -ENOMEM;
711                         goto err;
712                 }
713                 if (!bh_uptodate_or_lock(bh)) {
714                         trace_ext4_ext_load_extent(inode, block,
715                                                 path[ppos].p_block);
716                         ret = bh_submit_read(bh);
717                         if (ret < 0) {
718                                 put_bh(bh);
719                                 goto err;
720                         }
721                         /* validate the extent entries */
722                         need_to_validate = 1;
723                 }
724                 eh = ext_block_hdr(bh);
725                 ppos++;
726                 if (unlikely(ppos > depth)) {
727                         put_bh(bh);
728                         EXT4_ERROR_INODE(inode,
729                                          "ppos %d > depth %d", ppos, depth);
730                         ret = -EIO;
731                         goto err;
732                 }
733                 path[ppos].p_bh = bh;
734                 path[ppos].p_hdr = eh;
735                 i--;
736
737                 ret = need_to_validate ? ext4_ext_check(inode, eh, i) : 0;
738                 if (ret < 0)
739                         goto err;
740         }
741
742         path[ppos].p_depth = i;
743         path[ppos].p_ext = NULL;
744         path[ppos].p_idx = NULL;
745
746         /* find extent */
747         ext4_ext_binsearch(inode, path + ppos, block);
748         /* if not an empty leaf */
749         if (path[ppos].p_ext)
750                 path[ppos].p_block = ext4_ext_pblock(path[ppos].p_ext);
751
752         ext4_ext_show_path(inode, path);
753
754         return path;
755
756 err:
757         ext4_ext_drop_refs(path);
758         if (alloc)
759                 kfree(path);
760         return ERR_PTR(ret);
761 }
762
763 /*
764  * ext4_ext_insert_index:
765  * insert new index [@logical;@ptr] into the block at @curp;
766  * check where to insert: before @curp or after @curp
767  */
768 static int ext4_ext_insert_index(handle_t *handle, struct inode *inode,
769                                  struct ext4_ext_path *curp,
770                                  int logical, ext4_fsblk_t ptr)
771 {
772         struct ext4_extent_idx *ix;
773         int len, err;
774
775         err = ext4_ext_get_access(handle, inode, curp);
776         if (err)
777                 return err;
778
779         if (unlikely(logical == le32_to_cpu(curp->p_idx->ei_block))) {
780                 EXT4_ERROR_INODE(inode,
781                                  "logical %d == ei_block %d!",
782                                  logical, le32_to_cpu(curp->p_idx->ei_block));
783                 return -EIO;
784         }
785
786         if (unlikely(le16_to_cpu(curp->p_hdr->eh_entries)
787                              >= le16_to_cpu(curp->p_hdr->eh_max))) {
788                 EXT4_ERROR_INODE(inode,
789                                  "eh_entries %d >= eh_max %d!",
790                                  le16_to_cpu(curp->p_hdr->eh_entries),
791                                  le16_to_cpu(curp->p_hdr->eh_max));
792                 return -EIO;
793         }
794
795         if (logical > le32_to_cpu(curp->p_idx->ei_block)) {
796                 /* insert after */
797                 ext_debug("insert new index %d after: %llu\n", logical, ptr);
798                 ix = curp->p_idx + 1;
799         } else {
800                 /* insert before */
801                 ext_debug("insert new index %d before: %llu\n", logical, ptr);
802                 ix = curp->p_idx;
803         }
804
805         len = EXT_LAST_INDEX(curp->p_hdr) - ix + 1;
806         BUG_ON(len < 0);
807         if (len > 0) {
808                 ext_debug("insert new index %d: "
809                                 "move %d indices from 0x%p to 0x%p\n",
810                                 logical, len, ix, ix + 1);
811                 memmove(ix + 1, ix, len * sizeof(struct ext4_extent_idx));
812         }
813
814         if (unlikely(ix > EXT_MAX_INDEX(curp->p_hdr))) {
815                 EXT4_ERROR_INODE(inode, "ix > EXT_MAX_INDEX!");
816                 return -EIO;
817         }
818
819         ix->ei_block = cpu_to_le32(logical);
820         ext4_idx_store_pblock(ix, ptr);
821         le16_add_cpu(&curp->p_hdr->eh_entries, 1);
822
823         if (unlikely(ix > EXT_LAST_INDEX(curp->p_hdr))) {
824                 EXT4_ERROR_INODE(inode, "ix > EXT_LAST_INDEX!");
825                 return -EIO;
826         }
827
828         err = ext4_ext_dirty(handle, inode, curp);
829         ext4_std_error(inode->i_sb, err);
830
831         return err;
832 }
833
834 /*
835  * ext4_ext_split:
836  * inserts new subtree into the path, using free index entry
837  * at depth @at:
838  * - allocates all needed blocks (new leaf and all intermediate index blocks)
839  * - makes decision where to split
840  * - moves remaining extents and index entries (right to the split point)
841  *   into the newly allocated blocks
842  * - initializes subtree
843  */
844 static int ext4_ext_split(handle_t *handle, struct inode *inode,
845                           unsigned int flags,
846                           struct ext4_ext_path *path,
847                           struct ext4_extent *newext, int at)
848 {
849         struct buffer_head *bh = NULL;
850         int depth = ext_depth(inode);
851         struct ext4_extent_header *neh;
852         struct ext4_extent_idx *fidx;
853         int i = at, k, m, a;
854         ext4_fsblk_t newblock, oldblock;
855         __le32 border;
856         ext4_fsblk_t *ablocks = NULL; /* array of allocated blocks */
857         int err = 0;
858
859         /* make decision: where to split? */
860         /* FIXME: now decision is simplest: at current extent */
861
862         /* if current leaf will be split, then we should use
863          * border from split point */
864         if (unlikely(path[depth].p_ext > EXT_MAX_EXTENT(path[depth].p_hdr))) {
865                 EXT4_ERROR_INODE(inode, "p_ext > EXT_MAX_EXTENT!");
866                 return -EIO;
867         }
868         if (path[depth].p_ext != EXT_MAX_EXTENT(path[depth].p_hdr)) {
869                 border = path[depth].p_ext[1].ee_block;
870                 ext_debug("leaf will be split."
871                                 " next leaf starts at %d\n",
872                                   le32_to_cpu(border));
873         } else {
874                 border = newext->ee_block;
875                 ext_debug("leaf will be added."
876                                 " next leaf starts at %d\n",
877                                 le32_to_cpu(border));
878         }
879
880         /*
881          * If error occurs, then we break processing
882          * and mark filesystem read-only. index won't
883          * be inserted and tree will be in consistent
884          * state. Next mount will repair buffers too.
885          */
886
887         /*
888          * Get array to track all allocated blocks.
889          * We need this to handle errors and free blocks
890          * upon them.
891          */
892         ablocks = kzalloc(sizeof(ext4_fsblk_t) * depth, GFP_NOFS);
893         if (!ablocks)
894                 return -ENOMEM;
895
896         /* allocate all needed blocks */
897         ext_debug("allocate %d blocks for indexes/leaf\n", depth - at);
898         for (a = 0; a < depth - at; a++) {
899                 newblock = ext4_ext_new_meta_block(handle, inode, path,
900                                                    newext, &err, flags);
901                 if (newblock == 0)
902                         goto cleanup;
903                 ablocks[a] = newblock;
904         }
905
906         /* initialize new leaf */
907         newblock = ablocks[--a];
908         if (unlikely(newblock == 0)) {
909                 EXT4_ERROR_INODE(inode, "newblock == 0!");
910                 err = -EIO;
911                 goto cleanup;
912         }
913         bh = sb_getblk_gfp(inode->i_sb, newblock, __GFP_MOVABLE | GFP_NOFS);
914         if (!bh) {
915                 err = -ENOMEM;
916                 goto cleanup;
917         }
918         lock_buffer(bh);
919
920         err = ext4_journal_get_create_access(handle, bh);
921         if (err)
922                 goto cleanup;
923
924         neh = ext_block_hdr(bh);
925         neh->eh_entries = 0;
926         neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0));
927         neh->eh_magic = EXT4_EXT_MAGIC;
928         neh->eh_depth = 0;
929
930         /* move remainder of path[depth] to the new leaf */
931         if (unlikely(path[depth].p_hdr->eh_entries !=
932                      path[depth].p_hdr->eh_max)) {
933                 EXT4_ERROR_INODE(inode, "eh_entries %d != eh_max %d!",
934                                  path[depth].p_hdr->eh_entries,
935                                  path[depth].p_hdr->eh_max);
936                 err = -EIO;
937                 goto cleanup;
938         }
939         /* start copy from next extent */
940         m = EXT_MAX_EXTENT(path[depth].p_hdr) - path[depth].p_ext++;
941         ext4_ext_show_move(inode, path, newblock, depth);
942         if (m) {
943                 struct ext4_extent *ex;
944                 ex = EXT_FIRST_EXTENT(neh);
945                 memmove(ex, path[depth].p_ext, sizeof(struct ext4_extent) * m);
946                 le16_add_cpu(&neh->eh_entries, m);
947         }
948
949         set_buffer_uptodate(bh);
950         unlock_buffer(bh);
951
952         err = ext4_handle_dirty_metadata(handle, inode, bh);
953         if (err)
954                 goto cleanup;
955         brelse(bh);
956         bh = NULL;
957
958         /* correct old leaf */
959         if (m) {
960                 err = ext4_ext_get_access(handle, inode, path + depth);
961                 if (err)
962                         goto cleanup;
963                 le16_add_cpu(&path[depth].p_hdr->eh_entries, -m);
964                 err = ext4_ext_dirty(handle, inode, path + depth);
965                 if (err)
966                         goto cleanup;
967
968         }
969
970         /* create intermediate indexes */
971         k = depth - at - 1;
972         if (unlikely(k < 0)) {
973                 EXT4_ERROR_INODE(inode, "k %d < 0!", k);
974                 err = -EIO;
975                 goto cleanup;
976         }
977         if (k)
978                 ext_debug("create %d intermediate indices\n", k);
979         /* insert new index into current index block */
980         /* current depth stored in i var */
981         i = depth - 1;
982         while (k--) {
983                 oldblock = newblock;
984                 newblock = ablocks[--a];
985                 bh = sb_getblk(inode->i_sb, newblock);
986                 if (!bh) {
987                         err = -ENOMEM;
988                         goto cleanup;
989                 }
990                 lock_buffer(bh);
991
992                 err = ext4_journal_get_create_access(handle, bh);
993                 if (err)
994                         goto cleanup;
995
996                 neh = ext_block_hdr(bh);
997                 neh->eh_entries = cpu_to_le16(1);
998                 neh->eh_magic = EXT4_EXT_MAGIC;
999                 neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0));
1000                 neh->eh_depth = cpu_to_le16(depth - i);
1001                 fidx = EXT_FIRST_INDEX(neh);
1002                 fidx->ei_block = border;
1003                 ext4_idx_store_pblock(fidx, oldblock);
1004
1005                 ext_debug("int.index at %d (block %llu): %u -> %llu\n",
1006                                 i, newblock, le32_to_cpu(border), oldblock);
1007
1008                 /* move remainder of path[i] to the new index block */
1009                 if (unlikely(EXT_MAX_INDEX(path[i].p_hdr) !=
1010                                         EXT_LAST_INDEX(path[i].p_hdr))) {
1011                         EXT4_ERROR_INODE(inode,
1012                                          "EXT_MAX_INDEX != EXT_LAST_INDEX ee_block %d!",
1013                                          le32_to_cpu(path[i].p_ext->ee_block));
1014                         err = -EIO;
1015                         goto cleanup;
1016                 }
1017                 /* start copy indexes */
1018                 m = EXT_MAX_INDEX(path[i].p_hdr) - path[i].p_idx++;
1019                 ext_debug("cur 0x%p, last 0x%p\n", path[i].p_idx,
1020                                 EXT_MAX_INDEX(path[i].p_hdr));
1021                 ext4_ext_show_move(inode, path, newblock, i);
1022                 if (m) {
1023                         memmove(++fidx, path[i].p_idx,
1024                                 sizeof(struct ext4_extent_idx) * m);
1025                         le16_add_cpu(&neh->eh_entries, m);
1026                 }
1027                 set_buffer_uptodate(bh);
1028                 unlock_buffer(bh);
1029
1030                 err = ext4_handle_dirty_metadata(handle, inode, bh);
1031                 if (err)
1032                         goto cleanup;
1033                 brelse(bh);
1034                 bh = NULL;
1035
1036                 /* correct old index */
1037                 if (m) {
1038                         err = ext4_ext_get_access(handle, inode, path + i);
1039                         if (err)
1040                                 goto cleanup;
1041                         le16_add_cpu(&path[i].p_hdr->eh_entries, -m);
1042                         err = ext4_ext_dirty(handle, inode, path + i);
1043                         if (err)
1044                                 goto cleanup;
1045                 }
1046
1047                 i--;
1048         }
1049
1050         /* insert new index */
1051         err = ext4_ext_insert_index(handle, inode, path + at,
1052                                     le32_to_cpu(border), newblock);
1053
1054 cleanup:
1055         if (bh) {
1056                 if (buffer_locked(bh))
1057                         unlock_buffer(bh);
1058                 brelse(bh);
1059         }
1060
1061         if (err) {
1062                 /* free all allocated blocks in error case */
1063                 for (i = 0; i < depth; i++) {
1064                         if (!ablocks[i])
1065                                 continue;
1066                         ext4_free_blocks(handle, inode, NULL, ablocks[i], 1,
1067                                          EXT4_FREE_BLOCKS_METADATA);
1068                 }
1069         }
1070         kfree(ablocks);
1071
1072         return err;
1073 }
1074
1075 /*
1076  * ext4_ext_grow_indepth:
1077  * implements tree growing procedure:
1078  * - allocates new block
1079  * - moves top-level data (index block or leaf) into the new block
1080  * - initializes new top-level, creating index that points to the
1081  *   just created block
1082  */
1083 static int ext4_ext_grow_indepth(handle_t *handle, struct inode *inode,
1084                                  unsigned int flags,
1085                                  struct ext4_extent *newext)
1086 {
1087         struct ext4_extent_header *neh;
1088         struct buffer_head *bh;
1089         ext4_fsblk_t newblock;
1090         int err = 0;
1091
1092         newblock = ext4_ext_new_meta_block(handle, inode, NULL,
1093                 newext, &err, flags);
1094         if (newblock == 0)
1095                 return err;
1096
1097         bh = sb_getblk_gfp(inode->i_sb, newblock, __GFP_MOVABLE | GFP_NOFS);
1098         if (!bh)
1099                 return -ENOMEM;
1100         lock_buffer(bh);
1101
1102         err = ext4_journal_get_create_access(handle, bh);
1103         if (err) {
1104                 unlock_buffer(bh);
1105                 goto out;
1106         }
1107
1108         /* move top-level index/leaf into new block */
1109         memmove(bh->b_data, EXT4_I(inode)->i_data,
1110                 sizeof(EXT4_I(inode)->i_data));
1111
1112         /* set size of new block */
1113         neh = ext_block_hdr(bh);
1114         /* old root could have indexes or leaves
1115          * so calculate e_max right way */
1116         if (ext_depth(inode))
1117                 neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0));
1118         else
1119                 neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0));
1120         neh->eh_magic = EXT4_EXT_MAGIC;
1121         set_buffer_uptodate(bh);
1122         unlock_buffer(bh);
1123
1124         err = ext4_handle_dirty_metadata(handle, inode, bh);
1125         if (err)
1126                 goto out;
1127
1128         /* Update top-level index: num,max,pointer */
1129         neh = ext_inode_hdr(inode);
1130         neh->eh_entries = cpu_to_le16(1);
1131         ext4_idx_store_pblock(EXT_FIRST_INDEX(neh), newblock);
1132         if (neh->eh_depth == 0) {
1133                 /* Root extent block becomes index block */
1134                 neh->eh_max = cpu_to_le16(ext4_ext_space_root_idx(inode, 0));
1135                 EXT_FIRST_INDEX(neh)->ei_block =
1136                         EXT_FIRST_EXTENT(neh)->ee_block;
1137         }
1138         ext_debug("new root: num %d(%d), lblock %d, ptr %llu\n",
1139                   le16_to_cpu(neh->eh_entries), le16_to_cpu(neh->eh_max),
1140                   le32_to_cpu(EXT_FIRST_INDEX(neh)->ei_block),
1141                   ext4_idx_pblock(EXT_FIRST_INDEX(neh)));
1142
1143         neh->eh_depth = cpu_to_le16(le16_to_cpu(neh->eh_depth) + 1);
1144         ext4_mark_inode_dirty(handle, inode);
1145 out:
1146         brelse(bh);
1147
1148         return err;
1149 }
1150
1151 /*
1152  * ext4_ext_create_new_leaf:
1153  * finds empty index and adds new leaf.
1154  * if no free index is found, then it requests in-depth growing.
1155  */
1156 static int ext4_ext_create_new_leaf(handle_t *handle, struct inode *inode,
1157                                     unsigned int flags,
1158                                     struct ext4_ext_path *path,
1159                                     struct ext4_extent *newext)
1160 {
1161         struct ext4_ext_path *curp;
1162         int depth, i, err = 0;
1163
1164 repeat:
1165         i = depth = ext_depth(inode);
1166
1167         /* walk up to the tree and look for free index entry */
1168         curp = path + depth;
1169         while (i > 0 && !EXT_HAS_FREE_INDEX(curp)) {
1170                 i--;
1171                 curp--;
1172         }
1173
1174         /* we use already allocated block for index block,
1175          * so subsequent data blocks should be contiguous */
1176         if (EXT_HAS_FREE_INDEX(curp)) {
1177                 /* if we found index with free entry, then use that
1178                  * entry: create all needed subtree and add new leaf */
1179                 err = ext4_ext_split(handle, inode, flags, path, newext, i);
1180                 if (err)
1181                         goto out;
1182
1183                 /* refill path */
1184                 ext4_ext_drop_refs(path);
1185                 path = ext4_ext_find_extent(inode,
1186                                     (ext4_lblk_t)le32_to_cpu(newext->ee_block),
1187                                     path);
1188                 if (IS_ERR(path))
1189                         err = PTR_ERR(path);
1190         } else {
1191                 /* tree is full, time to grow in depth */
1192                 err = ext4_ext_grow_indepth(handle, inode, flags, newext);
1193                 if (err)
1194                         goto out;
1195
1196                 /* refill path */
1197                 ext4_ext_drop_refs(path);
1198                 path = ext4_ext_find_extent(inode,
1199                                    (ext4_lblk_t)le32_to_cpu(newext->ee_block),
1200                                     path);
1201                 if (IS_ERR(path)) {
1202                         err = PTR_ERR(path);
1203                         goto out;
1204                 }
1205
1206                 /*
1207                  * only first (depth 0 -> 1) produces free space;
1208                  * in all other cases we have to split the grown tree
1209                  */
1210                 depth = ext_depth(inode);
1211                 if (path[depth].p_hdr->eh_entries == path[depth].p_hdr->eh_max) {
1212                         /* now we need to split */
1213                         goto repeat;
1214                 }
1215         }
1216
1217 out:
1218         return err;
1219 }
1220
1221 /*
1222  * search the closest allocated block to the left for *logical
1223  * and returns it at @logical + it's physical address at @phys
1224  * if *logical is the smallest allocated block, the function
1225  * returns 0 at @phys
1226  * return value contains 0 (success) or error code
1227  */
1228 static int ext4_ext_search_left(struct inode *inode,
1229                                 struct ext4_ext_path *path,
1230                                 ext4_lblk_t *logical, ext4_fsblk_t *phys)
1231 {
1232         struct ext4_extent_idx *ix;
1233         struct ext4_extent *ex;
1234         int depth, ee_len;
1235
1236         if (unlikely(path == NULL)) {
1237                 EXT4_ERROR_INODE(inode, "path == NULL *logical %d!", *logical);
1238                 return -EIO;
1239         }
1240         depth = path->p_depth;
1241         *phys = 0;
1242
1243         if (depth == 0 && path->p_ext == NULL)
1244                 return 0;
1245
1246         /* usually extent in the path covers blocks smaller
1247          * then *logical, but it can be that extent is the
1248          * first one in the file */
1249
1250         ex = path[depth].p_ext;
1251         ee_len = ext4_ext_get_actual_len(ex);
1252         if (*logical < le32_to_cpu(ex->ee_block)) {
1253                 if (unlikely(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex)) {
1254                         EXT4_ERROR_INODE(inode,
1255                                          "EXT_FIRST_EXTENT != ex *logical %d ee_block %d!",
1256                                          *logical, le32_to_cpu(ex->ee_block));
1257                         return -EIO;
1258                 }
1259                 while (--depth >= 0) {
1260                         ix = path[depth].p_idx;
1261                         if (unlikely(ix != EXT_FIRST_INDEX(path[depth].p_hdr))) {
1262                                 EXT4_ERROR_INODE(inode,
1263                                   "ix (%d) != EXT_FIRST_INDEX (%d) (depth %d)!",
1264                                   ix != NULL ? le32_to_cpu(ix->ei_block) : 0,
1265                                   EXT_FIRST_INDEX(path[depth].p_hdr) != NULL ?
1266                 le32_to_cpu(EXT_FIRST_INDEX(path[depth].p_hdr)->ei_block) : 0,
1267                                   depth);
1268                                 return -EIO;
1269                         }
1270                 }
1271                 return 0;
1272         }
1273
1274         if (unlikely(*logical < (le32_to_cpu(ex->ee_block) + ee_len))) {
1275                 EXT4_ERROR_INODE(inode,
1276                                  "logical %d < ee_block %d + ee_len %d!",
1277                                  *logical, le32_to_cpu(ex->ee_block), ee_len);
1278                 return -EIO;
1279         }
1280
1281         *logical = le32_to_cpu(ex->ee_block) + ee_len - 1;
1282         *phys = ext4_ext_pblock(ex) + ee_len - 1;
1283         return 0;
1284 }
1285
1286 /*
1287  * search the closest allocated block to the right for *logical
1288  * and returns it at @logical + it's physical address at @phys
1289  * if *logical is the largest allocated block, the function
1290  * returns 0 at @phys
1291  * return value contains 0 (success) or error code
1292  */
1293 static int ext4_ext_search_right(struct inode *inode,
1294                                  struct ext4_ext_path *path,
1295                                  ext4_lblk_t *logical, ext4_fsblk_t *phys,
1296                                  struct ext4_extent **ret_ex)
1297 {
1298         struct buffer_head *bh = NULL;
1299         struct ext4_extent_header *eh;
1300         struct ext4_extent_idx *ix;
1301         struct ext4_extent *ex;
1302         ext4_fsblk_t block;
1303         int depth;      /* Note, NOT eh_depth; depth from top of tree */
1304         int ee_len;
1305
1306         if (unlikely(path == NULL)) {
1307                 EXT4_ERROR_INODE(inode, "path == NULL *logical %d!", *logical);
1308                 return -EIO;
1309         }
1310         depth = path->p_depth;
1311         *phys = 0;
1312
1313         if (depth == 0 && path->p_ext == NULL)
1314                 return 0;
1315
1316         /* usually extent in the path covers blocks smaller
1317          * then *logical, but it can be that extent is the
1318          * first one in the file */
1319
1320         ex = path[depth].p_ext;
1321         ee_len = ext4_ext_get_actual_len(ex);
1322         if (*logical < le32_to_cpu(ex->ee_block)) {
1323                 if (unlikely(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex)) {
1324                         EXT4_ERROR_INODE(inode,
1325                                          "first_extent(path[%d].p_hdr) != ex",
1326                                          depth);
1327                         return -EIO;
1328                 }
1329                 while (--depth >= 0) {
1330                         ix = path[depth].p_idx;
1331                         if (unlikely(ix != EXT_FIRST_INDEX(path[depth].p_hdr))) {
1332                                 EXT4_ERROR_INODE(inode,
1333                                                  "ix != EXT_FIRST_INDEX *logical %d!",
1334                                                  *logical);
1335                                 return -EIO;
1336                         }
1337                 }
1338                 goto found_extent;
1339         }
1340
1341         if (unlikely(*logical < (le32_to_cpu(ex->ee_block) + ee_len))) {
1342                 EXT4_ERROR_INODE(inode,
1343                                  "logical %d < ee_block %d + ee_len %d!",
1344                                  *logical, le32_to_cpu(ex->ee_block), ee_len);
1345                 return -EIO;
1346         }
1347
1348         if (ex != EXT_LAST_EXTENT(path[depth].p_hdr)) {
1349                 /* next allocated block in this leaf */
1350                 ex++;
1351                 goto found_extent;
1352         }
1353
1354         /* go up and search for index to the right */
1355         while (--depth >= 0) {
1356                 ix = path[depth].p_idx;
1357                 if (ix != EXT_LAST_INDEX(path[depth].p_hdr))
1358                         goto got_index;
1359         }
1360
1361         /* we've gone up to the root and found no index to the right */
1362         return 0;
1363
1364 got_index:
1365         /* we've found index to the right, let's
1366          * follow it and find the closest allocated
1367          * block to the right */
1368         ix++;
1369         block = ext4_idx_pblock(ix);
1370         while (++depth < path->p_depth) {
1371                 bh = sb_bread(inode->i_sb, block);
1372                 if (bh == NULL)
1373                         return -EIO;
1374                 eh = ext_block_hdr(bh);
1375                 /* subtract from p_depth to get proper eh_depth */
1376                 if (ext4_ext_check(inode, eh, path->p_depth - depth)) {
1377                         put_bh(bh);
1378                         return -EIO;
1379                 }
1380                 ix = EXT_FIRST_INDEX(eh);
1381                 block = ext4_idx_pblock(ix);
1382                 put_bh(bh);
1383         }
1384
1385         bh = sb_bread(inode->i_sb, block);
1386         if (bh == NULL)
1387                 return -EIO;
1388         eh = ext_block_hdr(bh);
1389         if (ext4_ext_check(inode, eh, path->p_depth - depth)) {
1390                 put_bh(bh);
1391                 return -EIO;
1392         }
1393         ex = EXT_FIRST_EXTENT(eh);
1394 found_extent:
1395         *logical = le32_to_cpu(ex->ee_block);
1396         *phys = ext4_ext_pblock(ex);
1397         *ret_ex = ex;
1398         if (bh)
1399                 put_bh(bh);
1400         return 0;
1401 }
1402
1403 /*
1404  * ext4_ext_next_allocated_block:
1405  * returns allocated block in subsequent extent or EXT_MAX_BLOCKS.
1406  * NOTE: it considers block number from index entry as
1407  * allocated block. Thus, index entries have to be consistent
1408  * with leaves.
1409  */
1410 static ext4_lblk_t
1411 ext4_ext_next_allocated_block(struct ext4_ext_path *path)
1412 {
1413         int depth;
1414
1415         BUG_ON(path == NULL);
1416         depth = path->p_depth;
1417
1418         if (depth == 0 && path->p_ext == NULL)
1419                 return EXT_MAX_BLOCKS;
1420
1421         while (depth >= 0) {
1422                 if (depth == path->p_depth) {
1423                         /* leaf */
1424                         if (path[depth].p_ext &&
1425                                 path[depth].p_ext !=
1426                                         EXT_LAST_EXTENT(path[depth].p_hdr))
1427                           return le32_to_cpu(path[depth].p_ext[1].ee_block);
1428                 } else {
1429                         /* index */
1430                         if (path[depth].p_idx !=
1431                                         EXT_LAST_INDEX(path[depth].p_hdr))
1432                           return le32_to_cpu(path[depth].p_idx[1].ei_block);
1433                 }
1434                 depth--;
1435         }
1436
1437         return EXT_MAX_BLOCKS;
1438 }
1439
1440 /*
1441  * ext4_ext_next_leaf_block:
1442  * returns first allocated block from next leaf or EXT_MAX_BLOCKS
1443  */
1444 static ext4_lblk_t ext4_ext_next_leaf_block(struct ext4_ext_path *path)
1445 {
1446         int depth;
1447
1448         BUG_ON(path == NULL);
1449         depth = path->p_depth;
1450
1451         /* zero-tree has no leaf blocks at all */
1452         if (depth == 0)
1453                 return EXT_MAX_BLOCKS;
1454
1455         /* go to index block */
1456         depth--;
1457
1458         while (depth >= 0) {
1459                 if (path[depth].p_idx !=
1460                                 EXT_LAST_INDEX(path[depth].p_hdr))
1461                         return (ext4_lblk_t)
1462                                 le32_to_cpu(path[depth].p_idx[1].ei_block);
1463                 depth--;
1464         }
1465
1466         return EXT_MAX_BLOCKS;
1467 }
1468
1469 /*
1470  * ext4_ext_correct_indexes:
1471  * if leaf gets modified and modified extent is first in the leaf,
1472  * then we have to correct all indexes above.
1473  * TODO: do we need to correct tree in all cases?
1474  */
1475 static int ext4_ext_correct_indexes(handle_t *handle, struct inode *inode,
1476                                 struct ext4_ext_path *path)
1477 {
1478         struct ext4_extent_header *eh;
1479         int depth = ext_depth(inode);
1480         struct ext4_extent *ex;
1481         __le32 border;
1482         int k, err = 0;
1483
1484         eh = path[depth].p_hdr;
1485         ex = path[depth].p_ext;
1486
1487         if (unlikely(ex == NULL || eh == NULL)) {
1488                 EXT4_ERROR_INODE(inode,
1489                                  "ex %p == NULL or eh %p == NULL", ex, eh);
1490                 return -EIO;
1491         }
1492
1493         if (depth == 0) {
1494                 /* there is no tree at all */
1495                 return 0;
1496         }
1497
1498         if (ex != EXT_FIRST_EXTENT(eh)) {
1499                 /* we correct tree if first leaf got modified only */
1500                 return 0;
1501         }
1502
1503         /*
1504          * TODO: we need correction if border is smaller than current one
1505          */
1506         k = depth - 1;
1507         border = path[depth].p_ext->ee_block;
1508         err = ext4_ext_get_access(handle, inode, path + k);
1509         if (err)
1510                 return err;
1511         path[k].p_idx->ei_block = border;
1512         err = ext4_ext_dirty(handle, inode, path + k);
1513         if (err)
1514                 return err;
1515
1516         while (k--) {
1517                 /* change all left-side indexes */
1518                 if (path[k+1].p_idx != EXT_FIRST_INDEX(path[k+1].p_hdr))
1519                         break;
1520                 err = ext4_ext_get_access(handle, inode, path + k);
1521                 if (err)
1522                         break;
1523                 path[k].p_idx->ei_block = border;
1524                 err = ext4_ext_dirty(handle, inode, path + k);
1525                 if (err)
1526                         break;
1527         }
1528
1529         return err;
1530 }
1531
1532 int
1533 ext4_can_extents_be_merged(struct inode *inode, struct ext4_extent *ex1,
1534                                 struct ext4_extent *ex2)
1535 {
1536         unsigned short ext1_ee_len, ext2_ee_len, max_len;
1537
1538         /*
1539          * Make sure that either both extents are uninitialized, or
1540          * both are _not_.
1541          */
1542         if (ext4_ext_is_uninitialized(ex1) ^ ext4_ext_is_uninitialized(ex2))
1543                 return 0;
1544
1545         if (ext4_ext_is_uninitialized(ex1))
1546                 max_len = EXT_UNINIT_MAX_LEN;
1547         else
1548                 max_len = EXT_INIT_MAX_LEN;
1549
1550         ext1_ee_len = ext4_ext_get_actual_len(ex1);
1551         ext2_ee_len = ext4_ext_get_actual_len(ex2);
1552
1553         if (le32_to_cpu(ex1->ee_block) + ext1_ee_len !=
1554                         le32_to_cpu(ex2->ee_block))
1555                 return 0;
1556
1557         /*
1558          * To allow future support for preallocated extents to be added
1559          * as an RO_COMPAT feature, refuse to merge to extents if
1560          * this can result in the top bit of ee_len being set.
1561          */
1562         if (ext1_ee_len + ext2_ee_len > max_len)
1563                 return 0;
1564 #ifdef AGGRESSIVE_TEST
1565         if (ext1_ee_len >= 4)
1566                 return 0;
1567 #endif
1568
1569         if (ext4_ext_pblock(ex1) + ext1_ee_len == ext4_ext_pblock(ex2))
1570                 return 1;
1571         return 0;
1572 }
1573
1574 /*
1575  * This function tries to merge the "ex" extent to the next extent in the tree.
1576  * It always tries to merge towards right. If you want to merge towards
1577  * left, pass "ex - 1" as argument instead of "ex".
1578  * Returns 0 if the extents (ex and ex+1) were _not_ merged and returns
1579  * 1 if they got merged.
1580  */
1581 static int ext4_ext_try_to_merge_right(struct inode *inode,
1582                                  struct ext4_ext_path *path,
1583                                  struct ext4_extent *ex)
1584 {
1585         struct ext4_extent_header *eh;
1586         unsigned int depth, len;
1587         int merge_done = 0;
1588         int uninitialized = 0;
1589
1590         depth = ext_depth(inode);
1591         BUG_ON(path[depth].p_hdr == NULL);
1592         eh = path[depth].p_hdr;
1593
1594         while (ex < EXT_LAST_EXTENT(eh)) {
1595                 if (!ext4_can_extents_be_merged(inode, ex, ex + 1))
1596                         break;
1597                 /* merge with next extent! */
1598                 if (ext4_ext_is_uninitialized(ex))
1599                         uninitialized = 1;
1600                 ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
1601                                 + ext4_ext_get_actual_len(ex + 1));
1602                 if (uninitialized)
1603                         ext4_ext_mark_uninitialized(ex);
1604
1605                 if (ex + 1 < EXT_LAST_EXTENT(eh)) {
1606                         len = (EXT_LAST_EXTENT(eh) - ex - 1)
1607                                 * sizeof(struct ext4_extent);
1608                         memmove(ex + 1, ex + 2, len);
1609                 }
1610                 le16_add_cpu(&eh->eh_entries, -1);
1611                 merge_done = 1;
1612                 WARN_ON(eh->eh_entries == 0);
1613                 if (!eh->eh_entries)
1614                         EXT4_ERROR_INODE(inode, "eh->eh_entries = 0!");
1615         }
1616
1617         return merge_done;
1618 }
1619
1620 /*
1621  * This function tries to merge the @ex extent to neighbours in the tree.
1622  * return 1 if merge left else 0.
1623  */
1624 static int ext4_ext_try_to_merge(struct inode *inode,
1625                                   struct ext4_ext_path *path,
1626                                   struct ext4_extent *ex) {
1627         struct ext4_extent_header *eh;
1628         unsigned int depth;
1629         int merge_done = 0;
1630         int ret = 0;
1631
1632         depth = ext_depth(inode);
1633         BUG_ON(path[depth].p_hdr == NULL);
1634         eh = path[depth].p_hdr;
1635
1636         if (ex > EXT_FIRST_EXTENT(eh))
1637                 merge_done = ext4_ext_try_to_merge_right(inode, path, ex - 1);
1638
1639         if (!merge_done)
1640                 ret = ext4_ext_try_to_merge_right(inode, path, ex);
1641
1642         return ret;
1643 }
1644
1645 /*
1646  * check if a portion of the "newext" extent overlaps with an
1647  * existing extent.
1648  *
1649  * If there is an overlap discovered, it updates the length of the newext
1650  * such that there will be no overlap, and then returns 1.
1651  * If there is no overlap found, it returns 0.
1652  */
1653 static unsigned int ext4_ext_check_overlap(struct ext4_sb_info *sbi,
1654                                            struct inode *inode,
1655                                            struct ext4_extent *newext,
1656                                            struct ext4_ext_path *path)
1657 {
1658         ext4_lblk_t b1, b2;
1659         unsigned int depth, len1;
1660         unsigned int ret = 0;
1661
1662         b1 = le32_to_cpu(newext->ee_block);
1663         len1 = ext4_ext_get_actual_len(newext);
1664         depth = ext_depth(inode);
1665         if (!path[depth].p_ext)
1666                 goto out;
1667         b2 = EXT4_LBLK_CMASK(sbi, le32_to_cpu(path[depth].p_ext->ee_block));
1668
1669         /*
1670          * get the next allocated block if the extent in the path
1671          * is before the requested block(s)
1672          */
1673         if (b2 < b1) {
1674                 b2 = ext4_ext_next_allocated_block(path);
1675                 if (b2 == EXT_MAX_BLOCKS)
1676                         goto out;
1677                 b2 = EXT4_LBLK_CMASK(sbi, b2);
1678         }
1679
1680         /* check for wrap through zero on extent logical start block*/
1681         if (b1 + len1 < b1) {
1682                 len1 = EXT_MAX_BLOCKS - b1;
1683                 newext->ee_len = cpu_to_le16(len1);
1684                 ret = 1;
1685         }
1686
1687         /* check for overlap */
1688         if (b1 + len1 > b2) {
1689                 newext->ee_len = cpu_to_le16(b2 - b1);
1690                 ret = 1;
1691         }
1692 out:
1693         return ret;
1694 }
1695
1696 /*
1697  * ext4_ext_insert_extent:
1698  * tries to merge requsted extent into the existing extent or
1699  * inserts requested extent as new one into the tree,
1700  * creating new leaf in the no-space case.
1701  */
1702 int ext4_ext_insert_extent(handle_t *handle, struct inode *inode,
1703                                 struct ext4_ext_path *path,
1704                                 struct ext4_extent *newext, int flag)
1705 {
1706         struct ext4_extent_header *eh;
1707         struct ext4_extent *ex, *fex;
1708         struct ext4_extent *nearex; /* nearest extent */
1709         struct ext4_ext_path *npath = NULL;
1710         int depth, len, err;
1711         ext4_lblk_t next;
1712         unsigned uninitialized = 0;
1713         int flags = 0;
1714
1715         if (unlikely(ext4_ext_get_actual_len(newext) == 0)) {
1716                 EXT4_ERROR_INODE(inode, "ext4_ext_get_actual_len(newext) == 0");
1717                 return -EIO;
1718         }
1719         depth = ext_depth(inode);
1720         ex = path[depth].p_ext;
1721         if (unlikely(path[depth].p_hdr == NULL)) {
1722                 EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
1723                 return -EIO;
1724         }
1725
1726         /* try to insert block into found extent and return */
1727         if (ex && !(flag & EXT4_GET_BLOCKS_PRE_IO)
1728                 && ext4_can_extents_be_merged(inode, ex, newext)) {
1729                 ext_debug("append [%d]%d block to %u:[%d]%d (from %llu)\n",
1730                           ext4_ext_is_uninitialized(newext),
1731                           ext4_ext_get_actual_len(newext),
1732                           le32_to_cpu(ex->ee_block),
1733                           ext4_ext_is_uninitialized(ex),
1734                           ext4_ext_get_actual_len(ex),
1735                           ext4_ext_pblock(ex));
1736                 err = ext4_ext_get_access(handle, inode, path + depth);
1737                 if (err)
1738                         return err;
1739
1740                 /*
1741                  * ext4_can_extents_be_merged should have checked that either
1742                  * both extents are uninitialized, or both aren't. Thus we
1743                  * need to check only one of them here.
1744                  */
1745                 if (ext4_ext_is_uninitialized(ex))
1746                         uninitialized = 1;
1747                 ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
1748                                         + ext4_ext_get_actual_len(newext));
1749                 if (uninitialized)
1750                         ext4_ext_mark_uninitialized(ex);
1751                 eh = path[depth].p_hdr;
1752                 nearex = ex;
1753                 goto merge;
1754         }
1755
1756         depth = ext_depth(inode);
1757         eh = path[depth].p_hdr;
1758         if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max))
1759                 goto has_space;
1760
1761         /* probably next leaf has space for us? */
1762         fex = EXT_LAST_EXTENT(eh);
1763         next = EXT_MAX_BLOCKS;
1764         if (le32_to_cpu(newext->ee_block) > le32_to_cpu(fex->ee_block))
1765                 next = ext4_ext_next_leaf_block(path);
1766         if (next != EXT_MAX_BLOCKS) {
1767                 ext_debug("next leaf block - %u\n", next);
1768                 BUG_ON(npath != NULL);
1769                 npath = ext4_ext_find_extent(inode, next, NULL);
1770                 if (IS_ERR(npath))
1771                         return PTR_ERR(npath);
1772                 BUG_ON(npath->p_depth != path->p_depth);
1773                 eh = npath[depth].p_hdr;
1774                 if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max)) {
1775                         ext_debug("next leaf isn't full(%d)\n",
1776                                   le16_to_cpu(eh->eh_entries));
1777                         path = npath;
1778                         goto has_space;
1779                 }
1780                 ext_debug("next leaf has no free space(%d,%d)\n",
1781                           le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
1782         }
1783
1784         /*
1785          * There is no free space in the found leaf.
1786          * We're gonna add a new leaf in the tree.
1787          */
1788         if (flag & EXT4_GET_BLOCKS_PUNCH_OUT_EXT)
1789                 flags = EXT4_MB_USE_ROOT_BLOCKS;
1790         err = ext4_ext_create_new_leaf(handle, inode, flags, path, newext);
1791         if (err)
1792                 goto cleanup;
1793         depth = ext_depth(inode);
1794         eh = path[depth].p_hdr;
1795
1796 has_space:
1797         nearex = path[depth].p_ext;
1798
1799         err = ext4_ext_get_access(handle, inode, path + depth);
1800         if (err)
1801                 goto cleanup;
1802
1803         if (!nearex) {
1804                 /* there is no extent in this leaf, create first one */
1805                 ext_debug("first extent in the leaf: %u:%llu:[%d]%d\n",
1806                                 le32_to_cpu(newext->ee_block),
1807                                 ext4_ext_pblock(newext),
1808                                 ext4_ext_is_uninitialized(newext),
1809                                 ext4_ext_get_actual_len(newext));
1810                 nearex = EXT_FIRST_EXTENT(eh);
1811         } else {
1812                 if (le32_to_cpu(newext->ee_block)
1813                            > le32_to_cpu(nearex->ee_block)) {
1814                         /* Insert after */
1815                         ext_debug("insert %u:%llu:[%d]%d before: "
1816                                         "nearest %p\n",
1817                                         le32_to_cpu(newext->ee_block),
1818                                         ext4_ext_pblock(newext),
1819                                         ext4_ext_is_uninitialized(newext),
1820                                         ext4_ext_get_actual_len(newext),
1821                                         nearex);
1822                         nearex++;
1823                 } else {
1824                         /* Insert before */
1825                         BUG_ON(newext->ee_block == nearex->ee_block);
1826                         ext_debug("insert %u:%llu:[%d]%d after: "
1827                                         "nearest %p\n",
1828                                         le32_to_cpu(newext->ee_block),
1829                                         ext4_ext_pblock(newext),
1830                                         ext4_ext_is_uninitialized(newext),
1831                                         ext4_ext_get_actual_len(newext),
1832                                         nearex);
1833                 }
1834                 len = EXT_LAST_EXTENT(eh) - nearex + 1;
1835                 if (len > 0) {
1836                         ext_debug("insert %u:%llu:[%d]%d: "
1837                                         "move %d extents from 0x%p to 0x%p\n",
1838                                         le32_to_cpu(newext->ee_block),
1839                                         ext4_ext_pblock(newext),
1840                                         ext4_ext_is_uninitialized(newext),
1841                                         ext4_ext_get_actual_len(newext),
1842                                         len, nearex, nearex + 1);
1843                         memmove(nearex + 1, nearex,
1844                                 len * sizeof(struct ext4_extent));
1845                 }
1846         }
1847
1848         le16_add_cpu(&eh->eh_entries, 1);
1849         path[depth].p_ext = nearex;
1850         nearex->ee_block = newext->ee_block;
1851         ext4_ext_store_pblock(nearex, ext4_ext_pblock(newext));
1852         nearex->ee_len = newext->ee_len;
1853
1854 merge:
1855         /* try to merge extents to the right */
1856         if (!(flag & EXT4_GET_BLOCKS_PRE_IO))
1857                 ext4_ext_try_to_merge(inode, path, nearex);
1858
1859         /* try to merge extents to the left */
1860
1861         /* time to correct all indexes above */
1862         err = ext4_ext_correct_indexes(handle, inode, path);
1863         if (err)
1864                 goto cleanup;
1865
1866         err = ext4_ext_dirty(handle, inode, path + depth);
1867
1868 cleanup:
1869         if (npath) {
1870                 ext4_ext_drop_refs(npath);
1871                 kfree(npath);
1872         }
1873         ext4_ext_invalidate_cache(inode);
1874         return err;
1875 }
1876
1877 static int ext4_ext_walk_space(struct inode *inode, ext4_lblk_t block,
1878                                ext4_lblk_t num, ext_prepare_callback func,
1879                                void *cbdata)
1880 {
1881         struct ext4_ext_path *path = NULL;
1882         struct ext4_ext_cache cbex;
1883         struct ext4_extent *ex;
1884         ext4_lblk_t next, start = 0, end = 0;
1885         ext4_lblk_t last = block + num;
1886         int depth, exists, err = 0;
1887
1888         BUG_ON(func == NULL);
1889         BUG_ON(inode == NULL);
1890
1891         while (block < last && block != EXT_MAX_BLOCKS) {
1892                 num = last - block;
1893                 /* find extent for this block */
1894                 down_read(&EXT4_I(inode)->i_data_sem);
1895                 path = ext4_ext_find_extent(inode, block, path);
1896                 up_read(&EXT4_I(inode)->i_data_sem);
1897                 if (IS_ERR(path)) {
1898                         err = PTR_ERR(path);
1899                         path = NULL;
1900                         break;
1901                 }
1902
1903                 depth = ext_depth(inode);
1904                 if (unlikely(path[depth].p_hdr == NULL)) {
1905                         EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
1906                         err = -EIO;
1907                         break;
1908                 }
1909                 ex = path[depth].p_ext;
1910                 next = ext4_ext_next_allocated_block(path);
1911
1912                 exists = 0;
1913                 if (!ex) {
1914                         /* there is no extent yet, so try to allocate
1915                          * all requested space */
1916                         start = block;
1917                         end = block + num;
1918                 } else if (le32_to_cpu(ex->ee_block) > block) {
1919                         /* need to allocate space before found extent */
1920                         start = block;
1921                         end = le32_to_cpu(ex->ee_block);
1922                         if (block + num < end)
1923                                 end = block + num;
1924                 } else if (block >= le32_to_cpu(ex->ee_block)
1925                                         + ext4_ext_get_actual_len(ex)) {
1926                         /* need to allocate space after found extent */
1927                         start = block;
1928                         end = block + num;
1929                         if (end >= next)
1930                                 end = next;
1931                 } else if (block >= le32_to_cpu(ex->ee_block)) {
1932                         /*
1933                          * some part of requested space is covered
1934                          * by found extent
1935                          */
1936                         start = block;
1937                         end = le32_to_cpu(ex->ee_block)
1938                                 + ext4_ext_get_actual_len(ex);
1939                         if (block + num < end)
1940                                 end = block + num;
1941                         exists = 1;
1942                 } else {
1943                         BUG();
1944                 }
1945                 BUG_ON(end <= start);
1946
1947                 if (!exists) {
1948                         cbex.ec_block = start;
1949                         cbex.ec_len = end - start;
1950                         cbex.ec_start = 0;
1951                 } else {
1952                         cbex.ec_block = le32_to_cpu(ex->ee_block);
1953                         cbex.ec_len = ext4_ext_get_actual_len(ex);
1954                         cbex.ec_start = ext4_ext_pblock(ex);
1955                 }
1956
1957                 if (unlikely(cbex.ec_len == 0)) {
1958                         EXT4_ERROR_INODE(inode, "cbex.ec_len == 0");
1959                         err = -EIO;
1960                         break;
1961                 }
1962                 err = func(inode, next, &cbex, ex, cbdata);
1963                 ext4_ext_drop_refs(path);
1964
1965                 if (err < 0)
1966                         break;
1967
1968                 if (err == EXT_REPEAT)
1969                         continue;
1970                 else if (err == EXT_BREAK) {
1971                         err = 0;
1972                         break;
1973                 }
1974
1975                 if (ext_depth(inode) != depth) {
1976                         /* depth was changed. we have to realloc path */
1977                         kfree(path);
1978                         path = NULL;
1979                 }
1980
1981                 block = cbex.ec_block + cbex.ec_len;
1982         }
1983
1984         if (path) {
1985                 ext4_ext_drop_refs(path);
1986                 kfree(path);
1987         }
1988
1989         return err;
1990 }
1991
1992 static void
1993 ext4_ext_put_in_cache(struct inode *inode, ext4_lblk_t block,
1994                         __u32 len, ext4_fsblk_t start)
1995 {
1996         struct ext4_ext_cache *cex;
1997         BUG_ON(len == 0);
1998         spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1999         trace_ext4_ext_put_in_cache(inode, block, len, start);
2000         cex = &EXT4_I(inode)->i_cached_extent;
2001         cex->ec_block = block;
2002         cex->ec_len = len;
2003         cex->ec_start = start;
2004         spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
2005 }
2006
2007 /*
2008  * ext4_ext_put_gap_in_cache:
2009  * calculate boundaries of the gap that the requested block fits into
2010  * and cache this gap
2011  */
2012 static void
2013 ext4_ext_put_gap_in_cache(struct inode *inode, struct ext4_ext_path *path,
2014                                 ext4_lblk_t block)
2015 {
2016         int depth = ext_depth(inode);
2017         unsigned long len;
2018         ext4_lblk_t lblock;
2019         struct ext4_extent *ex;
2020
2021         ex = path[depth].p_ext;
2022         if (ex == NULL) {
2023                 /* there is no extent yet, so gap is [0;-] */
2024                 lblock = 0;
2025                 len = EXT_MAX_BLOCKS;
2026                 ext_debug("cache gap(whole file):");
2027         } else if (block < le32_to_cpu(ex->ee_block)) {
2028                 lblock = block;
2029                 len = le32_to_cpu(ex->ee_block) - block;
2030                 ext_debug("cache gap(before): %u [%u:%u]",
2031                                 block,
2032                                 le32_to_cpu(ex->ee_block),
2033                                  ext4_ext_get_actual_len(ex));
2034         } else if (block >= le32_to_cpu(ex->ee_block)
2035                         + ext4_ext_get_actual_len(ex)) {
2036                 ext4_lblk_t next;
2037                 lblock = le32_to_cpu(ex->ee_block)
2038                         + ext4_ext_get_actual_len(ex);
2039
2040                 next = ext4_ext_next_allocated_block(path);
2041                 ext_debug("cache gap(after): [%u:%u] %u",
2042                                 le32_to_cpu(ex->ee_block),
2043                                 ext4_ext_get_actual_len(ex),
2044                                 block);
2045                 BUG_ON(next == lblock);
2046                 len = next - lblock;
2047         } else {
2048                 lblock = len = 0;
2049                 BUG();
2050         }
2051
2052         ext_debug(" -> %u:%lu\n", lblock, len);
2053         ext4_ext_put_in_cache(inode, lblock, len, 0);
2054 }
2055
2056 /*
2057  * ext4_ext_check_cache()
2058  * Checks to see if the given block is in the cache.
2059  * If it is, the cached extent is stored in the given
2060  * cache extent pointer.  If the cached extent is a hole,
2061  * this routine should be used instead of
2062  * ext4_ext_in_cache if the calling function needs to
2063  * know the size of the hole.
2064  *
2065  * @inode: The files inode
2066  * @block: The block to look for in the cache
2067  * @ex:    Pointer where the cached extent will be stored
2068  *         if it contains block
2069  *
2070  * Return 0 if cache is invalid; 1 if the cache is valid
2071  */
2072 static int ext4_ext_check_cache(struct inode *inode, ext4_lblk_t block,
2073         struct ext4_ext_cache *ex){
2074         struct ext4_ext_cache *cex;
2075         struct ext4_sb_info *sbi;
2076         int ret = 0;
2077
2078         /*
2079          * We borrow i_block_reservation_lock to protect i_cached_extent
2080          */
2081         spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
2082         cex = &EXT4_I(inode)->i_cached_extent;
2083         sbi = EXT4_SB(inode->i_sb);
2084
2085         /* has cache valid data? */
2086         if (cex->ec_len == 0)
2087                 goto errout;
2088
2089         if (in_range(block, cex->ec_block, cex->ec_len)) {
2090                 memcpy(ex, cex, sizeof(struct ext4_ext_cache));
2091                 ext_debug("%u cached by %u:%u:%llu\n",
2092                                 block,
2093                                 cex->ec_block, cex->ec_len, cex->ec_start);
2094                 ret = 1;
2095         }
2096 errout:
2097         trace_ext4_ext_in_cache(inode, block, ret);
2098         spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
2099         return ret;
2100 }
2101
2102 /*
2103  * ext4_ext_in_cache()
2104  * Checks to see if the given block is in the cache.
2105  * If it is, the cached extent is stored in the given
2106  * extent pointer.
2107  *
2108  * @inode: The files inode
2109  * @block: The block to look for in the cache
2110  * @ex:    Pointer where the cached extent will be stored
2111  *         if it contains block
2112  *
2113  * Return 0 if cache is invalid; 1 if the cache is valid
2114  */
2115 static int
2116 ext4_ext_in_cache(struct inode *inode, ext4_lblk_t block,
2117                         struct ext4_extent *ex)
2118 {
2119         struct ext4_ext_cache cex;
2120         int ret = 0;
2121
2122         if (ext4_ext_check_cache(inode, block, &cex)) {
2123                 ex->ee_block = cpu_to_le32(cex.ec_block);
2124                 ext4_ext_store_pblock(ex, cex.ec_start);
2125                 ex->ee_len = cpu_to_le16(cex.ec_len);
2126                 ret = 1;
2127         }
2128
2129         return ret;
2130 }
2131
2132
2133 /*
2134  * ext4_ext_rm_idx:
2135  * removes index from the index block.
2136  */
2137 static int ext4_ext_rm_idx(handle_t *handle, struct inode *inode,
2138                         struct ext4_ext_path *path, int depth)
2139 {
2140         int err;
2141         ext4_fsblk_t leaf;
2142
2143         /* free index block */
2144         depth--;
2145         path = path + depth;
2146         leaf = ext4_idx_pblock(path->p_idx);
2147         if (unlikely(path->p_hdr->eh_entries == 0)) {
2148                 EXT4_ERROR_INODE(inode, "path->p_hdr->eh_entries == 0");
2149                 return -EIO;
2150         }
2151         err = ext4_ext_get_access(handle, inode, path);
2152         if (err)
2153                 return err;
2154
2155         if (path->p_idx != EXT_LAST_INDEX(path->p_hdr)) {
2156                 int len = EXT_LAST_INDEX(path->p_hdr) - path->p_idx;
2157                 len *= sizeof(struct ext4_extent_idx);
2158                 memmove(path->p_idx, path->p_idx + 1, len);
2159         }
2160
2161         le16_add_cpu(&path->p_hdr->eh_entries, -1);
2162         err = ext4_ext_dirty(handle, inode, path);
2163         if (err)
2164                 return err;
2165         ext_debug("index is empty, remove it, free block %llu\n", leaf);
2166         trace_ext4_ext_rm_idx(inode, leaf);
2167
2168         ext4_free_blocks(handle, inode, NULL, leaf, 1,
2169                          EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET);
2170
2171         while (--depth >= 0) {
2172                 if (path->p_idx != EXT_FIRST_INDEX(path->p_hdr))
2173                         break;
2174                 path--;
2175                 err = ext4_ext_get_access(handle, inode, path);
2176                 if (err)
2177                         break;
2178                 path->p_idx->ei_block = (path+1)->p_idx->ei_block;
2179                 err = ext4_ext_dirty(handle, inode, path);
2180                 if (err)
2181                         break;
2182         }
2183         return err;
2184 }
2185
2186 /*
2187  * ext4_ext_calc_credits_for_single_extent:
2188  * This routine returns max. credits that needed to insert an extent
2189  * to the extent tree.
2190  * When pass the actual path, the caller should calculate credits
2191  * under i_data_sem.
2192  */
2193 int ext4_ext_calc_credits_for_single_extent(struct inode *inode, int nrblocks,
2194                                                 struct ext4_ext_path *path)
2195 {
2196         if (path) {
2197                 int depth = ext_depth(inode);
2198                 int ret = 0;
2199
2200                 /* probably there is space in leaf? */
2201                 if (le16_to_cpu(path[depth].p_hdr->eh_entries)
2202                                 < le16_to_cpu(path[depth].p_hdr->eh_max)) {
2203
2204                         /*
2205                          *  There are some space in the leaf tree, no
2206                          *  need to account for leaf block credit
2207                          *
2208                          *  bitmaps and block group descriptor blocks
2209                          *  and other metadata blocks still need to be
2210                          *  accounted.
2211                          */
2212                         /* 1 bitmap, 1 block group descriptor */
2213                         ret = 2 + EXT4_META_TRANS_BLOCKS(inode->i_sb);
2214                         return ret;
2215                 }
2216         }
2217
2218         return ext4_chunk_trans_blocks(inode, nrblocks);
2219 }
2220
2221 /*
2222  * How many index/leaf blocks need to change/allocate to modify nrblocks?
2223  *
2224  * if nrblocks are fit in a single extent (chunk flag is 1), then
2225  * in the worse case, each tree level index/leaf need to be changed
2226  * if the tree split due to insert a new extent, then the old tree
2227  * index/leaf need to be updated too
2228  *
2229  * If the nrblocks are discontiguous, they could cause
2230  * the whole tree split more than once, but this is really rare.
2231  */
2232 int ext4_ext_index_trans_blocks(struct inode *inode, int nrblocks, int chunk)
2233 {
2234         int index;
2235         int depth = ext_depth(inode);
2236
2237         if (chunk)
2238                 index = depth * 2;
2239         else
2240                 index = depth * 3;
2241
2242         return index;
2243 }
2244
2245 static int ext4_remove_blocks(handle_t *handle, struct inode *inode,
2246                               struct ext4_extent *ex,
2247                               ext4_fsblk_t *partial_cluster,
2248                               ext4_lblk_t from, ext4_lblk_t to)
2249 {
2250         struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2251         unsigned short ee_len =  ext4_ext_get_actual_len(ex);
2252         ext4_fsblk_t pblk;
2253         int flags = EXT4_FREE_BLOCKS_FORGET;
2254
2255         if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode))
2256                 flags |= EXT4_FREE_BLOCKS_METADATA;
2257         /*
2258          * For bigalloc file systems, we never free a partial cluster
2259          * at the beginning of the extent.  Instead, we make a note
2260          * that we tried freeing the cluster, and check to see if we
2261          * need to free it on a subsequent call to ext4_remove_blocks,
2262          * or at the end of the ext4_truncate() operation.
2263          */
2264         flags |= EXT4_FREE_BLOCKS_NOFREE_FIRST_CLUSTER;
2265
2266         trace_ext4_remove_blocks(inode, ex, from, to, *partial_cluster);
2267         /*
2268          * If we have a partial cluster, and it's different from the
2269          * cluster of the last block, we need to explicitly free the
2270          * partial cluster here.
2271          */
2272         pblk = ext4_ext_pblock(ex) + ee_len - 1;
2273         if (*partial_cluster && (EXT4_B2C(sbi, pblk) != *partial_cluster)) {
2274                 ext4_free_blocks(handle, inode, NULL,
2275                                  EXT4_C2B(sbi, *partial_cluster),
2276                                  sbi->s_cluster_ratio, flags);
2277                 *partial_cluster = 0;
2278         }
2279
2280 #ifdef EXTENTS_STATS
2281         {
2282                 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2283                 spin_lock(&sbi->s_ext_stats_lock);
2284                 sbi->s_ext_blocks += ee_len;
2285                 sbi->s_ext_extents++;
2286                 if (ee_len < sbi->s_ext_min)
2287                         sbi->s_ext_min = ee_len;
2288                 if (ee_len > sbi->s_ext_max)
2289                         sbi->s_ext_max = ee_len;
2290                 if (ext_depth(inode) > sbi->s_depth_max)
2291                         sbi->s_depth_max = ext_depth(inode);
2292                 spin_unlock(&sbi->s_ext_stats_lock);
2293         }
2294 #endif
2295         if (from >= le32_to_cpu(ex->ee_block)
2296             && to == le32_to_cpu(ex->ee_block) + ee_len - 1) {
2297                 /* tail removal */
2298                 ext4_lblk_t num;
2299
2300                 num = le32_to_cpu(ex->ee_block) + ee_len - from;
2301                 pblk = ext4_ext_pblock(ex) + ee_len - num;
2302                 ext_debug("free last %u blocks starting %llu\n", num, pblk);
2303                 ext4_free_blocks(handle, inode, NULL, pblk, num, flags);
2304                 /*
2305                  * If the block range to be freed didn't start at the
2306                  * beginning of a cluster, and we removed the entire
2307                  * extent, save the partial cluster here, since we
2308                  * might need to delete if we determine that the
2309                  * truncate operation has removed all of the blocks in
2310                  * the cluster.
2311                  */
2312                 if (EXT4_PBLK_COFF(sbi, pblk) &&
2313                     (ee_len == num))
2314                         *partial_cluster = EXT4_B2C(sbi, pblk);
2315                 else
2316                         *partial_cluster = 0;
2317         } else if (from == le32_to_cpu(ex->ee_block)
2318                    && to <= le32_to_cpu(ex->ee_block) + ee_len - 1) {
2319                 /* head removal */
2320                 ext4_lblk_t num;
2321                 ext4_fsblk_t start;
2322
2323                 num = to - from;
2324                 start = ext4_ext_pblock(ex);
2325
2326                 ext_debug("free first %u blocks starting %llu\n", num, start);
2327                 ext4_free_blocks(handle, inode, NULL, start, num, flags);
2328
2329         } else {
2330                 printk(KERN_INFO "strange request: removal(2) "
2331                                 "%u-%u from %u:%u\n",
2332                                 from, to, le32_to_cpu(ex->ee_block), ee_len);
2333         }
2334         return 0;
2335 }
2336
2337
2338 /*
2339  * ext4_ext_rm_leaf() Removes the extents associated with the
2340  * blocks appearing between "start" and "end", and splits the extents
2341  * if "start" and "end" appear in the same extent
2342  *
2343  * @handle: The journal handle
2344  * @inode:  The files inode
2345  * @path:   The path to the leaf
2346  * @start:  The first block to remove
2347  * @end:   The last block to remove
2348  */
2349 static int
2350 ext4_ext_rm_leaf(handle_t *handle, struct inode *inode,
2351                  struct ext4_ext_path *path, ext4_fsblk_t *partial_cluster,
2352                  ext4_lblk_t start, ext4_lblk_t end)
2353 {
2354         struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2355         int err = 0, correct_index = 0;
2356         int depth = ext_depth(inode), credits;
2357         struct ext4_extent_header *eh;
2358         ext4_lblk_t a, b;
2359         unsigned num;
2360         ext4_lblk_t ex_ee_block;
2361         unsigned short ex_ee_len;
2362         unsigned uninitialized = 0;
2363         struct ext4_extent *ex;
2364
2365         /* the header must be checked already in ext4_ext_remove_space() */
2366         ext_debug("truncate since %u in leaf to %u\n", start, end);
2367         if (!path[depth].p_hdr)
2368                 path[depth].p_hdr = ext_block_hdr(path[depth].p_bh);
2369         eh = path[depth].p_hdr;
2370         if (unlikely(path[depth].p_hdr == NULL)) {
2371                 EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
2372                 return -EIO;
2373         }
2374         /* find where to start removing */
2375         ex = EXT_LAST_EXTENT(eh);
2376
2377         ex_ee_block = le32_to_cpu(ex->ee_block);
2378         ex_ee_len = ext4_ext_get_actual_len(ex);
2379
2380         /*
2381          * If we're starting with an extent other than the last one in the
2382          * node, we need to see if it shares a cluster with the extent to
2383          * the right (towards the end of the file). If its leftmost cluster
2384          * is this extent's rightmost cluster and it is not cluster aligned,
2385          * we'll mark it as a partial that is not to be deallocated.
2386          */
2387
2388         if (ex != EXT_LAST_EXTENT(eh)) {
2389                 ext4_fsblk_t current_pblk, right_pblk;
2390                 long long current_cluster, right_cluster;
2391
2392                 current_pblk = ext4_ext_pblock(ex) + ex_ee_len - 1;
2393                 current_cluster = (long long)EXT4_B2C(sbi, current_pblk);
2394                 right_pblk = ext4_ext_pblock(ex + 1);
2395                 right_cluster = (long long)EXT4_B2C(sbi, right_pblk);
2396                 if (current_cluster == right_cluster &&
2397                         EXT4_PBLK_COFF(sbi, right_pblk))
2398                         *partial_cluster = -right_cluster;
2399         }
2400
2401         trace_ext4_ext_rm_leaf(inode, start, ex, *partial_cluster);
2402
2403         while (ex >= EXT_FIRST_EXTENT(eh) &&
2404                         ex_ee_block + ex_ee_len > start) {
2405
2406                 if (ext4_ext_is_uninitialized(ex))
2407                         uninitialized = 1;
2408                 else
2409                         uninitialized = 0;
2410
2411                 ext_debug("remove ext %u:[%d]%d\n", ex_ee_block,
2412                          uninitialized, ex_ee_len);
2413                 path[depth].p_ext = ex;
2414
2415                 a = ex_ee_block > start ? ex_ee_block : start;
2416                 b = ex_ee_block+ex_ee_len - 1 < end ?
2417                         ex_ee_block+ex_ee_len - 1 : end;
2418
2419                 ext_debug("  border %u:%u\n", a, b);
2420
2421                 /* If this extent is beyond the end of the hole, skip it */
2422                 if (end < ex_ee_block) {
2423                         ex--;
2424                         ex_ee_block = le32_to_cpu(ex->ee_block);
2425                         ex_ee_len = ext4_ext_get_actual_len(ex);
2426                         continue;
2427                 } else if (b != ex_ee_block + ex_ee_len - 1) {
2428                         EXT4_ERROR_INODE(inode,"  bad truncate %u:%u\n",
2429                                          start, end);
2430                         err = -EIO;
2431                         goto out;
2432                 } else if (a != ex_ee_block) {
2433                         /* remove tail of the extent */
2434                         num = a - ex_ee_block;
2435                 } else {
2436                         /* remove whole extent: excellent! */
2437                         num = 0;
2438                 }
2439                 /*
2440                  * 3 for leaf, sb, and inode plus 2 (bmap and group
2441                  * descriptor) for each block group; assume two block
2442                  * groups plus ex_ee_len/blocks_per_block_group for
2443                  * the worst case
2444                  */
2445                 credits = 7 + 2*(ex_ee_len/EXT4_BLOCKS_PER_GROUP(inode->i_sb));
2446                 if (ex == EXT_FIRST_EXTENT(eh)) {
2447                         correct_index = 1;
2448                         credits += (ext_depth(inode)) + 1;
2449                 }
2450                 credits += EXT4_MAXQUOTAS_TRANS_BLOCKS(inode->i_sb);
2451
2452                 err = ext4_ext_truncate_extend_restart(handle, inode, credits);
2453                 if (err)
2454                         goto out;
2455
2456                 err = ext4_ext_get_access(handle, inode, path + depth);
2457                 if (err)
2458                         goto out;
2459
2460                 err = ext4_remove_blocks(handle, inode, ex, partial_cluster,
2461                                          a, b);
2462                 if (err)
2463                         goto out;
2464
2465                 if (num == 0)
2466                         /* this extent is removed; mark slot entirely unused */
2467                         ext4_ext_store_pblock(ex, 0);
2468
2469                 ex->ee_len = cpu_to_le16(num);
2470                 /*
2471                  * Do not mark uninitialized if all the blocks in the
2472                  * extent have been removed.
2473                  */
2474                 if (uninitialized && num)
2475                         ext4_ext_mark_uninitialized(ex);
2476                 /*
2477                  * If the extent was completely released,
2478                  * we need to remove it from the leaf
2479                  */
2480                 if (num == 0) {
2481                         if (end != EXT_MAX_BLOCKS - 1) {
2482                                 /*
2483                                  * For hole punching, we need to scoot all the
2484                                  * extents up when an extent is removed so that
2485                                  * we dont have blank extents in the middle
2486                                  */
2487                                 memmove(ex, ex+1, (EXT_LAST_EXTENT(eh) - ex) *
2488                                         sizeof(struct ext4_extent));
2489
2490                                 /* Now get rid of the one at the end */
2491                                 memset(EXT_LAST_EXTENT(eh), 0,
2492                                         sizeof(struct ext4_extent));
2493                         }
2494                         le16_add_cpu(&eh->eh_entries, -1);
2495                 } else
2496                         *partial_cluster = 0;
2497
2498                 err = ext4_ext_dirty(handle, inode, path + depth);
2499                 if (err)
2500                         goto out;
2501
2502                 ext_debug("new extent: %u:%u:%llu\n", ex_ee_block, num,
2503                                 ext4_ext_pblock(ex));
2504                 ex--;
2505                 ex_ee_block = le32_to_cpu(ex->ee_block);
2506                 ex_ee_len = ext4_ext_get_actual_len(ex);
2507         }
2508
2509         if (correct_index && eh->eh_entries)
2510                 err = ext4_ext_correct_indexes(handle, inode, path);
2511
2512         /*
2513          * If there is still a entry in the leaf node, check to see if
2514          * it references the partial cluster.  This is the only place
2515          * where it could; if it doesn't, we can free the cluster.
2516          */
2517         if (*partial_cluster && ex >= EXT_FIRST_EXTENT(eh) &&
2518             (EXT4_B2C(sbi, ext4_ext_pblock(ex) + ex_ee_len - 1) !=
2519              *partial_cluster)) {
2520                 int flags = EXT4_FREE_BLOCKS_FORGET;
2521
2522                 if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode))
2523                         flags |= EXT4_FREE_BLOCKS_METADATA;
2524
2525                 ext4_free_blocks(handle, inode, NULL,
2526                                  EXT4_C2B(sbi, *partial_cluster),
2527                                  sbi->s_cluster_ratio, flags);
2528                 *partial_cluster = 0;
2529         }
2530
2531         /* if this leaf is free, then we should
2532          * remove it from index block above */
2533         if (err == 0 && eh->eh_entries == 0 && path[depth].p_bh != NULL)
2534                 err = ext4_ext_rm_idx(handle, inode, path, depth);
2535
2536 out:
2537         return err;
2538 }
2539
2540 /*
2541  * ext4_ext_more_to_rm:
2542  * returns 1 if current index has to be freed (even partial)
2543  */
2544 static int
2545 ext4_ext_more_to_rm(struct ext4_ext_path *path)
2546 {
2547         BUG_ON(path->p_idx == NULL);
2548
2549         if (path->p_idx < EXT_FIRST_INDEX(path->p_hdr))
2550                 return 0;
2551
2552         /*
2553          * if truncate on deeper level happened, it wasn't partial,
2554          * so we have to consider current index for truncation
2555          */
2556         if (le16_to_cpu(path->p_hdr->eh_entries) == path->p_block)
2557                 return 0;
2558         return 1;
2559 }
2560
2561 static int ext4_ext_remove_space(struct inode *inode, ext4_lblk_t start,
2562                                  ext4_lblk_t end)
2563 {
2564         struct super_block *sb = inode->i_sb;
2565         int depth = ext_depth(inode);
2566         struct ext4_ext_path *path = NULL;
2567         ext4_fsblk_t partial_cluster = 0;
2568         handle_t *handle;
2569         int i = 0, err;
2570
2571         ext_debug("truncate since %u to %u\n", start, end);
2572
2573         /* probably first extent we're gonna free will be last in block */
2574         handle = ext4_journal_start(inode, depth + 1);
2575         if (IS_ERR(handle))
2576                 return PTR_ERR(handle);
2577
2578 again:
2579         ext4_ext_invalidate_cache(inode);
2580
2581         trace_ext4_ext_remove_space(inode, start, depth);
2582
2583         /*
2584          * Check if we are removing extents inside the extent tree. If that
2585          * is the case, we are going to punch a hole inside the extent tree
2586          * so we have to check whether we need to split the extent covering
2587          * the last block to remove so we can easily remove the part of it
2588          * in ext4_ext_rm_leaf().
2589          */
2590         if (end < EXT_MAX_BLOCKS - 1) {
2591                 struct ext4_extent *ex;
2592                 ext4_lblk_t ee_block;
2593
2594                 /* find extent for this block */
2595                 path = ext4_ext_find_extent(inode, end, NULL);
2596                 if (IS_ERR(path)) {
2597                         ext4_journal_stop(handle);
2598                         return PTR_ERR(path);
2599                 }
2600                 depth = ext_depth(inode);
2601                 ex = path[depth].p_ext;
2602                 if (!ex) {
2603                         ext4_ext_drop_refs(path);
2604                         kfree(path);
2605                         path = NULL;
2606                         goto cont;
2607                 }
2608
2609                 ee_block = le32_to_cpu(ex->ee_block);
2610
2611                 /*
2612                  * See if the last block is inside the extent, if so split
2613                  * the extent at 'end' block so we can easily remove the
2614                  * tail of the first part of the split extent in
2615                  * ext4_ext_rm_leaf().
2616                  */
2617                 if (end >= ee_block &&
2618                     end < ee_block + ext4_ext_get_actual_len(ex) - 1) {
2619                         int split_flag = 0;
2620
2621                         if (ext4_ext_is_uninitialized(ex))
2622                                 split_flag = EXT4_EXT_MARK_UNINIT1 |
2623                                              EXT4_EXT_MARK_UNINIT2;
2624
2625                         /*
2626                          * Split the extent in two so that 'end' is the last
2627                          * block in the first new extent
2628                          */
2629                         err = ext4_split_extent_at(handle, inode, path,
2630                                                 end + 1, split_flag,
2631                                                 EXT4_GET_BLOCKS_PRE_IO |
2632                                                 EXT4_GET_BLOCKS_PUNCH_OUT_EXT);
2633
2634                         if (err < 0)
2635                                 goto out;
2636                 }
2637         }
2638 cont:
2639
2640         /*
2641          * We start scanning from right side, freeing all the blocks
2642          * after i_size and walking into the tree depth-wise.
2643          */
2644         depth = ext_depth(inode);
2645         if (path) {
2646                 int k = i = depth;
2647                 while (--k > 0)
2648                         path[k].p_block =
2649                                 le16_to_cpu(path[k].p_hdr->eh_entries)+1;
2650         } else {
2651                 path = kzalloc(sizeof(struct ext4_ext_path) * (depth + 1),
2652                                GFP_NOFS);
2653                 if (path == NULL) {
2654                         ext4_journal_stop(handle);
2655                         return -ENOMEM;
2656                 }
2657                 path[0].p_depth = depth;
2658                 path[0].p_hdr = ext_inode_hdr(inode);
2659                 i = 0;
2660
2661                 if (ext4_ext_check(inode, path[0].p_hdr, depth)) {
2662                         err = -EIO;
2663                         goto out;
2664                 }
2665         }
2666         err = 0;
2667
2668         while (i >= 0 && err == 0) {
2669                 if (i == depth) {
2670                         /* this is leaf block */
2671                         err = ext4_ext_rm_leaf(handle, inode, path,
2672                                                &partial_cluster, start,
2673                                                end);
2674                         /* root level has p_bh == NULL, brelse() eats this */
2675                         brelse(path[i].p_bh);
2676                         path[i].p_bh = NULL;
2677                         i--;
2678                         continue;
2679                 }
2680
2681                 /* this is index block */
2682                 if (!path[i].p_hdr) {
2683                         ext_debug("initialize header\n");
2684                         path[i].p_hdr = ext_block_hdr(path[i].p_bh);
2685                 }
2686
2687                 if (!path[i].p_idx) {
2688                         /* this level hasn't been touched yet */
2689                         path[i].p_idx = EXT_LAST_INDEX(path[i].p_hdr);
2690                         path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries)+1;
2691                         ext_debug("init index ptr: hdr 0x%p, num %d\n",
2692                                   path[i].p_hdr,
2693                                   le16_to_cpu(path[i].p_hdr->eh_entries));
2694                 } else {
2695                         /* we were already here, see at next index */
2696                         path[i].p_idx--;
2697                 }
2698
2699                 ext_debug("level %d - index, first 0x%p, cur 0x%p\n",
2700                                 i, EXT_FIRST_INDEX(path[i].p_hdr),
2701                                 path[i].p_idx);
2702                 if (ext4_ext_more_to_rm(path + i)) {
2703                         struct buffer_head *bh;
2704                         /* go to the next level */
2705                         ext_debug("move to level %d (block %llu)\n",
2706                                   i + 1, ext4_idx_pblock(path[i].p_idx));
2707                         memset(path + i + 1, 0, sizeof(*path));
2708                         bh = sb_bread(sb, ext4_idx_pblock(path[i].p_idx));
2709                         if (!bh) {
2710                                 /* should we reset i_size? */
2711                                 err = -EIO;
2712                                 break;
2713                         }
2714                         if (WARN_ON(i + 1 > depth)) {
2715                                 err = -EIO;
2716                                 break;
2717                         }
2718                         if (ext4_ext_check(inode, ext_block_hdr(bh),
2719                                                         depth - i - 1)) {
2720                                 err = -EIO;
2721                                 break;
2722                         }
2723                         path[i + 1].p_bh = bh;
2724
2725                         /* save actual number of indexes since this
2726                          * number is changed at the next iteration */
2727                         path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries);
2728                         i++;
2729                 } else {
2730                         /* we finished processing this index, go up */
2731                         if (path[i].p_hdr->eh_entries == 0 && i > 0) {
2732                                 /* index is empty, remove it;
2733                                  * handle must be already prepared by the
2734                                  * truncatei_leaf() */
2735                                 err = ext4_ext_rm_idx(handle, inode, path, i);
2736                         }
2737                         /* root level has p_bh == NULL, brelse() eats this */
2738                         brelse(path[i].p_bh);
2739                         path[i].p_bh = NULL;
2740                         i--;
2741                         ext_debug("return to level %d\n", i);
2742                 }
2743         }
2744
2745         trace_ext4_ext_remove_space_done(inode, start, depth, partial_cluster,
2746                         path->p_hdr->eh_entries);
2747
2748         /* If we still have something in the partial cluster and we have removed
2749          * even the first extent, then we should free the blocks in the partial
2750          * cluster as well. */
2751         if (partial_cluster && path->p_hdr->eh_entries == 0) {
2752                 int flags = EXT4_FREE_BLOCKS_FORGET;
2753
2754                 if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode))
2755                         flags |= EXT4_FREE_BLOCKS_METADATA;
2756
2757                 ext4_free_blocks(handle, inode, NULL,
2758                                  EXT4_C2B(EXT4_SB(sb), partial_cluster),
2759                                  EXT4_SB(sb)->s_cluster_ratio, flags);
2760                 partial_cluster = 0;
2761         }
2762
2763         /* TODO: flexible tree reduction should be here */
2764         if (path->p_hdr->eh_entries == 0) {
2765                 /*
2766                  * truncate to zero freed all the tree,
2767                  * so we need to correct eh_depth
2768                  */
2769                 err = ext4_ext_get_access(handle, inode, path);
2770                 if (err == 0) {
2771                         ext_inode_hdr(inode)->eh_depth = 0;
2772                         ext_inode_hdr(inode)->eh_max =
2773                                 cpu_to_le16(ext4_ext_space_root(inode, 0));
2774                         err = ext4_ext_dirty(handle, inode, path);
2775                 }
2776         }
2777 out:
2778         ext4_ext_drop_refs(path);
2779         kfree(path);
2780         if (err == -EAGAIN) {
2781                 path = NULL;
2782                 goto again;
2783         }
2784         ext4_journal_stop(handle);
2785
2786         return err;
2787 }
2788
2789 /*
2790  * called at mount time
2791  */
2792 void ext4_ext_init(struct super_block *sb)
2793 {
2794         /*
2795          * possible initialization would be here
2796          */
2797
2798         if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_EXTENTS)) {
2799 #if defined(AGGRESSIVE_TEST) || defined(CHECK_BINSEARCH) || defined(EXTENTS_STATS)
2800                 printk(KERN_INFO "EXT4-fs: file extents enabled");
2801 #ifdef AGGRESSIVE_TEST
2802                 printk(", aggressive tests");
2803 #endif
2804 #ifdef CHECK_BINSEARCH
2805                 printk(", check binsearch");
2806 #endif
2807 #ifdef EXTENTS_STATS
2808                 printk(", stats");
2809 #endif
2810                 printk("\n");
2811 #endif
2812 #ifdef EXTENTS_STATS
2813                 spin_lock_init(&EXT4_SB(sb)->s_ext_stats_lock);
2814                 EXT4_SB(sb)->s_ext_min = 1 << 30;
2815                 EXT4_SB(sb)->s_ext_max = 0;
2816 #endif
2817         }
2818 }
2819
2820 /*
2821  * called at umount time
2822  */
2823 void ext4_ext_release(struct super_block *sb)
2824 {
2825         if (!EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_EXTENTS))
2826                 return;
2827
2828 #ifdef EXTENTS_STATS
2829         if (EXT4_SB(sb)->s_ext_blocks && EXT4_SB(sb)->s_ext_extents) {
2830                 struct ext4_sb_info *sbi = EXT4_SB(sb);
2831                 printk(KERN_ERR "EXT4-fs: %lu blocks in %lu extents (%lu ave)\n",
2832                         sbi->s_ext_blocks, sbi->s_ext_extents,
2833                         sbi->s_ext_blocks / sbi->s_ext_extents);
2834                 printk(KERN_ERR "EXT4-fs: extents: %lu min, %lu max, max depth %lu\n",
2835                         sbi->s_ext_min, sbi->s_ext_max, sbi->s_depth_max);
2836         }
2837 #endif
2838 }
2839
2840 /* FIXME!! we need to try to merge to left or right after zero-out  */
2841 static int ext4_ext_zeroout(struct inode *inode, struct ext4_extent *ex)
2842 {
2843         ext4_fsblk_t ee_pblock;
2844         unsigned int ee_len;
2845         int ret;
2846
2847         ee_len    = ext4_ext_get_actual_len(ex);
2848         ee_pblock = ext4_ext_pblock(ex);
2849
2850         ret = sb_issue_zeroout(inode->i_sb, ee_pblock, ee_len, GFP_NOFS);
2851         if (ret > 0)
2852                 ret = 0;
2853
2854         return ret;
2855 }
2856
2857 /*
2858  * ext4_split_extent_at() splits an extent at given block.
2859  *
2860  * @handle: the journal handle
2861  * @inode: the file inode
2862  * @path: the path to the extent
2863  * @split: the logical block where the extent is splitted.
2864  * @split_flags: indicates if the extent could be zeroout if split fails, and
2865  *               the states(init or uninit) of new extents.
2866  * @flags: flags used to insert new extent to extent tree.
2867  *
2868  *
2869  * Splits extent [a, b] into two extents [a, @split) and [@split, b], states
2870  * of which are deterimined by split_flag.
2871  *
2872  * There are two cases:
2873  *  a> the extent are splitted into two extent.
2874  *  b> split is not needed, and just mark the extent.
2875  *
2876  * return 0 on success.
2877  */
2878 static int ext4_split_extent_at(handle_t *handle,
2879                              struct inode *inode,
2880                              struct ext4_ext_path *path,
2881                              ext4_lblk_t split,
2882                              int split_flag,
2883                              int flags)
2884 {
2885         ext4_fsblk_t newblock;
2886         ext4_lblk_t ee_block;
2887         struct ext4_extent *ex, newex, orig_ex;
2888         struct ext4_extent *ex2 = NULL;
2889         unsigned int ee_len, depth;
2890         int err = 0;
2891
2892         BUG_ON((split_flag & (EXT4_EXT_DATA_VALID1 | EXT4_EXT_DATA_VALID2)) ==
2893                (EXT4_EXT_DATA_VALID1 | EXT4_EXT_DATA_VALID2));
2894
2895         ext_debug("ext4_split_extents_at: inode %lu, logical"
2896                 "block %llu\n", inode->i_ino, (unsigned long long)split);
2897
2898         ext4_ext_show_leaf(inode, path);
2899
2900         depth = ext_depth(inode);
2901         ex = path[depth].p_ext;
2902         ee_block = le32_to_cpu(ex->ee_block);
2903         ee_len = ext4_ext_get_actual_len(ex);
2904         newblock = split - ee_block + ext4_ext_pblock(ex);
2905
2906         BUG_ON(split < ee_block || split >= (ee_block + ee_len));
2907
2908         err = ext4_ext_get_access(handle, inode, path + depth);
2909         if (err)
2910                 goto out;
2911
2912         if (split == ee_block) {
2913                 /*
2914                  * case b: block @split is the block that the extent begins with
2915                  * then we just change the state of the extent, and splitting
2916                  * is not needed.
2917                  */
2918                 if (split_flag & EXT4_EXT_MARK_UNINIT2)
2919                         ext4_ext_mark_uninitialized(ex);
2920                 else
2921                         ext4_ext_mark_initialized(ex);
2922
2923                 if (!(flags & EXT4_GET_BLOCKS_PRE_IO))
2924                         ext4_ext_try_to_merge(inode, path, ex);
2925
2926                 err = ext4_ext_dirty(handle, inode, path + depth);
2927                 goto out;
2928         }
2929
2930         /* case a */
2931         memcpy(&orig_ex, ex, sizeof(orig_ex));
2932         ex->ee_len = cpu_to_le16(split - ee_block);
2933         if (split_flag & EXT4_EXT_MARK_UNINIT1)
2934                 ext4_ext_mark_uninitialized(ex);
2935
2936         /*
2937          * path may lead to new leaf, not to original leaf any more
2938          * after ext4_ext_insert_extent() returns,
2939          */
2940         err = ext4_ext_dirty(handle, inode, path + depth);
2941         if (err)
2942                 goto fix_extent_len;
2943
2944         ex2 = &newex;
2945         ex2->ee_block = cpu_to_le32(split);
2946         ex2->ee_len   = cpu_to_le16(ee_len - (split - ee_block));
2947         ext4_ext_store_pblock(ex2, newblock);
2948         if (split_flag & EXT4_EXT_MARK_UNINIT2)
2949                 ext4_ext_mark_uninitialized(ex2);
2950
2951         err = ext4_ext_insert_extent(handle, inode, path, &newex, flags);
2952         if (err == -ENOSPC && (EXT4_EXT_MAY_ZEROOUT & split_flag)) {
2953                 if (split_flag & (EXT4_EXT_DATA_VALID1|EXT4_EXT_DATA_VALID2)) {
2954                         if (split_flag & EXT4_EXT_DATA_VALID1)
2955                                 err = ext4_ext_zeroout(inode, ex2);
2956                         else
2957                                 err = ext4_ext_zeroout(inode, ex);
2958                 } else
2959                         err = ext4_ext_zeroout(inode, &orig_ex);
2960
2961                 if (err)
2962                         goto fix_extent_len;
2963                 /* update the extent length and mark as initialized */
2964                 ex->ee_len = cpu_to_le16(ee_len);
2965                 ext4_ext_try_to_merge(inode, path, ex);
2966                 err = ext4_ext_dirty(handle, inode, path + depth);
2967                 goto out;
2968         } else if (err)
2969                 goto fix_extent_len;
2970
2971 out:
2972         ext4_ext_show_leaf(inode, path);
2973         return err;
2974
2975 fix_extent_len:
2976         ex->ee_len = orig_ex.ee_len;
2977         ext4_ext_dirty(handle, inode, path + depth);
2978         return err;
2979 }
2980
2981 /*
2982  * ext4_split_extents() splits an extent and mark extent which is covered
2983  * by @map as split_flags indicates
2984  *
2985  * It may result in splitting the extent into multiple extents (upto three)
2986  * There are three possibilities:
2987  *   a> There is no split required
2988  *   b> Splits in two extents: Split is happening at either end of the extent
2989  *   c> Splits in three extents: Somone is splitting in middle of the extent
2990  *
2991  */
2992 static int ext4_split_extent(handle_t *handle,
2993                               struct inode *inode,
2994                               struct ext4_ext_path *path,
2995                               struct ext4_map_blocks *map,
2996                               int split_flag,
2997                               int flags)
2998 {
2999         ext4_lblk_t ee_block;
3000         struct ext4_extent *ex;
3001         unsigned int ee_len, depth;
3002         int err = 0;
3003         int uninitialized;
3004         int split_flag1, flags1;
3005         int allocated = map->m_len;
3006
3007         depth = ext_depth(inode);
3008         ex = path[depth].p_ext;
3009         ee_block = le32_to_cpu(ex->ee_block);
3010         ee_len = ext4_ext_get_actual_len(ex);
3011         uninitialized = ext4_ext_is_uninitialized(ex);
3012
3013         if (map->m_lblk + map->m_len < ee_block + ee_len) {
3014                 split_flag1 = split_flag & EXT4_EXT_MAY_ZEROOUT;
3015                 flags1 = flags | EXT4_GET_BLOCKS_PRE_IO;
3016                 if (uninitialized)
3017                         split_flag1 |= EXT4_EXT_MARK_UNINIT1 |
3018                                        EXT4_EXT_MARK_UNINIT2;
3019                 if (split_flag & EXT4_EXT_DATA_VALID2)
3020                         split_flag1 |= EXT4_EXT_DATA_VALID1;
3021                 err = ext4_split_extent_at(handle, inode, path,
3022                                 map->m_lblk + map->m_len, split_flag1, flags1);
3023                 if (err)
3024                         goto out;
3025         } else {
3026                 allocated = ee_len - (map->m_lblk - ee_block);
3027         }
3028
3029         ext4_ext_drop_refs(path);
3030         path = ext4_ext_find_extent(inode, map->m_lblk, path);
3031         if (IS_ERR(path))
3032                 return PTR_ERR(path);
3033
3034         if (map->m_lblk >= ee_block) {
3035                 split_flag1 = split_flag & (EXT4_EXT_MAY_ZEROOUT |
3036                                             EXT4_EXT_DATA_VALID2);
3037                 if (uninitialized)
3038                         split_flag1 |= EXT4_EXT_MARK_UNINIT1;
3039                 if (split_flag & EXT4_EXT_MARK_UNINIT2)
3040                         split_flag1 |= EXT4_EXT_MARK_UNINIT2;
3041                 err = ext4_split_extent_at(handle, inode, path,
3042                                 map->m_lblk, split_flag1, flags);
3043                 if (err)
3044                         goto out;
3045         }
3046
3047         ext4_ext_show_leaf(inode, path);
3048 out:
3049         return err ? err : allocated;
3050 }
3051
3052 #define EXT4_EXT_ZERO_LEN 7
3053 /*
3054  * This function is called by ext4_ext_map_blocks() if someone tries to write
3055  * to an uninitialized extent. It may result in splitting the uninitialized
3056  * extent into multiple extents (up to three - one initialized and two
3057  * uninitialized).
3058  * There are three possibilities:
3059  *   a> There is no split required: Entire extent should be initialized
3060  *   b> Splits in two extents: Write is happening at either end of the extent
3061  *   c> Splits in three extents: Somone is writing in middle of the extent
3062  *
3063  * Pre-conditions:
3064  *  - The extent pointed to by 'path' is uninitialized.
3065  *  - The extent pointed to by 'path' contains a superset
3066  *    of the logical span [map->m_lblk, map->m_lblk + map->m_len).
3067  *
3068  * Post-conditions on success:
3069  *  - the returned value is the number of blocks beyond map->l_lblk
3070  *    that are allocated and initialized.
3071  *    It is guaranteed to be >= map->m_len.
3072  */
3073 static int ext4_ext_convert_to_initialized(handle_t *handle,
3074                                            struct inode *inode,
3075                                            struct ext4_map_blocks *map,
3076                                            struct ext4_ext_path *path)
3077 {
3078         struct ext4_extent_header *eh;
3079         struct ext4_map_blocks split_map;
3080         struct ext4_extent zero_ex;
3081         struct ext4_extent *ex;
3082         ext4_lblk_t ee_block, eof_block;
3083         unsigned int ee_len, depth;
3084         int allocated;
3085         int err = 0;
3086         int split_flag = 0;
3087
3088         ext_debug("ext4_ext_convert_to_initialized: inode %lu, logical"
3089                 "block %llu, max_blocks %u\n", inode->i_ino,
3090                 (unsigned long long)map->m_lblk, map->m_len);
3091
3092         eof_block = (inode->i_size + inode->i_sb->s_blocksize - 1) >>
3093                 inode->i_sb->s_blocksize_bits;
3094         if (eof_block < map->m_lblk + map->m_len)
3095                 eof_block = map->m_lblk + map->m_len;
3096
3097         depth = ext_depth(inode);
3098         eh = path[depth].p_hdr;
3099         ex = path[depth].p_ext;
3100         ee_block = le32_to_cpu(ex->ee_block);
3101