ext4: fix endianness breakage in ext4_split_extent_at()
[firefly-linux-kernel-4.4.55.git] / fs / ext4 / extents.c
1 /*
2  * Copyright (c) 2003-2006, Cluster File Systems, Inc, info@clusterfs.com
3  * Written by Alex Tomas <alex@clusterfs.com>
4  *
5  * Architecture independence:
6  *   Copyright (c) 2005, Bull S.A.
7  *   Written by Pierre Peiffer <pierre.peiffer@bull.net>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License version 2 as
11  * published by the Free Software Foundation.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public Licens
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-
21  */
22
23 /*
24  * Extents support for EXT4
25  *
26  * TODO:
27  *   - ext4*_error() should be used in some situations
28  *   - analyze all BUG()/BUG_ON(), use -EIO where appropriate
29  *   - smart tree reduction
30  */
31
32 #include <linux/module.h>
33 #include <linux/fs.h>
34 #include <linux/time.h>
35 #include <linux/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 #include "ext4_extents.h"
46
47 #include <trace/events/ext4.h>
48
49 static int ext4_split_extent(handle_t *handle,
50                                 struct inode *inode,
51                                 struct ext4_ext_path *path,
52                                 struct ext4_map_blocks *map,
53                                 int split_flag,
54                                 int flags);
55
56 static int ext4_ext_truncate_extend_restart(handle_t *handle,
57                                             struct inode *inode,
58                                             int needed)
59 {
60         int err;
61
62         if (!ext4_handle_valid(handle))
63                 return 0;
64         if (handle->h_buffer_credits > needed)
65                 return 0;
66         err = ext4_journal_extend(handle, needed);
67         if (err <= 0)
68                 return err;
69         err = ext4_truncate_restart_trans(handle, inode, needed);
70         if (err == 0)
71                 err = -EAGAIN;
72
73         return err;
74 }
75
76 /*
77  * could return:
78  *  - EROFS
79  *  - ENOMEM
80  */
81 static int ext4_ext_get_access(handle_t *handle, struct inode *inode,
82                                 struct ext4_ext_path *path)
83 {
84         if (path->p_bh) {
85                 /* path points to block */
86                 return ext4_journal_get_write_access(handle, path->p_bh);
87         }
88         /* path points to leaf/index in inode body */
89         /* we use in-core data, no need to protect them */
90         return 0;
91 }
92
93 /*
94  * could return:
95  *  - EROFS
96  *  - ENOMEM
97  *  - EIO
98  */
99 static int ext4_ext_dirty(handle_t *handle, struct inode *inode,
100                                 struct ext4_ext_path *path)
101 {
102         int err;
103         if (path->p_bh) {
104                 /* path points to block */
105                 err = ext4_handle_dirty_metadata(handle, inode, path->p_bh);
106         } else {
107                 /* path points to leaf/index in inode body */
108                 err = ext4_mark_inode_dirty(handle, inode);
109         }
110         return err;
111 }
112
113 static ext4_fsblk_t ext4_ext_find_goal(struct inode *inode,
114                               struct ext4_ext_path *path,
115                               ext4_lblk_t block)
116 {
117         struct ext4_inode_info *ei = EXT4_I(inode);
118         ext4_fsblk_t bg_start;
119         ext4_fsblk_t last_block;
120         ext4_grpblk_t colour;
121         ext4_group_t block_group;
122         int flex_size = ext4_flex_bg_size(EXT4_SB(inode->i_sb));
123         int depth;
124
125         if (path) {
126                 struct ext4_extent *ex;
127                 depth = path->p_depth;
128
129                 /*
130                  * Try to predict block placement assuming that we are
131                  * filling in a file which will eventually be
132                  * non-sparse --- i.e., in the case of libbfd writing
133                  * an ELF object sections out-of-order but in a way
134                  * the eventually results in a contiguous object or
135                  * executable file, or some database extending a table
136                  * space file.  However, this is actually somewhat
137                  * non-ideal if we are writing a sparse file such as
138                  * qemu or KVM writing a raw image file that is going
139                  * to stay fairly sparse, since it will end up
140                  * fragmenting the file system's free space.  Maybe we
141                  * should have some hueristics or some way to allow
142                  * userspace to pass a hint to file system,
143                  * especially if the latter case turns out to be
144                  * common.
145                  */
146                 ex = path[depth].p_ext;
147                 if (ex) {
148                         ext4_fsblk_t ext_pblk = ext4_ext_pblock(ex);
149                         ext4_lblk_t ext_block = le32_to_cpu(ex->ee_block);
150
151                         if (block > ext_block)
152                                 return ext_pblk + (block - ext_block);
153                         else
154                                 return ext_pblk - (ext_block - block);
155                 }
156
157                 /* it looks like index is empty;
158                  * try to find starting block from index itself */
159                 if (path[depth].p_bh)
160                         return path[depth].p_bh->b_blocknr;
161         }
162
163         /* OK. use inode's group */
164         block_group = ei->i_block_group;
165         if (flex_size >= EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME) {
166                 /*
167                  * If there are at least EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME
168                  * block groups per flexgroup, reserve the first block
169                  * group for directories and special files.  Regular
170                  * files will start at the second block group.  This
171                  * tends to speed up directory access and improves
172                  * fsck times.
173                  */
174                 block_group &= ~(flex_size-1);
175                 if (S_ISREG(inode->i_mode))
176                         block_group++;
177         }
178         bg_start = ext4_group_first_block_no(inode->i_sb, block_group);
179         last_block = ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es) - 1;
180
181         /*
182          * If we are doing delayed allocation, we don't need take
183          * colour into account.
184          */
185         if (test_opt(inode->i_sb, DELALLOC))
186                 return bg_start;
187
188         if (bg_start + EXT4_BLOCKS_PER_GROUP(inode->i_sb) <= last_block)
189                 colour = (current->pid % 16) *
190                         (EXT4_BLOCKS_PER_GROUP(inode->i_sb) / 16);
191         else
192                 colour = (current->pid % 16) * ((last_block - bg_start) / 16);
193         return bg_start + colour + block;
194 }
195
196 /*
197  * Allocation for a meta data block
198  */
199 static ext4_fsblk_t
200 ext4_ext_new_meta_block(handle_t *handle, struct inode *inode,
201                         struct ext4_ext_path *path,
202                         struct ext4_extent *ex, int *err, unsigned int flags)
203 {
204         ext4_fsblk_t goal, newblock;
205
206         goal = ext4_ext_find_goal(inode, path, le32_to_cpu(ex->ee_block));
207         newblock = ext4_new_meta_blocks(handle, inode, goal, flags,
208                                         NULL, err);
209         return newblock;
210 }
211
212 static inline int ext4_ext_space_block(struct inode *inode, int check)
213 {
214         int size;
215
216         size = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
217                         / sizeof(struct ext4_extent);
218         if (!check) {
219 #ifdef AGGRESSIVE_TEST
220                 if (size > 6)
221                         size = 6;
222 #endif
223         }
224         return size;
225 }
226
227 static inline int ext4_ext_space_block_idx(struct inode *inode, int check)
228 {
229         int size;
230
231         size = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
232                         / sizeof(struct ext4_extent_idx);
233         if (!check) {
234 #ifdef AGGRESSIVE_TEST
235                 if (size > 5)
236                         size = 5;
237 #endif
238         }
239         return size;
240 }
241
242 static inline int ext4_ext_space_root(struct inode *inode, int check)
243 {
244         int size;
245
246         size = sizeof(EXT4_I(inode)->i_data);
247         size -= sizeof(struct ext4_extent_header);
248         size /= sizeof(struct ext4_extent);
249         if (!check) {
250 #ifdef AGGRESSIVE_TEST
251                 if (size > 3)
252                         size = 3;
253 #endif
254         }
255         return size;
256 }
257
258 static inline int ext4_ext_space_root_idx(struct inode *inode, int check)
259 {
260         int size;
261
262         size = sizeof(EXT4_I(inode)->i_data);
263         size -= sizeof(struct ext4_extent_header);
264         size /= sizeof(struct ext4_extent_idx);
265         if (!check) {
266 #ifdef AGGRESSIVE_TEST
267                 if (size > 4)
268                         size = 4;
269 #endif
270         }
271         return size;
272 }
273
274 /*
275  * Calculate the number of metadata blocks needed
276  * to allocate @blocks
277  * Worse case is one block per extent
278  */
279 int ext4_ext_calc_metadata_amount(struct inode *inode, ext4_lblk_t lblock)
280 {
281         struct ext4_inode_info *ei = EXT4_I(inode);
282         int idxs, num = 0;
283
284         idxs = ((inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
285                 / sizeof(struct ext4_extent_idx));
286
287         /*
288          * If the new delayed allocation block is contiguous with the
289          * previous da block, it can share index blocks with the
290          * previous block, so we only need to allocate a new index
291          * block every idxs leaf blocks.  At ldxs**2 blocks, we need
292          * an additional index block, and at ldxs**3 blocks, yet
293          * another index blocks.
294          */
295         if (ei->i_da_metadata_calc_len &&
296             ei->i_da_metadata_calc_last_lblock+1 == lblock) {
297                 if ((ei->i_da_metadata_calc_len % idxs) == 0)
298                         num++;
299                 if ((ei->i_da_metadata_calc_len % (idxs*idxs)) == 0)
300                         num++;
301                 if ((ei->i_da_metadata_calc_len % (idxs*idxs*idxs)) == 0) {
302                         num++;
303                         ei->i_da_metadata_calc_len = 0;
304                 } else
305                         ei->i_da_metadata_calc_len++;
306                 ei->i_da_metadata_calc_last_lblock++;
307                 return num;
308         }
309
310         /*
311          * In the worst case we need a new set of index blocks at
312          * every level of the inode's extent tree.
313          */
314         ei->i_da_metadata_calc_len = 1;
315         ei->i_da_metadata_calc_last_lblock = lblock;
316         return ext_depth(inode) + 1;
317 }
318
319 static int
320 ext4_ext_max_entries(struct inode *inode, int depth)
321 {
322         int max;
323
324         if (depth == ext_depth(inode)) {
325                 if (depth == 0)
326                         max = ext4_ext_space_root(inode, 1);
327                 else
328                         max = ext4_ext_space_root_idx(inode, 1);
329         } else {
330                 if (depth == 0)
331                         max = ext4_ext_space_block(inode, 1);
332                 else
333                         max = ext4_ext_space_block_idx(inode, 1);
334         }
335
336         return max;
337 }
338
339 static int ext4_valid_extent(struct inode *inode, struct ext4_extent *ext)
340 {
341         ext4_fsblk_t block = ext4_ext_pblock(ext);
342         int len = ext4_ext_get_actual_len(ext);
343
344         if (len == 0)
345                 return 0;
346         return ext4_data_block_valid(EXT4_SB(inode->i_sb), block, len);
347 }
348
349 static int ext4_valid_extent_idx(struct inode *inode,
350                                 struct ext4_extent_idx *ext_idx)
351 {
352         ext4_fsblk_t block = ext4_idx_pblock(ext_idx);
353
354         return ext4_data_block_valid(EXT4_SB(inode->i_sb), block, 1);
355 }
356
357 static int ext4_valid_extent_entries(struct inode *inode,
358                                 struct ext4_extent_header *eh,
359                                 int depth)
360 {
361         struct ext4_extent *ext;
362         struct ext4_extent_idx *ext_idx;
363         unsigned short entries;
364         if (eh->eh_entries == 0)
365                 return 1;
366
367         entries = le16_to_cpu(eh->eh_entries);
368
369         if (depth == 0) {
370                 /* leaf entries */
371                 ext = EXT_FIRST_EXTENT(eh);
372                 while (entries) {
373                         if (!ext4_valid_extent(inode, ext))
374                                 return 0;
375                         ext++;
376                         entries--;
377                 }
378         } else {
379                 ext_idx = EXT_FIRST_INDEX(eh);
380                 while (entries) {
381                         if (!ext4_valid_extent_idx(inode, ext_idx))
382                                 return 0;
383                         ext_idx++;
384                         entries--;
385                 }
386         }
387         return 1;
388 }
389
390 static int __ext4_ext_check(const char *function, unsigned int line,
391                             struct inode *inode, struct ext4_extent_header *eh,
392                             int depth)
393 {
394         const char *error_msg;
395         int max = 0;
396
397         if (unlikely(eh->eh_magic != EXT4_EXT_MAGIC)) {
398                 error_msg = "invalid magic";
399                 goto corrupted;
400         }
401         if (unlikely(le16_to_cpu(eh->eh_depth) != depth)) {
402                 error_msg = "unexpected eh_depth";
403                 goto corrupted;
404         }
405         if (unlikely(eh->eh_max == 0)) {
406                 error_msg = "invalid eh_max";
407                 goto corrupted;
408         }
409         max = ext4_ext_max_entries(inode, depth);
410         if (unlikely(le16_to_cpu(eh->eh_max) > max)) {
411                 error_msg = "too large eh_max";
412                 goto corrupted;
413         }
414         if (unlikely(le16_to_cpu(eh->eh_entries) > le16_to_cpu(eh->eh_max))) {
415                 error_msg = "invalid eh_entries";
416                 goto corrupted;
417         }
418         if (!ext4_valid_extent_entries(inode, eh, depth)) {
419                 error_msg = "invalid extent entries";
420                 goto corrupted;
421         }
422         return 0;
423
424 corrupted:
425         ext4_error_inode(inode, function, line, 0,
426                         "bad header/extent: %s - magic %x, "
427                         "entries %u, max %u(%u), depth %u(%u)",
428                         error_msg, le16_to_cpu(eh->eh_magic),
429                         le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max),
430                         max, le16_to_cpu(eh->eh_depth), depth);
431
432         return -EIO;
433 }
434
435 #define ext4_ext_check(inode, eh, depth)        \
436         __ext4_ext_check(__func__, __LINE__, inode, eh, depth)
437
438 int ext4_ext_check_inode(struct inode *inode)
439 {
440         return ext4_ext_check(inode, ext_inode_hdr(inode), ext_depth(inode));
441 }
442
443 #ifdef EXT_DEBUG
444 static void ext4_ext_show_path(struct inode *inode, struct ext4_ext_path *path)
445 {
446         int k, l = path->p_depth;
447
448         ext_debug("path:");
449         for (k = 0; k <= l; k++, path++) {
450                 if (path->p_idx) {
451                   ext_debug("  %d->%llu", le32_to_cpu(path->p_idx->ei_block),
452                             ext4_idx_pblock(path->p_idx));
453                 } else if (path->p_ext) {
454                         ext_debug("  %d:[%d]%d:%llu ",
455                                   le32_to_cpu(path->p_ext->ee_block),
456                                   ext4_ext_is_uninitialized(path->p_ext),
457                                   ext4_ext_get_actual_len(path->p_ext),
458                                   ext4_ext_pblock(path->p_ext));
459                 } else
460                         ext_debug("  []");
461         }
462         ext_debug("\n");
463 }
464
465 static void ext4_ext_show_leaf(struct inode *inode, struct ext4_ext_path *path)
466 {
467         int depth = ext_depth(inode);
468         struct ext4_extent_header *eh;
469         struct ext4_extent *ex;
470         int i;
471
472         if (!path)
473                 return;
474
475         eh = path[depth].p_hdr;
476         ex = EXT_FIRST_EXTENT(eh);
477
478         ext_debug("Displaying leaf extents for inode %lu\n", inode->i_ino);
479
480         for (i = 0; i < le16_to_cpu(eh->eh_entries); i++, ex++) {
481                 ext_debug("%d:[%d]%d:%llu ", le32_to_cpu(ex->ee_block),
482                           ext4_ext_is_uninitialized(ex),
483                           ext4_ext_get_actual_len(ex), ext4_ext_pblock(ex));
484         }
485         ext_debug("\n");
486 }
487
488 static void ext4_ext_show_move(struct inode *inode, struct ext4_ext_path *path,
489                         ext4_fsblk_t newblock, int level)
490 {
491         int depth = ext_depth(inode);
492         struct ext4_extent *ex;
493
494         if (depth != level) {
495                 struct ext4_extent_idx *idx;
496                 idx = path[level].p_idx;
497                 while (idx <= EXT_MAX_INDEX(path[level].p_hdr)) {
498                         ext_debug("%d: move %d:%llu in new index %llu\n", level,
499                                         le32_to_cpu(idx->ei_block),
500                                         ext4_idx_pblock(idx),
501                                         newblock);
502                         idx++;
503                 }
504
505                 return;
506         }
507
508         ex = path[depth].p_ext;
509         while (ex <= EXT_MAX_EXTENT(path[depth].p_hdr)) {
510                 ext_debug("move %d:%llu:[%d]%d in new leaf %llu\n",
511                                 le32_to_cpu(ex->ee_block),
512                                 ext4_ext_pblock(ex),
513                                 ext4_ext_is_uninitialized(ex),
514                                 ext4_ext_get_actual_len(ex),
515                                 newblock);
516                 ex++;
517         }
518 }
519
520 #else
521 #define ext4_ext_show_path(inode, path)
522 #define ext4_ext_show_leaf(inode, path)
523 #define ext4_ext_show_move(inode, path, newblock, level)
524 #endif
525
526 void ext4_ext_drop_refs(struct ext4_ext_path *path)
527 {
528         int depth = path->p_depth;
529         int i;
530
531         for (i = 0; i <= depth; i++, path++)
532                 if (path->p_bh) {
533                         brelse(path->p_bh);
534                         path->p_bh = NULL;
535                 }
536 }
537
538 /*
539  * ext4_ext_binsearch_idx:
540  * binary search for the closest index of the given block
541  * the header must be checked before calling this
542  */
543 static void
544 ext4_ext_binsearch_idx(struct inode *inode,
545                         struct ext4_ext_path *path, ext4_lblk_t block)
546 {
547         struct ext4_extent_header *eh = path->p_hdr;
548         struct ext4_extent_idx *r, *l, *m;
549
550
551         ext_debug("binsearch for %u(idx):  ", block);
552
553         l = EXT_FIRST_INDEX(eh) + 1;
554         r = EXT_LAST_INDEX(eh);
555         while (l <= r) {
556                 m = l + (r - l) / 2;
557                 if (block < le32_to_cpu(m->ei_block))
558                         r = m - 1;
559                 else
560                         l = m + 1;
561                 ext_debug("%p(%u):%p(%u):%p(%u) ", l, le32_to_cpu(l->ei_block),
562                                 m, le32_to_cpu(m->ei_block),
563                                 r, le32_to_cpu(r->ei_block));
564         }
565
566         path->p_idx = l - 1;
567         ext_debug("  -> %d->%lld ", le32_to_cpu(path->p_idx->ei_block),
568                   ext4_idx_pblock(path->p_idx));
569
570 #ifdef CHECK_BINSEARCH
571         {
572                 struct ext4_extent_idx *chix, *ix;
573                 int k;
574
575                 chix = ix = EXT_FIRST_INDEX(eh);
576                 for (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ix++) {
577                   if (k != 0 &&
578                       le32_to_cpu(ix->ei_block) <= le32_to_cpu(ix[-1].ei_block)) {
579                                 printk(KERN_DEBUG "k=%d, ix=0x%p, "
580                                        "first=0x%p\n", k,
581                                        ix, EXT_FIRST_INDEX(eh));
582                                 printk(KERN_DEBUG "%u <= %u\n",
583                                        le32_to_cpu(ix->ei_block),
584                                        le32_to_cpu(ix[-1].ei_block));
585                         }
586                         BUG_ON(k && le32_to_cpu(ix->ei_block)
587                                            <= le32_to_cpu(ix[-1].ei_block));
588                         if (block < le32_to_cpu(ix->ei_block))
589                                 break;
590                         chix = ix;
591                 }
592                 BUG_ON(chix != path->p_idx);
593         }
594 #endif
595
596 }
597
598 /*
599  * ext4_ext_binsearch:
600  * binary search for closest extent of the given block
601  * the header must be checked before calling this
602  */
603 static void
604 ext4_ext_binsearch(struct inode *inode,
605                 struct ext4_ext_path *path, ext4_lblk_t block)
606 {
607         struct ext4_extent_header *eh = path->p_hdr;
608         struct ext4_extent *r, *l, *m;
609
610         if (eh->eh_entries == 0) {
611                 /*
612                  * this leaf is empty:
613                  * we get such a leaf in split/add case
614                  */
615                 return;
616         }
617
618         ext_debug("binsearch for %u:  ", block);
619
620         l = EXT_FIRST_EXTENT(eh) + 1;
621         r = EXT_LAST_EXTENT(eh);
622
623         while (l <= r) {
624                 m = l + (r - l) / 2;
625                 if (block < le32_to_cpu(m->ee_block))
626                         r = m - 1;
627                 else
628                         l = m + 1;
629                 ext_debug("%p(%u):%p(%u):%p(%u) ", l, le32_to_cpu(l->ee_block),
630                                 m, le32_to_cpu(m->ee_block),
631                                 r, le32_to_cpu(r->ee_block));
632         }
633
634         path->p_ext = l - 1;
635         ext_debug("  -> %d:%llu:[%d]%d ",
636                         le32_to_cpu(path->p_ext->ee_block),
637                         ext4_ext_pblock(path->p_ext),
638                         ext4_ext_is_uninitialized(path->p_ext),
639                         ext4_ext_get_actual_len(path->p_ext));
640
641 #ifdef CHECK_BINSEARCH
642         {
643                 struct ext4_extent *chex, *ex;
644                 int k;
645
646                 chex = ex = EXT_FIRST_EXTENT(eh);
647                 for (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ex++) {
648                         BUG_ON(k && le32_to_cpu(ex->ee_block)
649                                           <= le32_to_cpu(ex[-1].ee_block));
650                         if (block < le32_to_cpu(ex->ee_block))
651                                 break;
652                         chex = ex;
653                 }
654                 BUG_ON(chex != path->p_ext);
655         }
656 #endif
657
658 }
659
660 int ext4_ext_tree_init(handle_t *handle, struct inode *inode)
661 {
662         struct ext4_extent_header *eh;
663
664         eh = ext_inode_hdr(inode);
665         eh->eh_depth = 0;
666         eh->eh_entries = 0;
667         eh->eh_magic = EXT4_EXT_MAGIC;
668         eh->eh_max = cpu_to_le16(ext4_ext_space_root(inode, 0));
669         ext4_mark_inode_dirty(handle, inode);
670         ext4_ext_invalidate_cache(inode);
671         return 0;
672 }
673
674 struct ext4_ext_path *
675 ext4_ext_find_extent(struct inode *inode, ext4_lblk_t block,
676                                         struct ext4_ext_path *path)
677 {
678         struct ext4_extent_header *eh;
679         struct buffer_head *bh;
680         short int depth, i, ppos = 0, alloc = 0;
681
682         eh = ext_inode_hdr(inode);
683         depth = ext_depth(inode);
684
685         /* account possible depth increase */
686         if (!path) {
687                 path = kzalloc(sizeof(struct ext4_ext_path) * (depth + 2),
688                                 GFP_NOFS);
689                 if (!path)
690                         return ERR_PTR(-ENOMEM);
691                 alloc = 1;
692         }
693         path[0].p_hdr = eh;
694         path[0].p_bh = NULL;
695
696         i = depth;
697         /* walk through the tree */
698         while (i) {
699                 int need_to_validate = 0;
700
701                 ext_debug("depth %d: num %d, max %d\n",
702                           ppos, le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
703
704                 ext4_ext_binsearch_idx(inode, path + ppos, block);
705                 path[ppos].p_block = ext4_idx_pblock(path[ppos].p_idx);
706                 path[ppos].p_depth = i;
707                 path[ppos].p_ext = NULL;
708
709                 bh = sb_getblk(inode->i_sb, path[ppos].p_block);
710                 if (unlikely(!bh))
711                         goto err;
712                 if (!bh_uptodate_or_lock(bh)) {
713                         trace_ext4_ext_load_extent(inode, block,
714                                                 path[ppos].p_block);
715                         if (bh_submit_read(bh) < 0) {
716                                 put_bh(bh);
717                                 goto err;
718                         }
719                         /* validate the extent entries */
720                         need_to_validate = 1;
721                 }
722                 eh = ext_block_hdr(bh);
723                 ppos++;
724                 if (unlikely(ppos > depth)) {
725                         put_bh(bh);
726                         EXT4_ERROR_INODE(inode,
727                                          "ppos %d > depth %d", ppos, depth);
728                         goto err;
729                 }
730                 path[ppos].p_bh = bh;
731                 path[ppos].p_hdr = eh;
732                 i--;
733
734                 if (need_to_validate && ext4_ext_check(inode, eh, i))
735                         goto err;
736         }
737
738         path[ppos].p_depth = i;
739         path[ppos].p_ext = NULL;
740         path[ppos].p_idx = NULL;
741
742         /* find extent */
743         ext4_ext_binsearch(inode, path + ppos, block);
744         /* if not an empty leaf */
745         if (path[ppos].p_ext)
746                 path[ppos].p_block = ext4_ext_pblock(path[ppos].p_ext);
747
748         ext4_ext_show_path(inode, path);
749
750         return path;
751
752 err:
753         ext4_ext_drop_refs(path);
754         if (alloc)
755                 kfree(path);
756         return ERR_PTR(-EIO);
757 }
758
759 /*
760  * ext4_ext_insert_index:
761  * insert new index [@logical;@ptr] into the block at @curp;
762  * check where to insert: before @curp or after @curp
763  */
764 static int ext4_ext_insert_index(handle_t *handle, struct inode *inode,
765                                  struct ext4_ext_path *curp,
766                                  int logical, ext4_fsblk_t ptr)
767 {
768         struct ext4_extent_idx *ix;
769         int len, err;
770
771         err = ext4_ext_get_access(handle, inode, curp);
772         if (err)
773                 return err;
774
775         if (unlikely(logical == le32_to_cpu(curp->p_idx->ei_block))) {
776                 EXT4_ERROR_INODE(inode,
777                                  "logical %d == ei_block %d!",
778                                  logical, le32_to_cpu(curp->p_idx->ei_block));
779                 return -EIO;
780         }
781         len = EXT_MAX_INDEX(curp->p_hdr) - curp->p_idx;
782         if (logical > le32_to_cpu(curp->p_idx->ei_block)) {
783                 /* insert after */
784                 if (curp->p_idx != EXT_LAST_INDEX(curp->p_hdr)) {
785                         len = (len - 1) * sizeof(struct ext4_extent_idx);
786                         len = len < 0 ? 0 : len;
787                         ext_debug("insert new index %d after: %llu. "
788                                         "move %d from 0x%p to 0x%p\n",
789                                         logical, ptr, len,
790                                         (curp->p_idx + 1), (curp->p_idx + 2));
791                         memmove(curp->p_idx + 2, curp->p_idx + 1, len);
792                 }
793                 ix = curp->p_idx + 1;
794         } else {
795                 /* insert before */
796                 len = len * sizeof(struct ext4_extent_idx);
797                 len = len < 0 ? 0 : len;
798                 ext_debug("insert new index %d before: %llu. "
799                                 "move %d from 0x%p to 0x%p\n",
800                                 logical, ptr, len,
801                                 curp->p_idx, (curp->p_idx + 1));
802                 memmove(curp->p_idx + 1, curp->p_idx, len);
803                 ix = curp->p_idx;
804         }
805
806         ix->ei_block = cpu_to_le32(logical);
807         ext4_idx_store_pblock(ix, ptr);
808         le16_add_cpu(&curp->p_hdr->eh_entries, 1);
809
810         if (unlikely(le16_to_cpu(curp->p_hdr->eh_entries)
811                              > le16_to_cpu(curp->p_hdr->eh_max))) {
812                 EXT4_ERROR_INODE(inode,
813                                  "logical %d == ei_block %d!",
814                                  logical, le32_to_cpu(curp->p_idx->ei_block));
815                 return -EIO;
816         }
817         if (unlikely(ix > EXT_LAST_INDEX(curp->p_hdr))) {
818                 EXT4_ERROR_INODE(inode, "ix > EXT_LAST_INDEX!");
819                 return -EIO;
820         }
821
822         err = ext4_ext_dirty(handle, inode, curp);
823         ext4_std_error(inode->i_sb, err);
824
825         return err;
826 }
827
828 /*
829  * ext4_ext_split:
830  * inserts new subtree into the path, using free index entry
831  * at depth @at:
832  * - allocates all needed blocks (new leaf and all intermediate index blocks)
833  * - makes decision where to split
834  * - moves remaining extents and index entries (right to the split point)
835  *   into the newly allocated blocks
836  * - initializes subtree
837  */
838 static int ext4_ext_split(handle_t *handle, struct inode *inode,
839                           unsigned int flags,
840                           struct ext4_ext_path *path,
841                           struct ext4_extent *newext, int at)
842 {
843         struct buffer_head *bh = NULL;
844         int depth = ext_depth(inode);
845         struct ext4_extent_header *neh;
846         struct ext4_extent_idx *fidx;
847         int i = at, k, m, a;
848         ext4_fsblk_t newblock, oldblock;
849         __le32 border;
850         ext4_fsblk_t *ablocks = NULL; /* array of allocated blocks */
851         int err = 0;
852
853         /* make decision: where to split? */
854         /* FIXME: now decision is simplest: at current extent */
855
856         /* if current leaf will be split, then we should use
857          * border from split point */
858         if (unlikely(path[depth].p_ext > EXT_MAX_EXTENT(path[depth].p_hdr))) {
859                 EXT4_ERROR_INODE(inode, "p_ext > EXT_MAX_EXTENT!");
860                 return -EIO;
861         }
862         if (path[depth].p_ext != EXT_MAX_EXTENT(path[depth].p_hdr)) {
863                 border = path[depth].p_ext[1].ee_block;
864                 ext_debug("leaf will be split."
865                                 " next leaf starts at %d\n",
866                                   le32_to_cpu(border));
867         } else {
868                 border = newext->ee_block;
869                 ext_debug("leaf will be added."
870                                 " next leaf starts at %d\n",
871                                 le32_to_cpu(border));
872         }
873
874         /*
875          * If error occurs, then we break processing
876          * and mark filesystem read-only. index won't
877          * be inserted and tree will be in consistent
878          * state. Next mount will repair buffers too.
879          */
880
881         /*
882          * Get array to track all allocated blocks.
883          * We need this to handle errors and free blocks
884          * upon them.
885          */
886         ablocks = kzalloc(sizeof(ext4_fsblk_t) * depth, GFP_NOFS);
887         if (!ablocks)
888                 return -ENOMEM;
889
890         /* allocate all needed blocks */
891         ext_debug("allocate %d blocks for indexes/leaf\n", depth - at);
892         for (a = 0; a < depth - at; a++) {
893                 newblock = ext4_ext_new_meta_block(handle, inode, path,
894                                                    newext, &err, flags);
895                 if (newblock == 0)
896                         goto cleanup;
897                 ablocks[a] = newblock;
898         }
899
900         /* initialize new leaf */
901         newblock = ablocks[--a];
902         if (unlikely(newblock == 0)) {
903                 EXT4_ERROR_INODE(inode, "newblock == 0!");
904                 err = -EIO;
905                 goto cleanup;
906         }
907         bh = sb_getblk(inode->i_sb, newblock);
908         if (!bh) {
909                 err = -EIO;
910                 goto cleanup;
911         }
912         lock_buffer(bh);
913
914         err = ext4_journal_get_create_access(handle, bh);
915         if (err)
916                 goto cleanup;
917
918         neh = ext_block_hdr(bh);
919         neh->eh_entries = 0;
920         neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0));
921         neh->eh_magic = EXT4_EXT_MAGIC;
922         neh->eh_depth = 0;
923
924         /* move remainder of path[depth] to the new leaf */
925         if (unlikely(path[depth].p_hdr->eh_entries !=
926                      path[depth].p_hdr->eh_max)) {
927                 EXT4_ERROR_INODE(inode, "eh_entries %d != eh_max %d!",
928                                  path[depth].p_hdr->eh_entries,
929                                  path[depth].p_hdr->eh_max);
930                 err = -EIO;
931                 goto cleanup;
932         }
933         /* start copy from next extent */
934         m = EXT_MAX_EXTENT(path[depth].p_hdr) - path[depth].p_ext++;
935         ext4_ext_show_move(inode, path, newblock, depth);
936         if (m) {
937                 struct ext4_extent *ex;
938                 ex = EXT_FIRST_EXTENT(neh);
939                 memmove(ex, path[depth].p_ext, sizeof(struct ext4_extent) * m);
940                 le16_add_cpu(&neh->eh_entries, m);
941         }
942
943         set_buffer_uptodate(bh);
944         unlock_buffer(bh);
945
946         err = ext4_handle_dirty_metadata(handle, inode, bh);
947         if (err)
948                 goto cleanup;
949         brelse(bh);
950         bh = NULL;
951
952         /* correct old leaf */
953         if (m) {
954                 err = ext4_ext_get_access(handle, inode, path + depth);
955                 if (err)
956                         goto cleanup;
957                 le16_add_cpu(&path[depth].p_hdr->eh_entries, -m);
958                 err = ext4_ext_dirty(handle, inode, path + depth);
959                 if (err)
960                         goto cleanup;
961
962         }
963
964         /* create intermediate indexes */
965         k = depth - at - 1;
966         if (unlikely(k < 0)) {
967                 EXT4_ERROR_INODE(inode, "k %d < 0!", k);
968                 err = -EIO;
969                 goto cleanup;
970         }
971         if (k)
972                 ext_debug("create %d intermediate indices\n", k);
973         /* insert new index into current index block */
974         /* current depth stored in i var */
975         i = depth - 1;
976         while (k--) {
977                 oldblock = newblock;
978                 newblock = ablocks[--a];
979                 bh = sb_getblk(inode->i_sb, newblock);
980                 if (!bh) {
981                         err = -EIO;
982                         goto cleanup;
983                 }
984                 lock_buffer(bh);
985
986                 err = ext4_journal_get_create_access(handle, bh);
987                 if (err)
988                         goto cleanup;
989
990                 neh = ext_block_hdr(bh);
991                 neh->eh_entries = cpu_to_le16(1);
992                 neh->eh_magic = EXT4_EXT_MAGIC;
993                 neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0));
994                 neh->eh_depth = cpu_to_le16(depth - i);
995                 fidx = EXT_FIRST_INDEX(neh);
996                 fidx->ei_block = border;
997                 ext4_idx_store_pblock(fidx, oldblock);
998
999                 ext_debug("int.index at %d (block %llu): %u -> %llu\n",
1000                                 i, newblock, le32_to_cpu(border), oldblock);
1001
1002                 /* move remainder of path[i] to the new index block */
1003                 if (unlikely(EXT_MAX_INDEX(path[i].p_hdr) !=
1004                                         EXT_LAST_INDEX(path[i].p_hdr))) {
1005                         EXT4_ERROR_INODE(inode,
1006                                          "EXT_MAX_INDEX != EXT_LAST_INDEX ee_block %d!",
1007                                          le32_to_cpu(path[i].p_ext->ee_block));
1008                         err = -EIO;
1009                         goto cleanup;
1010                 }
1011                 /* start copy indexes */
1012                 m = EXT_MAX_INDEX(path[i].p_hdr) - path[i].p_idx++;
1013                 ext_debug("cur 0x%p, last 0x%p\n", path[i].p_idx,
1014                                 EXT_MAX_INDEX(path[i].p_hdr));
1015                 ext4_ext_show_move(inode, path, newblock, i);
1016                 if (m) {
1017                         memmove(++fidx, path[i].p_idx,
1018                                 sizeof(struct ext4_extent_idx) * m);
1019                         le16_add_cpu(&neh->eh_entries, m);
1020                 }
1021                 set_buffer_uptodate(bh);
1022                 unlock_buffer(bh);
1023
1024                 err = ext4_handle_dirty_metadata(handle, inode, bh);
1025                 if (err)
1026                         goto cleanup;
1027                 brelse(bh);
1028                 bh = NULL;
1029
1030                 /* correct old index */
1031                 if (m) {
1032                         err = ext4_ext_get_access(handle, inode, path + i);
1033                         if (err)
1034                                 goto cleanup;
1035                         le16_add_cpu(&path[i].p_hdr->eh_entries, -m);
1036                         err = ext4_ext_dirty(handle, inode, path + i);
1037                         if (err)
1038                                 goto cleanup;
1039                 }
1040
1041                 i--;
1042         }
1043
1044         /* insert new index */
1045         err = ext4_ext_insert_index(handle, inode, path + at,
1046                                     le32_to_cpu(border), newblock);
1047
1048 cleanup:
1049         if (bh) {
1050                 if (buffer_locked(bh))
1051                         unlock_buffer(bh);
1052                 brelse(bh);
1053         }
1054
1055         if (err) {
1056                 /* free all allocated blocks in error case */
1057                 for (i = 0; i < depth; i++) {
1058                         if (!ablocks[i])
1059                                 continue;
1060                         ext4_free_blocks(handle, inode, NULL, ablocks[i], 1,
1061                                          EXT4_FREE_BLOCKS_METADATA);
1062                 }
1063         }
1064         kfree(ablocks);
1065
1066         return err;
1067 }
1068
1069 /*
1070  * ext4_ext_grow_indepth:
1071  * implements tree growing procedure:
1072  * - allocates new block
1073  * - moves top-level data (index block or leaf) into the new block
1074  * - initializes new top-level, creating index that points to the
1075  *   just created block
1076  */
1077 static int ext4_ext_grow_indepth(handle_t *handle, struct inode *inode,
1078                                  unsigned int flags,
1079                                  struct ext4_ext_path *path,
1080                                  struct ext4_extent *newext)
1081 {
1082         struct ext4_ext_path *curp = path;
1083         struct ext4_extent_header *neh;
1084         struct buffer_head *bh;
1085         ext4_fsblk_t newblock;
1086         int err = 0;
1087
1088         newblock = ext4_ext_new_meta_block(handle, inode, path,
1089                 newext, &err, flags);
1090         if (newblock == 0)
1091                 return err;
1092
1093         bh = sb_getblk(inode->i_sb, newblock);
1094         if (!bh) {
1095                 err = -EIO;
1096                 ext4_std_error(inode->i_sb, err);
1097                 return err;
1098         }
1099         lock_buffer(bh);
1100
1101         err = ext4_journal_get_create_access(handle, bh);
1102         if (err) {
1103                 unlock_buffer(bh);
1104                 goto out;
1105         }
1106
1107         /* move top-level index/leaf into new block */
1108         memmove(bh->b_data, curp->p_hdr, sizeof(EXT4_I(inode)->i_data));
1109
1110         /* set size of new block */
1111         neh = ext_block_hdr(bh);
1112         /* old root could have indexes or leaves
1113          * so calculate e_max right way */
1114         if (ext_depth(inode))
1115                 neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0));
1116         else
1117                 neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0));
1118         neh->eh_magic = EXT4_EXT_MAGIC;
1119         set_buffer_uptodate(bh);
1120         unlock_buffer(bh);
1121
1122         err = ext4_handle_dirty_metadata(handle, inode, bh);
1123         if (err)
1124                 goto out;
1125
1126         /* create index in new top-level index: num,max,pointer */
1127         err = ext4_ext_get_access(handle, inode, curp);
1128         if (err)
1129                 goto out;
1130
1131         curp->p_hdr->eh_magic = EXT4_EXT_MAGIC;
1132         curp->p_hdr->eh_max = cpu_to_le16(ext4_ext_space_root_idx(inode, 0));
1133         curp->p_hdr->eh_entries = cpu_to_le16(1);
1134         curp->p_idx = EXT_FIRST_INDEX(curp->p_hdr);
1135
1136         if (path[0].p_hdr->eh_depth)
1137                 curp->p_idx->ei_block =
1138                         EXT_FIRST_INDEX(path[0].p_hdr)->ei_block;
1139         else
1140                 curp->p_idx->ei_block =
1141                         EXT_FIRST_EXTENT(path[0].p_hdr)->ee_block;
1142         ext4_idx_store_pblock(curp->p_idx, newblock);
1143
1144         neh = ext_inode_hdr(inode);
1145         ext_debug("new root: num %d(%d), lblock %d, ptr %llu\n",
1146                   le16_to_cpu(neh->eh_entries), le16_to_cpu(neh->eh_max),
1147                   le32_to_cpu(EXT_FIRST_INDEX(neh)->ei_block),
1148                   ext4_idx_pblock(EXT_FIRST_INDEX(neh)));
1149
1150         neh->eh_depth = cpu_to_le16(path->p_depth + 1);
1151         err = ext4_ext_dirty(handle, inode, curp);
1152 out:
1153         brelse(bh);
1154
1155         return err;
1156 }
1157
1158 /*
1159  * ext4_ext_create_new_leaf:
1160  * finds empty index and adds new leaf.
1161  * if no free index is found, then it requests in-depth growing.
1162  */
1163 static int ext4_ext_create_new_leaf(handle_t *handle, struct inode *inode,
1164                                     unsigned int flags,
1165                                     struct ext4_ext_path *path,
1166                                     struct ext4_extent *newext)
1167 {
1168         struct ext4_ext_path *curp;
1169         int depth, i, err = 0;
1170
1171 repeat:
1172         i = depth = ext_depth(inode);
1173
1174         /* walk up to the tree and look for free index entry */
1175         curp = path + depth;
1176         while (i > 0 && !EXT_HAS_FREE_INDEX(curp)) {
1177                 i--;
1178                 curp--;
1179         }
1180
1181         /* we use already allocated block for index block,
1182          * so subsequent data blocks should be contiguous */
1183         if (EXT_HAS_FREE_INDEX(curp)) {
1184                 /* if we found index with free entry, then use that
1185                  * entry: create all needed subtree and add new leaf */
1186                 err = ext4_ext_split(handle, inode, flags, path, newext, i);
1187                 if (err)
1188                         goto out;
1189
1190                 /* refill path */
1191                 ext4_ext_drop_refs(path);
1192                 path = ext4_ext_find_extent(inode,
1193                                     (ext4_lblk_t)le32_to_cpu(newext->ee_block),
1194                                     path);
1195                 if (IS_ERR(path))
1196                         err = PTR_ERR(path);
1197         } else {
1198                 /* tree is full, time to grow in depth */
1199                 err = ext4_ext_grow_indepth(handle, inode, flags,
1200                                             path, newext);
1201                 if (err)
1202                         goto out;
1203
1204                 /* refill path */
1205                 ext4_ext_drop_refs(path);
1206                 path = ext4_ext_find_extent(inode,
1207                                    (ext4_lblk_t)le32_to_cpu(newext->ee_block),
1208                                     path);
1209                 if (IS_ERR(path)) {
1210                         err = PTR_ERR(path);
1211                         goto out;
1212                 }
1213
1214                 /*
1215                  * only first (depth 0 -> 1) produces free space;
1216                  * in all other cases we have to split the grown tree
1217                  */
1218                 depth = ext_depth(inode);
1219                 if (path[depth].p_hdr->eh_entries == path[depth].p_hdr->eh_max) {
1220                         /* now we need to split */
1221                         goto repeat;
1222                 }
1223         }
1224
1225 out:
1226         return err;
1227 }
1228
1229 /*
1230  * search the closest allocated block to the left for *logical
1231  * and returns it at @logical + it's physical address at @phys
1232  * if *logical is the smallest allocated block, the function
1233  * returns 0 at @phys
1234  * return value contains 0 (success) or error code
1235  */
1236 static int ext4_ext_search_left(struct inode *inode,
1237                                 struct ext4_ext_path *path,
1238                                 ext4_lblk_t *logical, ext4_fsblk_t *phys)
1239 {
1240         struct ext4_extent_idx *ix;
1241         struct ext4_extent *ex;
1242         int depth, ee_len;
1243
1244         if (unlikely(path == NULL)) {
1245                 EXT4_ERROR_INODE(inode, "path == NULL *logical %d!", *logical);
1246                 return -EIO;
1247         }
1248         depth = path->p_depth;
1249         *phys = 0;
1250
1251         if (depth == 0 && path->p_ext == NULL)
1252                 return 0;
1253
1254         /* usually extent in the path covers blocks smaller
1255          * then *logical, but it can be that extent is the
1256          * first one in the file */
1257
1258         ex = path[depth].p_ext;
1259         ee_len = ext4_ext_get_actual_len(ex);
1260         if (*logical < le32_to_cpu(ex->ee_block)) {
1261                 if (unlikely(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex)) {
1262                         EXT4_ERROR_INODE(inode,
1263                                          "EXT_FIRST_EXTENT != ex *logical %d ee_block %d!",
1264                                          *logical, le32_to_cpu(ex->ee_block));
1265                         return -EIO;
1266                 }
1267                 while (--depth >= 0) {
1268                         ix = path[depth].p_idx;
1269                         if (unlikely(ix != EXT_FIRST_INDEX(path[depth].p_hdr))) {
1270                                 EXT4_ERROR_INODE(inode,
1271                                   "ix (%d) != EXT_FIRST_INDEX (%d) (depth %d)!",
1272                                   ix != NULL ? ix->ei_block : 0,
1273                                   EXT_FIRST_INDEX(path[depth].p_hdr) != NULL ?
1274                                     EXT_FIRST_INDEX(path[depth].p_hdr)->ei_block : 0,
1275                                   depth);
1276                                 return -EIO;
1277                         }
1278                 }
1279                 return 0;
1280         }
1281
1282         if (unlikely(*logical < (le32_to_cpu(ex->ee_block) + ee_len))) {
1283                 EXT4_ERROR_INODE(inode,
1284                                  "logical %d < ee_block %d + ee_len %d!",
1285                                  *logical, le32_to_cpu(ex->ee_block), ee_len);
1286                 return -EIO;
1287         }
1288
1289         *logical = le32_to_cpu(ex->ee_block) + ee_len - 1;
1290         *phys = ext4_ext_pblock(ex) + ee_len - 1;
1291         return 0;
1292 }
1293
1294 /*
1295  * search the closest allocated block to the right for *logical
1296  * and returns it at @logical + it's physical address at @phys
1297  * if *logical is the smallest allocated block, the function
1298  * returns 0 at @phys
1299  * return value contains 0 (success) or error code
1300  */
1301 static int ext4_ext_search_right(struct inode *inode,
1302                                  struct ext4_ext_path *path,
1303                                  ext4_lblk_t *logical, ext4_fsblk_t *phys)
1304 {
1305         struct buffer_head *bh = NULL;
1306         struct ext4_extent_header *eh;
1307         struct ext4_extent_idx *ix;
1308         struct ext4_extent *ex;
1309         ext4_fsblk_t block;
1310         int depth;      /* Note, NOT eh_depth; depth from top of tree */
1311         int ee_len;
1312
1313         if (unlikely(path == NULL)) {
1314                 EXT4_ERROR_INODE(inode, "path == NULL *logical %d!", *logical);
1315                 return -EIO;
1316         }
1317         depth = path->p_depth;
1318         *phys = 0;
1319
1320         if (depth == 0 && path->p_ext == NULL)
1321                 return 0;
1322
1323         /* usually extent in the path covers blocks smaller
1324          * then *logical, but it can be that extent is the
1325          * first one in the file */
1326
1327         ex = path[depth].p_ext;
1328         ee_len = ext4_ext_get_actual_len(ex);
1329         if (*logical < le32_to_cpu(ex->ee_block)) {
1330                 if (unlikely(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex)) {
1331                         EXT4_ERROR_INODE(inode,
1332                                          "first_extent(path[%d].p_hdr) != ex",
1333                                          depth);
1334                         return -EIO;
1335                 }
1336                 while (--depth >= 0) {
1337                         ix = path[depth].p_idx;
1338                         if (unlikely(ix != EXT_FIRST_INDEX(path[depth].p_hdr))) {
1339                                 EXT4_ERROR_INODE(inode,
1340                                                  "ix != EXT_FIRST_INDEX *logical %d!",
1341                                                  *logical);
1342                                 return -EIO;
1343                         }
1344                 }
1345                 *logical = le32_to_cpu(ex->ee_block);
1346                 *phys = ext4_ext_pblock(ex);
1347                 return 0;
1348         }
1349
1350         if (unlikely(*logical < (le32_to_cpu(ex->ee_block) + ee_len))) {
1351                 EXT4_ERROR_INODE(inode,
1352                                  "logical %d < ee_block %d + ee_len %d!",
1353                                  *logical, le32_to_cpu(ex->ee_block), ee_len);
1354                 return -EIO;
1355         }
1356
1357         if (ex != EXT_LAST_EXTENT(path[depth].p_hdr)) {
1358                 /* next allocated block in this leaf */
1359                 ex++;
1360                 *logical = le32_to_cpu(ex->ee_block);
1361                 *phys = ext4_ext_pblock(ex);
1362                 return 0;
1363         }
1364
1365         /* go up and search for index to the right */
1366         while (--depth >= 0) {
1367                 ix = path[depth].p_idx;
1368                 if (ix != EXT_LAST_INDEX(path[depth].p_hdr))
1369                         goto got_index;
1370         }
1371
1372         /* we've gone up to the root and found no index to the right */
1373         return 0;
1374
1375 got_index:
1376         /* we've found index to the right, let's
1377          * follow it and find the closest allocated
1378          * block to the right */
1379         ix++;
1380         block = ext4_idx_pblock(ix);
1381         while (++depth < path->p_depth) {
1382                 bh = sb_bread(inode->i_sb, block);
1383                 if (bh == NULL)
1384                         return -EIO;
1385                 eh = ext_block_hdr(bh);
1386                 /* subtract from p_depth to get proper eh_depth */
1387                 if (ext4_ext_check(inode, eh, path->p_depth - depth)) {
1388                         put_bh(bh);
1389                         return -EIO;
1390                 }
1391                 ix = EXT_FIRST_INDEX(eh);
1392                 block = ext4_idx_pblock(ix);
1393                 put_bh(bh);
1394         }
1395
1396         bh = sb_bread(inode->i_sb, block);
1397         if (bh == NULL)
1398                 return -EIO;
1399         eh = ext_block_hdr(bh);
1400         if (ext4_ext_check(inode, eh, path->p_depth - depth)) {
1401                 put_bh(bh);
1402                 return -EIO;
1403         }
1404         ex = EXT_FIRST_EXTENT(eh);
1405         *logical = le32_to_cpu(ex->ee_block);
1406         *phys = ext4_ext_pblock(ex);
1407         put_bh(bh);
1408         return 0;
1409 }
1410
1411 /*
1412  * ext4_ext_next_allocated_block:
1413  * returns allocated block in subsequent extent or EXT_MAX_BLOCKS.
1414  * NOTE: it considers block number from index entry as
1415  * allocated block. Thus, index entries have to be consistent
1416  * with leaves.
1417  */
1418 static ext4_lblk_t
1419 ext4_ext_next_allocated_block(struct ext4_ext_path *path)
1420 {
1421         int depth;
1422
1423         BUG_ON(path == NULL);
1424         depth = path->p_depth;
1425
1426         if (depth == 0 && path->p_ext == NULL)
1427                 return EXT_MAX_BLOCKS;
1428
1429         while (depth >= 0) {
1430                 if (depth == path->p_depth) {
1431                         /* leaf */
1432                         if (path[depth].p_ext !=
1433                                         EXT_LAST_EXTENT(path[depth].p_hdr))
1434                           return le32_to_cpu(path[depth].p_ext[1].ee_block);
1435                 } else {
1436                         /* index */
1437                         if (path[depth].p_idx !=
1438                                         EXT_LAST_INDEX(path[depth].p_hdr))
1439                           return le32_to_cpu(path[depth].p_idx[1].ei_block);
1440                 }
1441                 depth--;
1442         }
1443
1444         return EXT_MAX_BLOCKS;
1445 }
1446
1447 /*
1448  * ext4_ext_next_leaf_block:
1449  * returns first allocated block from next leaf or EXT_MAX_BLOCKS
1450  */
1451 static ext4_lblk_t ext4_ext_next_leaf_block(struct inode *inode,
1452                                         struct ext4_ext_path *path)
1453 {
1454         int depth;
1455
1456         BUG_ON(path == NULL);
1457         depth = path->p_depth;
1458
1459         /* zero-tree has no leaf blocks at all */
1460         if (depth == 0)
1461                 return EXT_MAX_BLOCKS;
1462
1463         /* go to index block */
1464         depth--;
1465
1466         while (depth >= 0) {
1467                 if (path[depth].p_idx !=
1468                                 EXT_LAST_INDEX(path[depth].p_hdr))
1469                         return (ext4_lblk_t)
1470                                 le32_to_cpu(path[depth].p_idx[1].ei_block);
1471                 depth--;
1472         }
1473
1474         return EXT_MAX_BLOCKS;
1475 }
1476
1477 /*
1478  * ext4_ext_correct_indexes:
1479  * if leaf gets modified and modified extent is first in the leaf,
1480  * then we have to correct all indexes above.
1481  * TODO: do we need to correct tree in all cases?
1482  */
1483 static int ext4_ext_correct_indexes(handle_t *handle, struct inode *inode,
1484                                 struct ext4_ext_path *path)
1485 {
1486         struct ext4_extent_header *eh;
1487         int depth = ext_depth(inode);
1488         struct ext4_extent *ex;
1489         __le32 border;
1490         int k, err = 0;
1491
1492         eh = path[depth].p_hdr;
1493         ex = path[depth].p_ext;
1494
1495         if (unlikely(ex == NULL || eh == NULL)) {
1496                 EXT4_ERROR_INODE(inode,
1497                                  "ex %p == NULL or eh %p == NULL", ex, eh);
1498                 return -EIO;
1499         }
1500
1501         if (depth == 0) {
1502                 /* there is no tree at all */
1503                 return 0;
1504         }
1505
1506         if (ex != EXT_FIRST_EXTENT(eh)) {
1507                 /* we correct tree if first leaf got modified only */
1508                 return 0;
1509         }
1510
1511         /*
1512          * TODO: we need correction if border is smaller than current one
1513          */
1514         k = depth - 1;
1515         border = path[depth].p_ext->ee_block;
1516         err = ext4_ext_get_access(handle, inode, path + k);
1517         if (err)
1518                 return err;
1519         path[k].p_idx->ei_block = border;
1520         err = ext4_ext_dirty(handle, inode, path + k);
1521         if (err)
1522                 return err;
1523
1524         while (k--) {
1525                 /* change all left-side indexes */
1526                 if (path[k+1].p_idx != EXT_FIRST_INDEX(path[k+1].p_hdr))
1527                         break;
1528                 err = ext4_ext_get_access(handle, inode, path + k);
1529                 if (err)
1530                         break;
1531                 path[k].p_idx->ei_block = border;
1532                 err = ext4_ext_dirty(handle, inode, path + k);
1533                 if (err)
1534                         break;
1535         }
1536
1537         return err;
1538 }
1539
1540 int
1541 ext4_can_extents_be_merged(struct inode *inode, struct ext4_extent *ex1,
1542                                 struct ext4_extent *ex2)
1543 {
1544         unsigned short ext1_ee_len, ext2_ee_len, max_len;
1545
1546         /*
1547          * Make sure that either both extents are uninitialized, or
1548          * both are _not_.
1549          */
1550         if (ext4_ext_is_uninitialized(ex1) ^ ext4_ext_is_uninitialized(ex2))
1551                 return 0;
1552
1553         if (ext4_ext_is_uninitialized(ex1))
1554                 max_len = EXT_UNINIT_MAX_LEN;
1555         else
1556                 max_len = EXT_INIT_MAX_LEN;
1557
1558         ext1_ee_len = ext4_ext_get_actual_len(ex1);
1559         ext2_ee_len = ext4_ext_get_actual_len(ex2);
1560
1561         if (le32_to_cpu(ex1->ee_block) + ext1_ee_len !=
1562                         le32_to_cpu(ex2->ee_block))
1563                 return 0;
1564
1565         /*
1566          * To allow future support for preallocated extents to be added
1567          * as an RO_COMPAT feature, refuse to merge to extents if
1568          * this can result in the top bit of ee_len being set.
1569          */
1570         if (ext1_ee_len + ext2_ee_len > max_len)
1571                 return 0;
1572 #ifdef AGGRESSIVE_TEST
1573         if (ext1_ee_len >= 4)
1574                 return 0;
1575 #endif
1576
1577         if (ext4_ext_pblock(ex1) + ext1_ee_len == ext4_ext_pblock(ex2))
1578                 return 1;
1579         return 0;
1580 }
1581
1582 /*
1583  * This function tries to merge the "ex" extent to the next extent in the tree.
1584  * It always tries to merge towards right. If you want to merge towards
1585  * left, pass "ex - 1" as argument instead of "ex".
1586  * Returns 0 if the extents (ex and ex+1) were _not_ merged and returns
1587  * 1 if they got merged.
1588  */
1589 static int ext4_ext_try_to_merge_right(struct inode *inode,
1590                                  struct ext4_ext_path *path,
1591                                  struct ext4_extent *ex)
1592 {
1593         struct ext4_extent_header *eh;
1594         unsigned int depth, len;
1595         int merge_done = 0;
1596         int uninitialized = 0;
1597
1598         depth = ext_depth(inode);
1599         BUG_ON(path[depth].p_hdr == NULL);
1600         eh = path[depth].p_hdr;
1601
1602         while (ex < EXT_LAST_EXTENT(eh)) {
1603                 if (!ext4_can_extents_be_merged(inode, ex, ex + 1))
1604                         break;
1605                 /* merge with next extent! */
1606                 if (ext4_ext_is_uninitialized(ex))
1607                         uninitialized = 1;
1608                 ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
1609                                 + ext4_ext_get_actual_len(ex + 1));
1610                 if (uninitialized)
1611                         ext4_ext_mark_uninitialized(ex);
1612
1613                 if (ex + 1 < EXT_LAST_EXTENT(eh)) {
1614                         len = (EXT_LAST_EXTENT(eh) - ex - 1)
1615                                 * sizeof(struct ext4_extent);
1616                         memmove(ex + 1, ex + 2, len);
1617                 }
1618                 le16_add_cpu(&eh->eh_entries, -1);
1619                 merge_done = 1;
1620                 WARN_ON(eh->eh_entries == 0);
1621                 if (!eh->eh_entries)
1622                         EXT4_ERROR_INODE(inode, "eh->eh_entries = 0!");
1623         }
1624
1625         return merge_done;
1626 }
1627
1628 /*
1629  * This function tries to merge the @ex extent to neighbours in the tree.
1630  * return 1 if merge left else 0.
1631  */
1632 static int ext4_ext_try_to_merge(struct inode *inode,
1633                                   struct ext4_ext_path *path,
1634                                   struct ext4_extent *ex) {
1635         struct ext4_extent_header *eh;
1636         unsigned int depth;
1637         int merge_done = 0;
1638         int ret = 0;
1639
1640         depth = ext_depth(inode);
1641         BUG_ON(path[depth].p_hdr == NULL);
1642         eh = path[depth].p_hdr;
1643
1644         if (ex > EXT_FIRST_EXTENT(eh))
1645                 merge_done = ext4_ext_try_to_merge_right(inode, path, ex - 1);
1646
1647         if (!merge_done)
1648                 ret = ext4_ext_try_to_merge_right(inode, path, ex);
1649
1650         return ret;
1651 }
1652
1653 /*
1654  * check if a portion of the "newext" extent overlaps with an
1655  * existing extent.
1656  *
1657  * If there is an overlap discovered, it updates the length of the newext
1658  * such that there will be no overlap, and then returns 1.
1659  * If there is no overlap found, it returns 0.
1660  */
1661 static unsigned int ext4_ext_check_overlap(struct inode *inode,
1662                                            struct ext4_extent *newext,
1663                                            struct ext4_ext_path *path)
1664 {
1665         ext4_lblk_t b1, b2;
1666         unsigned int depth, len1;
1667         unsigned int ret = 0;
1668
1669         b1 = le32_to_cpu(newext->ee_block);
1670         len1 = ext4_ext_get_actual_len(newext);
1671         depth = ext_depth(inode);
1672         if (!path[depth].p_ext)
1673                 goto out;
1674         b2 = le32_to_cpu(path[depth].p_ext->ee_block);
1675
1676         /*
1677          * get the next allocated block if the extent in the path
1678          * is before the requested block(s)
1679          */
1680         if (b2 < b1) {
1681                 b2 = ext4_ext_next_allocated_block(path);
1682                 if (b2 == EXT_MAX_BLOCKS)
1683                         goto out;
1684         }
1685
1686         /* check for wrap through zero on extent logical start block*/
1687         if (b1 + len1 < b1) {
1688                 len1 = EXT_MAX_BLOCKS - b1;
1689                 newext->ee_len = cpu_to_le16(len1);
1690                 ret = 1;
1691         }
1692
1693         /* check for overlap */
1694         if (b1 + len1 > b2) {
1695                 newext->ee_len = cpu_to_le16(b2 - b1);
1696                 ret = 1;
1697         }
1698 out:
1699         return ret;
1700 }
1701
1702 /*
1703  * ext4_ext_insert_extent:
1704  * tries to merge requsted extent into the existing extent or
1705  * inserts requested extent as new one into the tree,
1706  * creating new leaf in the no-space case.
1707  */
1708 int ext4_ext_insert_extent(handle_t *handle, struct inode *inode,
1709                                 struct ext4_ext_path *path,
1710                                 struct ext4_extent *newext, int flag)
1711 {
1712         struct ext4_extent_header *eh;
1713         struct ext4_extent *ex, *fex;
1714         struct ext4_extent *nearex; /* nearest extent */
1715         struct ext4_ext_path *npath = NULL;
1716         int depth, len, err;
1717         ext4_lblk_t next;
1718         unsigned uninitialized = 0;
1719         int flags = 0;
1720
1721         if (unlikely(ext4_ext_get_actual_len(newext) == 0)) {
1722                 EXT4_ERROR_INODE(inode, "ext4_ext_get_actual_len(newext) == 0");
1723                 return -EIO;
1724         }
1725         depth = ext_depth(inode);
1726         ex = path[depth].p_ext;
1727         if (unlikely(path[depth].p_hdr == NULL)) {
1728                 EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
1729                 return -EIO;
1730         }
1731
1732         /* try to insert block into found extent and return */
1733         if (ex && !(flag & EXT4_GET_BLOCKS_PRE_IO)
1734                 && ext4_can_extents_be_merged(inode, ex, newext)) {
1735                 ext_debug("append [%d]%d block to %d:[%d]%d (from %llu)\n",
1736                           ext4_ext_is_uninitialized(newext),
1737                           ext4_ext_get_actual_len(newext),
1738                           le32_to_cpu(ex->ee_block),
1739                           ext4_ext_is_uninitialized(ex),
1740                           ext4_ext_get_actual_len(ex),
1741                           ext4_ext_pblock(ex));
1742                 err = ext4_ext_get_access(handle, inode, path + depth);
1743                 if (err)
1744                         return err;
1745
1746                 /*
1747                  * ext4_can_extents_be_merged should have checked that either
1748                  * both extents are uninitialized, or both aren't. Thus we
1749                  * need to check only one of them here.
1750                  */
1751                 if (ext4_ext_is_uninitialized(ex))
1752                         uninitialized = 1;
1753                 ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
1754                                         + ext4_ext_get_actual_len(newext));
1755                 if (uninitialized)
1756                         ext4_ext_mark_uninitialized(ex);
1757                 eh = path[depth].p_hdr;
1758                 nearex = ex;
1759                 goto merge;
1760         }
1761
1762 repeat:
1763         depth = ext_depth(inode);
1764         eh = path[depth].p_hdr;
1765         if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max))
1766                 goto has_space;
1767
1768         /* probably next leaf has space for us? */
1769         fex = EXT_LAST_EXTENT(eh);
1770         next = ext4_ext_next_leaf_block(inode, path);
1771         if (le32_to_cpu(newext->ee_block) > le32_to_cpu(fex->ee_block)
1772             && next != EXT_MAX_BLOCKS) {
1773                 ext_debug("next leaf block - %d\n", next);
1774                 BUG_ON(npath != NULL);
1775                 npath = ext4_ext_find_extent(inode, next, NULL);
1776                 if (IS_ERR(npath))
1777                         return PTR_ERR(npath);
1778                 BUG_ON(npath->p_depth != path->p_depth);
1779                 eh = npath[depth].p_hdr;
1780                 if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max)) {
1781                         ext_debug("next leaf isn't full(%d)\n",
1782                                   le16_to_cpu(eh->eh_entries));
1783                         path = npath;
1784                         goto repeat;
1785                 }
1786                 ext_debug("next leaf has no free space(%d,%d)\n",
1787                           le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
1788         }
1789
1790         /*
1791          * There is no free space in the found leaf.
1792          * We're gonna add a new leaf in the tree.
1793          */
1794         if (flag & EXT4_GET_BLOCKS_PUNCH_OUT_EXT)
1795                 flags = EXT4_MB_USE_ROOT_BLOCKS;
1796         err = ext4_ext_create_new_leaf(handle, inode, flags, path, newext);
1797         if (err)
1798                 goto cleanup;
1799         depth = ext_depth(inode);
1800         eh = path[depth].p_hdr;
1801
1802 has_space:
1803         nearex = path[depth].p_ext;
1804
1805         err = ext4_ext_get_access(handle, inode, path + depth);
1806         if (err)
1807                 goto cleanup;
1808
1809         if (!nearex) {
1810                 /* there is no extent in this leaf, create first one */
1811                 ext_debug("first extent in the leaf: %d:%llu:[%d]%d\n",
1812                                 le32_to_cpu(newext->ee_block),
1813                                 ext4_ext_pblock(newext),
1814                                 ext4_ext_is_uninitialized(newext),
1815                                 ext4_ext_get_actual_len(newext));
1816                 path[depth].p_ext = EXT_FIRST_EXTENT(eh);
1817         } else if (le32_to_cpu(newext->ee_block)
1818                            > le32_to_cpu(nearex->ee_block)) {
1819 /*              BUG_ON(newext->ee_block == nearex->ee_block); */
1820                 if (nearex != EXT_LAST_EXTENT(eh)) {
1821                         len = EXT_MAX_EXTENT(eh) - nearex;
1822                         len = (len - 1) * sizeof(struct ext4_extent);
1823                         len = len < 0 ? 0 : len;
1824                         ext_debug("insert %d:%llu:[%d]%d after: nearest 0x%p, "
1825                                         "move %d from 0x%p to 0x%p\n",
1826                                         le32_to_cpu(newext->ee_block),
1827                                         ext4_ext_pblock(newext),
1828                                         ext4_ext_is_uninitialized(newext),
1829                                         ext4_ext_get_actual_len(newext),
1830                                         nearex, len, nearex + 1, nearex + 2);
1831                         memmove(nearex + 2, nearex + 1, len);
1832                 }
1833                 path[depth].p_ext = nearex + 1;
1834         } else {
1835                 BUG_ON(newext->ee_block == nearex->ee_block);
1836                 len = (EXT_MAX_EXTENT(eh) - nearex) * sizeof(struct ext4_extent);
1837                 len = len < 0 ? 0 : len;
1838                 ext_debug("insert %d:%llu:[%d]%d before: nearest 0x%p, "
1839                                 "move %d from 0x%p to 0x%p\n",
1840                                 le32_to_cpu(newext->ee_block),
1841                                 ext4_ext_pblock(newext),
1842                                 ext4_ext_is_uninitialized(newext),
1843                                 ext4_ext_get_actual_len(newext),
1844                                 nearex, len, nearex + 1, nearex + 2);
1845                 memmove(nearex + 1, nearex, len);
1846                 path[depth].p_ext = nearex;
1847         }
1848
1849         le16_add_cpu(&eh->eh_entries, 1);
1850         nearex = path[depth].p_ext;
1851         nearex->ee_block = newext->ee_block;
1852         ext4_ext_store_pblock(nearex, ext4_ext_pblock(newext));
1853         nearex->ee_len = newext->ee_len;
1854
1855 merge:
1856         /* try to merge extents to the right */
1857         if (!(flag & EXT4_GET_BLOCKS_PRE_IO))
1858                 ext4_ext_try_to_merge(inode, path, nearex);
1859
1860         /* try to merge extents to the left */
1861
1862         /* time to correct all indexes above */
1863         err = ext4_ext_correct_indexes(handle, inode, path);
1864         if (err)
1865                 goto cleanup;
1866
1867         err = ext4_ext_dirty(handle, inode, path + depth);
1868
1869 cleanup:
1870         if (npath) {
1871                 ext4_ext_drop_refs(npath);
1872                 kfree(npath);
1873         }
1874         ext4_ext_invalidate_cache(inode);
1875         return err;
1876 }
1877
1878 static int ext4_ext_walk_space(struct inode *inode, ext4_lblk_t block,
1879                                ext4_lblk_t num, ext_prepare_callback func,
1880                                void *cbdata)
1881 {
1882         struct ext4_ext_path *path = NULL;
1883         struct ext4_ext_cache cbex;
1884         struct ext4_extent *ex;
1885         ext4_lblk_t next, start = 0, end = 0;
1886         ext4_lblk_t last = block + num;
1887         int depth, exists, err = 0;
1888
1889         BUG_ON(func == NULL);
1890         BUG_ON(inode == NULL);
1891
1892         while (block < last && block != EXT_MAX_BLOCKS) {
1893                 num = last - block;
1894                 /* find extent for this block */
1895                 down_read(&EXT4_I(inode)->i_data_sem);
1896                 path = ext4_ext_find_extent(inode, block, path);
1897                 up_read(&EXT4_I(inode)->i_data_sem);
1898                 if (IS_ERR(path)) {
1899                         err = PTR_ERR(path);
1900                         path = NULL;
1901                         break;
1902                 }
1903
1904                 depth = ext_depth(inode);
1905                 if (unlikely(path[depth].p_hdr == NULL)) {
1906                         EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
1907                         err = -EIO;
1908                         break;
1909                 }
1910                 ex = path[depth].p_ext;
1911                 next = ext4_ext_next_allocated_block(path);
1912
1913                 exists = 0;
1914                 if (!ex) {
1915                         /* there is no extent yet, so try to allocate
1916                          * all requested space */
1917                         start = block;
1918                         end = block + num;
1919                 } else if (le32_to_cpu(ex->ee_block) > block) {
1920                         /* need to allocate space before found extent */
1921                         start = block;
1922                         end = le32_to_cpu(ex->ee_block);
1923                         if (block + num < end)
1924                                 end = block + num;
1925                 } else if (block >= le32_to_cpu(ex->ee_block)
1926                                         + ext4_ext_get_actual_len(ex)) {
1927                         /* need to allocate space after found extent */
1928                         start = block;
1929                         end = block + num;
1930                         if (end >= next)
1931                                 end = next;
1932                 } else if (block >= le32_to_cpu(ex->ee_block)) {
1933                         /*
1934                          * some part of requested space is covered
1935                          * by found extent
1936                          */
1937                         start = block;
1938                         end = le32_to_cpu(ex->ee_block)
1939                                 + ext4_ext_get_actual_len(ex);
1940                         if (block + num < end)
1941                                 end = block + num;
1942                         exists = 1;
1943                 } else {
1944                         BUG();
1945                 }
1946                 BUG_ON(end <= start);
1947
1948                 if (!exists) {
1949                         cbex.ec_block = start;
1950                         cbex.ec_len = end - start;
1951                         cbex.ec_start = 0;
1952                 } else {
1953                         cbex.ec_block = le32_to_cpu(ex->ee_block);
1954                         cbex.ec_len = ext4_ext_get_actual_len(ex);
1955                         cbex.ec_start = ext4_ext_pblock(ex);
1956                 }
1957
1958                 if (unlikely(cbex.ec_len == 0)) {
1959                         EXT4_ERROR_INODE(inode, "cbex.ec_len == 0");
1960                         err = -EIO;
1961                         break;
1962                 }
1963                 err = func(inode, next, &cbex, ex, cbdata);
1964                 ext4_ext_drop_refs(path);
1965
1966                 if (err < 0)
1967                         break;
1968
1969                 if (err == EXT_REPEAT)
1970                         continue;
1971                 else if (err == EXT_BREAK) {
1972                         err = 0;
1973                         break;
1974                 }
1975
1976                 if (ext_depth(inode) != depth) {
1977                         /* depth was changed. we have to realloc path */
1978                         kfree(path);
1979                         path = NULL;
1980                 }
1981
1982                 block = cbex.ec_block + cbex.ec_len;
1983         }
1984
1985         if (path) {
1986                 ext4_ext_drop_refs(path);
1987                 kfree(path);
1988         }
1989
1990         return err;
1991 }
1992
1993 static void
1994 ext4_ext_put_in_cache(struct inode *inode, ext4_lblk_t block,
1995                         __u32 len, ext4_fsblk_t start)
1996 {
1997         struct ext4_ext_cache *cex;
1998         BUG_ON(len == 0);
1999         spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
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_in_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         if (!ret)
2098                 sbi->extent_cache_misses++;
2099         else
2100                 sbi->extent_cache_hits++;
2101         spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
2102         return ret;
2103 }
2104
2105 /*
2106  * ext4_ext_in_cache()
2107  * Checks to see if the given block is in the cache.
2108  * If it is, the cached extent is stored in the given
2109  * extent pointer.
2110  *
2111  * @inode: The files inode
2112  * @block: The block to look for in the cache
2113  * @ex:    Pointer where the cached extent will be stored
2114  *         if it contains block
2115  *
2116  * Return 0 if cache is invalid; 1 if the cache is valid
2117  */
2118 static int
2119 ext4_ext_in_cache(struct inode *inode, ext4_lblk_t block,
2120                         struct ext4_extent *ex)
2121 {
2122         struct ext4_ext_cache cex;
2123         int ret = 0;
2124
2125         if (ext4_ext_check_cache(inode, block, &cex)) {
2126                 ex->ee_block = cpu_to_le32(cex.ec_block);
2127                 ext4_ext_store_pblock(ex, cex.ec_start);
2128                 ex->ee_len = cpu_to_le16(cex.ec_len);
2129                 ret = 1;
2130         }
2131
2132         return ret;
2133 }
2134
2135
2136 /*
2137  * ext4_ext_rm_idx:
2138  * removes index from the index block.
2139  * It's used in truncate case only, thus all requests are for
2140  * last index in the block only.
2141  */
2142 static int ext4_ext_rm_idx(handle_t *handle, struct inode *inode,
2143                         struct ext4_ext_path *path)
2144 {
2145         int err;
2146         ext4_fsblk_t leaf;
2147
2148         /* free index block */
2149         path--;
2150         leaf = ext4_idx_pblock(path->p_idx);
2151         if (unlikely(path->p_hdr->eh_entries == 0)) {
2152                 EXT4_ERROR_INODE(inode, "path->p_hdr->eh_entries == 0");
2153                 return -EIO;
2154         }
2155         err = ext4_ext_get_access(handle, inode, path);
2156         if (err)
2157                 return err;
2158         le16_add_cpu(&path->p_hdr->eh_entries, -1);
2159         err = ext4_ext_dirty(handle, inode, path);
2160         if (err)
2161                 return err;
2162         ext_debug("index is empty, remove it, free block %llu\n", leaf);
2163         ext4_free_blocks(handle, inode, NULL, leaf, 1,
2164                          EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET);
2165         return err;
2166 }
2167
2168 /*
2169  * ext4_ext_calc_credits_for_single_extent:
2170  * This routine returns max. credits that needed to insert an extent
2171  * to the extent tree.
2172  * When pass the actual path, the caller should calculate credits
2173  * under i_data_sem.
2174  */
2175 int ext4_ext_calc_credits_for_single_extent(struct inode *inode, int nrblocks,
2176                                                 struct ext4_ext_path *path)
2177 {
2178         if (path) {
2179                 int depth = ext_depth(inode);
2180                 int ret = 0;
2181
2182                 /* probably there is space in leaf? */
2183                 if (le16_to_cpu(path[depth].p_hdr->eh_entries)
2184                                 < le16_to_cpu(path[depth].p_hdr->eh_max)) {
2185
2186                         /*
2187                          *  There are some space in the leaf tree, no
2188                          *  need to account for leaf block credit
2189                          *
2190                          *  bitmaps and block group descriptor blocks
2191                          *  and other metadat blocks still need to be
2192                          *  accounted.
2193                          */
2194                         /* 1 bitmap, 1 block group descriptor */
2195                         ret = 2 + EXT4_META_TRANS_BLOCKS(inode->i_sb);
2196                         return ret;
2197                 }
2198         }
2199
2200         return ext4_chunk_trans_blocks(inode, nrblocks);
2201 }
2202
2203 /*
2204  * How many index/leaf blocks need to change/allocate to modify nrblocks?
2205  *
2206  * if nrblocks are fit in a single extent (chunk flag is 1), then
2207  * in the worse case, each tree level index/leaf need to be changed
2208  * if the tree split due to insert a new extent, then the old tree
2209  * index/leaf need to be updated too
2210  *
2211  * If the nrblocks are discontiguous, they could cause
2212  * the whole tree split more than once, but this is really rare.
2213  */
2214 int ext4_ext_index_trans_blocks(struct inode *inode, int nrblocks, int chunk)
2215 {
2216         int index;
2217         int depth = ext_depth(inode);
2218
2219         if (chunk)
2220                 index = depth * 2;
2221         else
2222                 index = depth * 3;
2223
2224         return index;
2225 }
2226
2227 static int ext4_remove_blocks(handle_t *handle, struct inode *inode,
2228                                 struct ext4_extent *ex,
2229                                 ext4_lblk_t from, ext4_lblk_t to)
2230 {
2231         unsigned short ee_len =  ext4_ext_get_actual_len(ex);
2232         int flags = EXT4_FREE_BLOCKS_FORGET;
2233
2234         if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode))
2235                 flags |= EXT4_FREE_BLOCKS_METADATA;
2236 #ifdef EXTENTS_STATS
2237         {
2238                 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2239                 spin_lock(&sbi->s_ext_stats_lock);
2240                 sbi->s_ext_blocks += ee_len;
2241                 sbi->s_ext_extents++;
2242                 if (ee_len < sbi->s_ext_min)
2243                         sbi->s_ext_min = ee_len;
2244                 if (ee_len > sbi->s_ext_max)
2245                         sbi->s_ext_max = ee_len;
2246                 if (ext_depth(inode) > sbi->s_depth_max)
2247                         sbi->s_depth_max = ext_depth(inode);
2248                 spin_unlock(&sbi->s_ext_stats_lock);
2249         }
2250 #endif
2251         if (from >= le32_to_cpu(ex->ee_block)
2252             && to == le32_to_cpu(ex->ee_block) + ee_len - 1) {
2253                 /* tail removal */
2254                 ext4_lblk_t num;
2255                 ext4_fsblk_t start;
2256
2257                 num = le32_to_cpu(ex->ee_block) + ee_len - from;
2258                 start = ext4_ext_pblock(ex) + ee_len - num;
2259                 ext_debug("free last %u blocks starting %llu\n", num, start);
2260                 ext4_free_blocks(handle, inode, NULL, start, num, flags);
2261         } else if (from == le32_to_cpu(ex->ee_block)
2262                    && to <= le32_to_cpu(ex->ee_block) + ee_len - 1) {
2263                 /* head removal */
2264                 ext4_lblk_t num;
2265                 ext4_fsblk_t start;
2266
2267                 num = to - from;
2268                 start = ext4_ext_pblock(ex);
2269
2270                 ext_debug("free first %u blocks starting %llu\n", num, start);
2271                 ext4_free_blocks(handle, inode, 0, start, num, flags);
2272
2273         } else {
2274                 printk(KERN_INFO "strange request: removal(2) "
2275                                 "%u-%u from %u:%u\n",
2276                                 from, to, le32_to_cpu(ex->ee_block), ee_len);
2277         }
2278         return 0;
2279 }
2280
2281
2282 /*
2283  * ext4_ext_rm_leaf() Removes the extents associated with the
2284  * blocks appearing between "start" and "end", and splits the extents
2285  * if "start" and "end" appear in the same extent
2286  *
2287  * @handle: The journal handle
2288  * @inode:  The files inode
2289  * @path:   The path to the leaf
2290  * @start:  The first block to remove
2291  * @end:   The last block to remove
2292  */
2293 static int
2294 ext4_ext_rm_leaf(handle_t *handle, struct inode *inode,
2295                 struct ext4_ext_path *path, ext4_lblk_t start,
2296                 ext4_lblk_t end)
2297 {
2298         int err = 0, correct_index = 0;
2299         int depth = ext_depth(inode), credits;
2300         struct ext4_extent_header *eh;
2301         ext4_lblk_t a, b, block;
2302         unsigned num;
2303         ext4_lblk_t ex_ee_block;
2304         unsigned short ex_ee_len;
2305         unsigned uninitialized = 0;
2306         struct ext4_extent *ex;
2307         struct ext4_map_blocks map;
2308
2309         /* the header must be checked already in ext4_ext_remove_space() */
2310         ext_debug("truncate since %u in leaf\n", start);
2311         if (!path[depth].p_hdr)
2312                 path[depth].p_hdr = ext_block_hdr(path[depth].p_bh);
2313         eh = path[depth].p_hdr;
2314         if (unlikely(path[depth].p_hdr == NULL)) {
2315                 EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
2316                 return -EIO;
2317         }
2318         /* find where to start removing */
2319         ex = EXT_LAST_EXTENT(eh);
2320
2321         ex_ee_block = le32_to_cpu(ex->ee_block);
2322         ex_ee_len = ext4_ext_get_actual_len(ex);
2323
2324         while (ex >= EXT_FIRST_EXTENT(eh) &&
2325                         ex_ee_block + ex_ee_len > start) {
2326
2327                 if (ext4_ext_is_uninitialized(ex))
2328                         uninitialized = 1;
2329                 else
2330                         uninitialized = 0;
2331
2332                 ext_debug("remove ext %u:[%d]%d\n", ex_ee_block,
2333                          uninitialized, ex_ee_len);
2334                 path[depth].p_ext = ex;
2335
2336                 a = ex_ee_block > start ? ex_ee_block : start;
2337                 b = ex_ee_block+ex_ee_len - 1 < end ?
2338                         ex_ee_block+ex_ee_len - 1 : end;
2339
2340                 ext_debug("  border %u:%u\n", a, b);
2341
2342                 /* If this extent is beyond the end of the hole, skip it */
2343                 if (end <= ex_ee_block) {
2344                         ex--;
2345                         ex_ee_block = le32_to_cpu(ex->ee_block);
2346                         ex_ee_len = ext4_ext_get_actual_len(ex);
2347                         continue;
2348                 } else if (a != ex_ee_block &&
2349                         b != ex_ee_block + ex_ee_len - 1) {
2350                         /*
2351                          * If this is a truncate, then this condition should
2352                          * never happen because at least one of the end points
2353                          * needs to be on the edge of the extent.
2354                          */
2355                         if (end == EXT_MAX_BLOCKS - 1) {
2356                                 ext_debug("  bad truncate %u:%u\n",
2357                                                 start, end);
2358                                 block = 0;
2359                                 num = 0;
2360                                 err = -EIO;
2361                                 goto out;
2362                         }
2363                         /*
2364                          * else this is a hole punch, so the extent needs to
2365                          * be split since neither edge of the hole is on the
2366                          * extent edge
2367                          */
2368                         else{
2369                                 map.m_pblk = ext4_ext_pblock(ex);
2370                                 map.m_lblk = ex_ee_block;
2371                                 map.m_len = b - ex_ee_block;
2372
2373                                 err = ext4_split_extent(handle,
2374                                         inode, path, &map, 0,
2375                                         EXT4_GET_BLOCKS_PUNCH_OUT_EXT |
2376                                         EXT4_GET_BLOCKS_PRE_IO);
2377
2378                                 if (err < 0)
2379                                         goto out;
2380
2381                                 ex_ee_len = ext4_ext_get_actual_len(ex);
2382
2383                                 b = ex_ee_block+ex_ee_len - 1 < end ?
2384                                         ex_ee_block+ex_ee_len - 1 : end;
2385
2386                                 /* Then remove tail of this extent */
2387                                 block = ex_ee_block;
2388                                 num = a - block;
2389                         }
2390                 } else if (a != ex_ee_block) {
2391                         /* remove tail of the extent */
2392                         block = ex_ee_block;
2393                         num = a - block;
2394                 } else if (b != ex_ee_block + ex_ee_len - 1) {
2395                         /* remove head of the extent */
2396                         block = b;
2397                         num =  ex_ee_block + ex_ee_len - b;
2398
2399                         /*
2400                          * If this is a truncate, this condition
2401                          * should never happen
2402                          */
2403                         if (end == EXT_MAX_BLOCKS - 1) {
2404                                 ext_debug("  bad truncate %u:%u\n",
2405                                         start, end);
2406                                 err = -EIO;
2407                                 goto out;
2408                         }
2409                 } else {
2410                         /* remove whole extent: excellent! */
2411                         block = ex_ee_block;
2412                         num = 0;
2413                         if (a != ex_ee_block) {
2414                                 ext_debug("  bad truncate %u:%u\n",
2415                                         start, end);
2416                                 err = -EIO;
2417                                 goto out;
2418                         }
2419
2420                         if (b != ex_ee_block + ex_ee_len - 1) {
2421                                 ext_debug("  bad truncate %u:%u\n",
2422                                         start, end);
2423                                 err = -EIO;
2424                                 goto out;
2425                         }
2426                 }
2427
2428                 /*
2429                  * 3 for leaf, sb, and inode plus 2 (bmap and group
2430                  * descriptor) for each block group; assume two block
2431                  * groups plus ex_ee_len/blocks_per_block_group for
2432                  * the worst case
2433                  */
2434                 credits = 7 + 2*(ex_ee_len/EXT4_BLOCKS_PER_GROUP(inode->i_sb));
2435                 if (ex == EXT_FIRST_EXTENT(eh)) {
2436                         correct_index = 1;
2437                         credits += (ext_depth(inode)) + 1;
2438                 }
2439                 credits += EXT4_MAXQUOTAS_TRANS_BLOCKS(inode->i_sb);
2440
2441                 err = ext4_ext_truncate_extend_restart(handle, inode, credits);
2442                 if (err)
2443                         goto out;
2444
2445                 err = ext4_ext_get_access(handle, inode, path + depth);
2446                 if (err)
2447                         goto out;
2448
2449                 err = ext4_remove_blocks(handle, inode, ex, a, b);
2450                 if (err)
2451                         goto out;
2452
2453                 if (num == 0) {
2454                         /* this extent is removed; mark slot entirely unused */
2455                         ext4_ext_store_pblock(ex, 0);
2456                 } else if (block != ex_ee_block) {
2457                         /*
2458                          * If this was a head removal, then we need to update
2459                          * the physical block since it is now at a different
2460                          * location
2461                          */
2462                         ext4_ext_store_pblock(ex, ext4_ext_pblock(ex) + (b-a));
2463                 }
2464
2465                 ex->ee_block = cpu_to_le32(block);
2466                 ex->ee_len = cpu_to_le16(num);
2467                 /*
2468                  * Do not mark uninitialized if all the blocks in the
2469                  * extent have been removed.
2470                  */
2471                 if (uninitialized && num)
2472                         ext4_ext_mark_uninitialized(ex);
2473
2474                 err = ext4_ext_dirty(handle, inode, path + depth);
2475                 if (err)
2476                         goto out;
2477
2478                 /*
2479                  * If the extent was completely released,
2480                  * we need to remove it from the leaf
2481                  */
2482                 if (num == 0) {
2483                         if (end != EXT_MAX_BLOCKS - 1) {
2484                                 /*
2485                                  * For hole punching, we need to scoot all the
2486                                  * extents up when an extent is removed so that
2487                                  * we dont have blank extents in the middle
2488                                  */
2489                                 memmove(ex, ex+1, (EXT_LAST_EXTENT(eh) - ex) *
2490                                         sizeof(struct ext4_extent));
2491
2492                                 /* Now get rid of the one at the end */
2493                                 memset(EXT_LAST_EXTENT(eh), 0,
2494                                         sizeof(struct ext4_extent));
2495                         }
2496                         le16_add_cpu(&eh->eh_entries, -1);
2497                 }
2498
2499                 ext_debug("new extent: %u:%u:%llu\n", block, num,
2500                                 ext4_ext_pblock(ex));
2501                 ex--;
2502                 ex_ee_block = le32_to_cpu(ex->ee_block);
2503                 ex_ee_len = ext4_ext_get_actual_len(ex);
2504         }
2505
2506         if (correct_index && eh->eh_entries)
2507                 err = ext4_ext_correct_indexes(handle, inode, path);
2508
2509         /* if this leaf is free, then we should
2510          * remove it from index block above */
2511         if (err == 0 && eh->eh_entries == 0 && path[depth].p_bh != NULL)
2512                 err = ext4_ext_rm_idx(handle, inode, path + depth);
2513
2514 out:
2515         return err;
2516 }
2517
2518 /*
2519  * ext4_ext_more_to_rm:
2520  * returns 1 if current index has to be freed (even partial)
2521  */
2522 static int
2523 ext4_ext_more_to_rm(struct ext4_ext_path *path)
2524 {
2525         BUG_ON(path->p_idx == NULL);
2526
2527         if (path->p_idx < EXT_FIRST_INDEX(path->p_hdr))
2528                 return 0;
2529
2530         /*
2531          * if truncate on deeper level happened, it wasn't partial,
2532          * so we have to consider current index for truncation
2533          */
2534         if (le16_to_cpu(path->p_hdr->eh_entries) == path->p_block)
2535                 return 0;
2536         return 1;
2537 }
2538
2539 static int ext4_ext_remove_space(struct inode *inode, ext4_lblk_t start,
2540                                 ext4_lblk_t end)
2541 {
2542         struct super_block *sb = inode->i_sb;
2543         int depth = ext_depth(inode);
2544         struct ext4_ext_path *path;
2545         handle_t *handle;
2546         int i, err;
2547
2548         ext_debug("truncate since %u\n", start);
2549
2550         /* probably first extent we're gonna free will be last in block */
2551         handle = ext4_journal_start(inode, depth + 1);
2552         if (IS_ERR(handle))
2553                 return PTR_ERR(handle);
2554
2555 again:
2556         ext4_ext_invalidate_cache(inode);
2557
2558         /*
2559          * We start scanning from right side, freeing all the blocks
2560          * after i_size and walking into the tree depth-wise.
2561          */
2562         depth = ext_depth(inode);
2563         path = kzalloc(sizeof(struct ext4_ext_path) * (depth + 1), GFP_NOFS);
2564         if (path == NULL) {
2565                 ext4_journal_stop(handle);
2566                 return -ENOMEM;
2567         }
2568         path[0].p_depth = depth;
2569         path[0].p_hdr = ext_inode_hdr(inode);
2570         if (ext4_ext_check(inode, path[0].p_hdr, depth)) {
2571                 err = -EIO;
2572                 goto out;
2573         }
2574         i = err = 0;
2575
2576         while (i >= 0 && err == 0) {
2577                 if (i == depth) {
2578                         /* this is leaf block */
2579                         err = ext4_ext_rm_leaf(handle, inode, path,
2580                                         start, end);
2581                         /* root level has p_bh == NULL, brelse() eats this */
2582                         brelse(path[i].p_bh);
2583                         path[i].p_bh = NULL;
2584                         i--;
2585                         continue;
2586                 }
2587
2588                 /* this is index block */
2589                 if (!path[i].p_hdr) {
2590                         ext_debug("initialize header\n");
2591                         path[i].p_hdr = ext_block_hdr(path[i].p_bh);
2592                 }
2593
2594                 if (!path[i].p_idx) {
2595                         /* this level hasn't been touched yet */
2596                         path[i].p_idx = EXT_LAST_INDEX(path[i].p_hdr);
2597                         path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries)+1;
2598                         ext_debug("init index ptr: hdr 0x%p, num %d\n",
2599                                   path[i].p_hdr,
2600                                   le16_to_cpu(path[i].p_hdr->eh_entries));
2601                 } else {
2602                         /* we were already here, see at next index */
2603                         path[i].p_idx--;
2604                 }
2605
2606                 ext_debug("level %d - index, first 0x%p, cur 0x%p\n",
2607                                 i, EXT_FIRST_INDEX(path[i].p_hdr),
2608                                 path[i].p_idx);
2609                 if (ext4_ext_more_to_rm(path + i)) {
2610                         struct buffer_head *bh;
2611                         /* go to the next level */
2612                         ext_debug("move to level %d (block %llu)\n",
2613                                   i + 1, ext4_idx_pblock(path[i].p_idx));
2614                         memset(path + i + 1, 0, sizeof(*path));
2615                         bh = sb_bread(sb, ext4_idx_pblock(path[i].p_idx));
2616                         if (!bh) {
2617                                 /* should we reset i_size? */
2618                                 err = -EIO;
2619                                 break;
2620                         }
2621                         if (WARN_ON(i + 1 > depth)) {
2622                                 err = -EIO;
2623                                 break;
2624                         }
2625                         if (ext4_ext_check(inode, ext_block_hdr(bh),
2626                                                         depth - i - 1)) {
2627                                 err = -EIO;
2628                                 break;
2629                         }
2630                         path[i + 1].p_bh = bh;
2631
2632                         /* save actual number of indexes since this
2633                          * number is changed at the next iteration */
2634                         path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries);
2635                         i++;
2636                 } else {
2637                         /* we finished processing this index, go up */
2638                         if (path[i].p_hdr->eh_entries == 0 && i > 0) {
2639                                 /* index is empty, remove it;
2640                                  * handle must be already prepared by the
2641                                  * truncatei_leaf() */
2642                                 err = ext4_ext_rm_idx(handle, inode, path + i);
2643                         }
2644                         /* root level has p_bh == NULL, brelse() eats this */
2645                         brelse(path[i].p_bh);
2646                         path[i].p_bh = NULL;
2647                         i--;
2648                         ext_debug("return to level %d\n", i);
2649                 }
2650         }
2651
2652         /* TODO: flexible tree reduction should be here */
2653         if (path->p_hdr->eh_entries == 0) {
2654                 /*
2655                  * truncate to zero freed all the tree,
2656                  * so we need to correct eh_depth
2657                  */
2658                 err = ext4_ext_get_access(handle, inode, path);
2659                 if (err == 0) {
2660                         ext_inode_hdr(inode)->eh_depth = 0;
2661                         ext_inode_hdr(inode)->eh_max =
2662                                 cpu_to_le16(ext4_ext_space_root(inode, 0));
2663                         err = ext4_ext_dirty(handle, inode, path);
2664                 }
2665         }
2666 out:
2667         ext4_ext_drop_refs(path);
2668         kfree(path);
2669         if (err == -EAGAIN)
2670                 goto again;
2671         ext4_journal_stop(handle);
2672
2673         return err;
2674 }
2675
2676 /*
2677  * called at mount time
2678  */
2679 void ext4_ext_init(struct super_block *sb)
2680 {
2681         /*
2682          * possible initialization would be here
2683          */
2684
2685         if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_EXTENTS)) {
2686 #if defined(AGGRESSIVE_TEST) || defined(CHECK_BINSEARCH) || defined(EXTENTS_STATS)
2687                 printk(KERN_INFO "EXT4-fs: file extents enabled");
2688 #ifdef AGGRESSIVE_TEST
2689                 printk(", aggressive tests");
2690 #endif
2691 #ifdef CHECK_BINSEARCH
2692                 printk(", check binsearch");
2693 #endif
2694 #ifdef EXTENTS_STATS
2695                 printk(", stats");
2696 #endif
2697                 printk("\n");
2698 #endif
2699 #ifdef EXTENTS_STATS
2700                 spin_lock_init(&EXT4_SB(sb)->s_ext_stats_lock);
2701                 EXT4_SB(sb)->s_ext_min = 1 << 30;
2702                 EXT4_SB(sb)->s_ext_max = 0;
2703 #endif
2704         }
2705 }
2706
2707 /*
2708  * called at umount time
2709  */
2710 void ext4_ext_release(struct super_block *sb)
2711 {
2712         if (!EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_EXTENTS))
2713                 return;
2714
2715 #ifdef EXTENTS_STATS
2716         if (EXT4_SB(sb)->s_ext_blocks && EXT4_SB(sb)->s_ext_extents) {
2717                 struct ext4_sb_info *sbi = EXT4_SB(sb);
2718                 printk(KERN_ERR "EXT4-fs: %lu blocks in %lu extents (%lu ave)\n",
2719                         sbi->s_ext_blocks, sbi->s_ext_extents,
2720                         sbi->s_ext_blocks / sbi->s_ext_extents);
2721                 printk(KERN_ERR "EXT4-fs: extents: %lu min, %lu max, max depth %lu\n",
2722                         sbi->s_ext_min, sbi->s_ext_max, sbi->s_depth_max);
2723         }
2724 #endif
2725 }
2726
2727 /* FIXME!! we need to try to merge to left or right after zero-out  */
2728 static int ext4_ext_zeroout(struct inode *inode, struct ext4_extent *ex)
2729 {
2730         ext4_fsblk_t ee_pblock;
2731         unsigned int ee_len;
2732         int ret;
2733
2734         ee_len    = ext4_ext_get_actual_len(ex);
2735         ee_pblock = ext4_ext_pblock(ex);
2736
2737         ret = sb_issue_zeroout(inode->i_sb, ee_pblock, ee_len, GFP_NOFS);
2738         if (ret > 0)
2739                 ret = 0;
2740
2741         return ret;
2742 }
2743
2744 /*
2745  * used by extent splitting.
2746  */
2747 #define EXT4_EXT_MAY_ZEROOUT    0x1  /* safe to zeroout if split fails \
2748                                         due to ENOSPC */
2749 #define EXT4_EXT_MARK_UNINIT1   0x2  /* mark first half uninitialized */
2750 #define EXT4_EXT_MARK_UNINIT2   0x4  /* mark second half uninitialized */
2751
2752 /*
2753  * ext4_split_extent_at() splits an extent at given block.
2754  *
2755  * @handle: the journal handle
2756  * @inode: the file inode
2757  * @path: the path to the extent
2758  * @split: the logical block where the extent is splitted.
2759  * @split_flags: indicates if the extent could be zeroout if split fails, and
2760  *               the states(init or uninit) of new extents.
2761  * @flags: flags used to insert new extent to extent tree.
2762  *
2763  *
2764  * Splits extent [a, b] into two extents [a, @split) and [@split, b], states
2765  * of which are deterimined by split_flag.
2766  *
2767  * There are two cases:
2768  *  a> the extent are splitted into two extent.
2769  *  b> split is not needed, and just mark the extent.
2770  *
2771  * return 0 on success.
2772  */
2773 static int ext4_split_extent_at(handle_t *handle,
2774                              struct inode *inode,
2775                              struct ext4_ext_path *path,
2776                              ext4_lblk_t split,
2777                              int split_flag,
2778                              int flags)
2779 {
2780         ext4_fsblk_t newblock;
2781         ext4_lblk_t ee_block;
2782         struct ext4_extent *ex, newex, orig_ex;
2783         struct ext4_extent *ex2 = NULL;
2784         unsigned int ee_len, depth;
2785         int err = 0;
2786
2787         ext_debug("ext4_split_extents_at: inode %lu, logical"
2788                 "block %llu\n", inode->i_ino, (unsigned long long)split);
2789
2790         ext4_ext_show_leaf(inode, path);
2791
2792         depth = ext_depth(inode);
2793         ex = path[depth].p_ext;
2794         ee_block = le32_to_cpu(ex->ee_block);
2795         ee_len = ext4_ext_get_actual_len(ex);
2796         newblock = split - ee_block + ext4_ext_pblock(ex);
2797
2798         BUG_ON(split < ee_block || split >= (ee_block + ee_len));
2799
2800         err = ext4_ext_get_access(handle, inode, path + depth);
2801         if (err)
2802                 goto out;
2803
2804         if (split == ee_block) {
2805                 /*
2806                  * case b: block @split is the block that the extent begins with
2807                  * then we just change the state of the extent, and splitting
2808                  * is not needed.
2809                  */
2810                 if (split_flag & EXT4_EXT_MARK_UNINIT2)
2811                         ext4_ext_mark_uninitialized(ex);
2812                 else
2813                         ext4_ext_mark_initialized(ex);
2814
2815                 if (!(flags & EXT4_GET_BLOCKS_PRE_IO))
2816                         ext4_ext_try_to_merge(inode, path, ex);
2817
2818                 err = ext4_ext_dirty(handle, inode, path + depth);
2819                 goto out;
2820         }
2821
2822         /* case a */
2823         memcpy(&orig_ex, ex, sizeof(orig_ex));
2824         ex->ee_len = cpu_to_le16(split - ee_block);
2825         if (split_flag & EXT4_EXT_MARK_UNINIT1)
2826                 ext4_ext_mark_uninitialized(ex);
2827
2828         /*
2829          * path may lead to new leaf, not to original leaf any more
2830          * after ext4_ext_insert_extent() returns,
2831          */
2832         err = ext4_ext_dirty(handle, inode, path + depth);
2833         if (err)
2834                 goto fix_extent_len;
2835
2836         ex2 = &newex;
2837         ex2->ee_block = cpu_to_le32(split);
2838         ex2->ee_len   = cpu_to_le16(ee_len - (split - ee_block));
2839         ext4_ext_store_pblock(ex2, newblock);
2840         if (split_flag & EXT4_EXT_MARK_UNINIT2)
2841                 ext4_ext_mark_uninitialized(ex2);
2842
2843         err = ext4_ext_insert_extent(handle, inode, path, &newex, flags);
2844         if (err == -ENOSPC && (EXT4_EXT_MAY_ZEROOUT & split_flag)) {
2845                 err = ext4_ext_zeroout(inode, &orig_ex);
2846                 if (err)
2847                         goto fix_extent_len;
2848                 /* update the extent length and mark as initialized */
2849                 ex->ee_len = cpu_to_le16(ee_len);
2850                 ext4_ext_try_to_merge(inode, path, ex);
2851                 err = ext4_ext_dirty(handle, inode, path + depth);
2852                 goto out;
2853         } else if (err)
2854                 goto fix_extent_len;
2855
2856 out:
2857         ext4_ext_show_leaf(inode, path);
2858         return err;
2859
2860 fix_extent_len:
2861         ex->ee_len = orig_ex.ee_len;
2862         ext4_ext_dirty(handle, inode, path + depth);
2863         return err;
2864 }
2865
2866 /*
2867  * ext4_split_extents() splits an extent and mark extent which is covered
2868  * by @map as split_flags indicates
2869  *
2870  * It may result in splitting the extent into multiple extents (upto three)
2871  * There are three possibilities:
2872  *   a> There is no split required
2873  *   b> Splits in two extents: Split is happening at either end of the extent
2874  *   c> Splits in three extents: Somone is splitting in middle of the extent
2875  *
2876  */
2877 static int ext4_split_extent(handle_t *handle,
2878                               struct inode *inode,
2879                               struct ext4_ext_path *path,
2880                               struct ext4_map_blocks *map,
2881                               int split_flag,
2882                               int flags)
2883 {
2884         ext4_lblk_t ee_block;
2885         struct ext4_extent *ex;
2886         unsigned int ee_len, depth;
2887         int err = 0;
2888         int uninitialized;
2889         int split_flag1, flags1;
2890
2891         depth = ext_depth(inode);
2892         ex = path[depth].p_ext;
2893         ee_block = le32_to_cpu(ex->ee_block);
2894         ee_len = ext4_ext_get_actual_len(ex);
2895         uninitialized = ext4_ext_is_uninitialized(ex);
2896
2897         if (map->m_lblk + map->m_len < ee_block + ee_len) {
2898                 split_flag1 = split_flag & EXT4_EXT_MAY_ZEROOUT ?
2899                               EXT4_EXT_MAY_ZEROOUT : 0;
2900                 flags1 = flags | EXT4_GET_BLOCKS_PRE_IO;
2901                 if (uninitialized)
2902                         split_flag1 |= EXT4_EXT_MARK_UNINIT1 |
2903                                        EXT4_EXT_MARK_UNINIT2;
2904                 err = ext4_split_extent_at(handle, inode, path,
2905                                 map->m_lblk + map->m_len, split_flag1, flags1);
2906                 if (err)
2907                         goto out;
2908         }
2909
2910         ext4_ext_drop_refs(path);
2911         path = ext4_ext_find_extent(inode, map->m_lblk, path);
2912         if (IS_ERR(path))
2913                 return PTR_ERR(path);
2914
2915         if (map->m_lblk >= ee_block) {
2916                 split_flag1 = split_flag & EXT4_EXT_MAY_ZEROOUT ?
2917                               EXT4_EXT_MAY_ZEROOUT : 0;
2918                 if (uninitialized)
2919                         split_flag1 |= EXT4_EXT_MARK_UNINIT1;
2920                 if (split_flag & EXT4_EXT_MARK_UNINIT2)
2921                         split_flag1 |= EXT4_EXT_MARK_UNINIT2;
2922                 err = ext4_split_extent_at(handle, inode, path,
2923                                 map->m_lblk, split_flag1, flags);
2924                 if (err)
2925                         goto out;
2926         }
2927
2928         ext4_ext_show_leaf(inode, path);
2929 out:
2930         return err ? err : map->m_len;
2931 }
2932
2933 #define EXT4_EXT_ZERO_LEN 7
2934 /*
2935  * This function is called by ext4_ext_map_blocks() if someone tries to write
2936  * to an uninitialized extent. It may result in splitting the uninitialized
2937  * extent into multiple extents (up to three - one initialized and two
2938  * uninitialized).
2939  * There are three possibilities:
2940  *   a> There is no split required: Entire extent should be initialized
2941  *   b> Splits in two extents: Write is happening at either end of the extent
2942  *   c> Splits in three extents: Somone is writing in middle of the extent
2943  */
2944 static int ext4_ext_convert_to_initialized(handle_t *handle,
2945                                            struct inode *inode,
2946                                            struct ext4_map_blocks *map,
2947                                            struct ext4_ext_path *path)
2948 {
2949         struct ext4_map_blocks split_map;
2950         struct ext4_extent zero_ex;
2951         struct ext4_extent *ex;
2952         ext4_lblk_t ee_block, eof_block;
2953         unsigned int allocated, ee_len, depth;
2954         int err = 0;
2955         int split_flag = 0;
2956
2957         ext_debug("ext4_ext_convert_to_initialized: inode %lu, logical"
2958                 "block %llu, max_blocks %u\n", inode->i_ino,
2959                 (unsigned long long)map->m_lblk, map->m_len);
2960
2961         eof_block = (inode->i_size + inode->i_sb->s_blocksize - 1) >>
2962                 inode->i_sb->s_blocksize_bits;
2963         if (eof_block < map->m_lblk + map->m_len)
2964                 eof_block = map->m_lblk + map->m_len;
2965
2966         depth = ext_depth(inode);
2967         ex = path[depth].p_ext;
2968         ee_block = le32_to_cpu(ex->ee_block);
2969         ee_len = ext4_ext_get_actual_len(ex);
2970         allocated = ee_len - (map->m_lblk - ee_block);
2971
2972         WARN_ON(map->m_lblk < ee_block);
2973         /*
2974          * It is safe to convert extent to initialized via explicit
2975          * zeroout only if extent is fully insde i_size or new_size.
2976          */
2977         split_flag |= ee_block + ee_len <= eof_block ? EXT4_EXT_MAY_ZEROOUT : 0;
2978
2979         /* If extent has less than 2*EXT4_EXT_ZERO_LEN zerout directly */
2980         if (ee_len <= 2*EXT4_EXT_ZERO_LEN &&
2981             (EXT4_EXT_MAY_ZEROOUT & split_flag)) {
2982                 err = ext4_ext_zeroout(inode, ex);
2983                 if (err)
2984                         goto out;
2985
2986                 err = ext4_ext_get_access(handle, inode, path + depth);
2987                 if (err)
2988                         goto out;
2989                 ext4_ext_mark_initialized(ex);
2990                 ext4_ext_try_to_merge(inode, path, ex);
2991                 err = ext4_ext_dirty(handle, inode, path + depth);
2992                 goto out;
2993         }
2994
2995         /*
2996          * four cases:
2997          * 1. split the extent into three extents.
2998          * 2. split the extent into two extents, zeroout the first half.
2999          * 3. split the extent into two extents, zeroout the second half.
3000          * 4. split the extent into two extents with out zeroout.
3001          */
3002         split_map.m_lblk = map->m_lblk;
3003         split_map.m_len = map->m_len;
3004
3005         if (allocated > map->m_len) {
3006                 if (allocated <= EXT4_EXT_ZERO_LEN &&
3007                     (EXT4_EXT_MAY_ZEROOUT & split_flag)) {
3008                         /* case 3 */
3009                         zero_ex.ee_block =
3010                                          cpu_to_le32(map->m_lblk);
3011                         zero_ex.ee_len = cpu_to_le16(allocated);
3012                         ext4_ext_store_pblock(&zero_ex,
3013                                 ext4_ext_pblock(ex) + map->m_lblk - ee_block);
3014                         err = ext4_ext_zeroout(inode, &zero_ex);
3015                         if (err)
3016                                 goto out;
3017                         split_map.m_lblk = map->m_lblk;
3018                         split_map.m_len = allocated;
3019                 } else if ((map->m_lblk - ee_block + map->m_len <
3020                            EXT4_EXT_ZERO_LEN) &&
3021                            (EXT4_EXT_MAY_ZEROOUT & split_flag)) {
3022                         /* case 2 */
3023                         if (map->m_lblk != ee_block) {
3024                                 zero_ex.ee_block = ex->ee_block;
3025                                 zero_ex.ee_len = cpu_to_le16(map->m_lblk -
3026                                                         ee_block);
3027                                 ext4_ext_store_pblock(&zero_ex,
3028                                                       ext4_ext_pblock(ex));
3029                                 err = ext4_ext_zeroout(inode, &zero_ex);
3030                                 if (err)
3031                                         goto out;
3032                         }
3033
3034                         split_map.m_lblk = ee_block;
3035                         split_map.m_len = map->m_lblk - ee_block + map->m_len;
3036                         allocated = map->m_len;
3037                 }
3038         }
3039
3040         allocated = ext4_split_extent(handle, inode, path,
3041                                        &split_map, split_flag, 0);
3042         if (allocated < 0)
3043                 err = allocated;
3044
3045 out:
3046         return err ? err : allocated;
3047 }
3048
3049 /*
3050  * This function is called by ext4_ext_map_blocks() from
3051  * ext4_get_blocks_dio_write() when DIO to write
3052  * to an uninitialized extent.
3053  *
3054  * Writing to an uninitialized extent may result in splitting the uninitialized
3055  * extent into multiple /initialized uninitialized extents (up to three)
3056  * There are three possibilities:
3057  *   a> There is no split required: Entire extent should be uninitialized
3058  *   b> Splits in two extents: Write is happening at either end of the extent
3059  *   c> Splits in three extents: Somone is writing in middle of the extent
3060  *
3061  * One of more index blocks maybe needed if the extent tree grow after
3062  * the uninitialized extent split. To prevent ENOSPC occur at the IO
3063  * complete, we need to split the uninitialized extent before DIO submit
3064  * the IO. The uninitialized extent called at this time will be split
3065  * into three uninitialized extent(at most). After IO complete, the part
3066  * being filled will be convert to initialized by the end_io callback function
3067  * via ext4_convert_unwritten_extents().
3068  *
3069  * Returns the size of uninitialized extent to be written on success.
3070  */
3071 static int ext4_split_unwritten_extents(handle_t *handle,
3072                                         struct inode *inode,
3073                                         struct ext4_map_blocks *map,
3074                                         struct ext4_ext_path *path,
3075                                         int flags)
3076 {
3077         ext4_lblk_t eof_block;
3078         ext4_lblk_t ee_block;
3079         struct ext4_extent *ex;
3080         unsigned int ee_len;
3081         int split_flag = 0, depth;
3082
3083         ext_debug("ext4_split_unwritten_extents: inode %lu, logical"
3084                 "block %llu, max_blocks %u\n", inode->i_ino,
3085                 (unsigned long long)map->m_lblk, map->m_len);
3086
3087         eof_block = (inode->i_size + inode->i_sb->s_blocksize - 1) >>
3088                 inode->i_sb->s_blocksize_bits;
3089         if (eof_block < map->m_lblk + map->m_len)
3090                 eof_block = map->m_lblk + map->m_len;
3091         /*
3092          * It is safe to convert extent to initialized via explicit
3093          * zeroout only if extent is fully insde i_size or new_size.
3094          */
3095         depth = ext_depth(inode);
3096         ex = path[depth].p_ext;
3097         ee_block = le32_to_cpu(ex->ee_block);
3098         ee_len = ext4_ext_get_actual_len(ex);
3099
3100         split_flag |= ee_block + ee_len <= eof_block ? EXT4_EXT_MAY_ZEROOUT : 0;
3101         split_flag |= EXT4_EXT_MARK_UNINIT2;
3102
3103         flags |= EXT4_GET_BLOCKS_PRE_IO;
3104         return ext4_split_extent(handle, inode, path, map, split_flag, flags);
3105 }
3106
3107 static int ext4_convert_unwritten_extents_endio(handle_t *handle,
3108                                               struct inode *inode,
3109                                               struct ext4_ext_path *path)
3110 {
3111         struct ext4_extent *ex;
3112         struct ext4_extent_header *eh;
3113         int depth;
3114         int err = 0;
3115
3116         depth = ext_depth(inode);
3117         eh = path[depth].p_hdr;
3118         ex = path[depth].p_ext;
3119
3120         ext_debug("ext4_convert_unwritten_extents_endio: inode %lu, logical"
3121                 "block %llu, max_blocks %u\n", inode->i_ino,
3122                 (unsigned long long)le32_to_cpu(ex->ee_block),
3123                 ext4_ext_get_actual_len(ex));
3124
3125         err = ext4_ext_get_access(handle, inode, path + depth);
3126         if (err)
3127                 goto out;
3128         /* first mark the extent as initialized */
3129         ext4_ext_mark_initialized(ex);
3130
3131         /* note: ext4_ext_correct_indexes() isn't needed here because
3132          * borders are not changed
3133          */
3134         ext4_ext_try_to_merge(inode, path, ex);
3135
3136         /* Mark modified extent as dirty */
3137         err = ext4_ext_dirty(handle, inode, path + depth);
3138 out:
3139         ext4_ext_show_leaf(inode, path);
3140         return err;
3141 }
3142
3143 static void unmap_underlying_metadata_blocks(struct block_device *bdev,
3144                         sector_t block, int count)
3145 {
3146         int i;
3147         for (i = 0; i < count; i++)
3148                 unmap_underlying_metadata(bdev, block + i);
3149 }
3150
3151 /*
3152  * Handle EOFBLOCKS_FL flag, clearing it if necessary
3153  */
3154 static int check_eofblocks_fl(handle_t *handle, struct inode *inode,
3155                               ext4_lblk_t lblk,
3156                               struct ext4_ext_path *path,
3157                               unsigned int len)
3158 {
3159         int i, depth;
3160         struct ext4_extent_header *eh;
3161         struct ext4_extent *last_ex;
3162
3163         if (!ext4_test_inode_flag(inode, EXT4_INODE_EOFBLOCKS))
3164                 return 0;
3165
3166         depth = ext_depth(inode);
3167         eh = path[depth].p_hdr;
3168
3169         if (unlikely(!eh->eh_entries)) {
3170                 EXT4_ERROR_INODE(inode, "eh->eh_entries == 0 and "
3171                                  "EOFBLOCKS_FL set");
3172                 return -EIO;
3173         }
3174         last_ex = EXT_LAST_EXTENT(eh);
3175         /*
3176          * We should clear the EOFBLOCKS_FL flag if we are writing the
3177          * last block in the last extent in the file.  We test this by
3178          * first checking to see if the caller to
3179          * ext4_ext_get_blocks() was interested in the last block (or
3180          * a block beyond the last block) in the current extent.  If
3181          * this turns out to be false, we can bail out from this
3182          * function immediately.
3183          */
3184         if (lblk + len < le32_to_cpu(last_ex->ee_block) +
3185             ext4_ext_get_actual_len(last_ex))
3186                 return 0;
3187         /*
3188          * If the caller does appear to be planning to write at or
3189          * beyond the end of the current extent, we then test to see
3190          * if the current extent is the last extent in the file, by
3191          * checking to make sure it was reached via the rightmost node
3192          * at each level of the tree.
3193          */
3194         for (i = depth-1; i >= 0; i--)
3195                 if (path[i].p_idx != EXT_LAST_INDEX(path[i].p_hdr))
3196                         return 0;
3197         ext4_clear_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
3198         return ext4_mark_inode_dirty(handle, inode);
3199 }
3200
3201 static int
3202 ext4_ext_handle_uninitialized_extents(handle_t *handle, struct inode *inode,
3203                         struct ext4_map_blocks *map,
3204                         struct ext4_ext_path *path, int flags,
3205                         unsigned int allocated, ext4_fsblk_t newblock)
3206 {
3207         int ret = 0;
3208         int err = 0;
3209         ext4_io_end_t *io = EXT4_I(inode)->cur_aio_dio;
3210
3211         ext_debug("ext4_ext_handle_uninitialized_extents: inode %lu, logical"
3212                   "block %llu, max_blocks %u, flags %d, allocated %u",
3213                   inode->i_ino, (unsigned long long)map->m_lblk, map->m_len,
3214                   flags, allocated);
3215         ext4_ext_show_leaf(inode, path);
3216
3217         /* get_block() before submit the IO, split the extent */
3218         if ((flags & EXT4_GET_BLOCKS_PRE_IO)) {
3219                 ret = ext4_split_unwritten_extents(handle, inode, map,
3220                                                    path, flags);
3221                 /*
3222                  * Flag the inode(non aio case) or end_io struct (aio case)
3223                  * that this IO needs to conversion to written when IO is
3224                  * completed
3225                  */
3226                 if (io && !(io->flag & EXT4_IO_END_UNWRITTEN)) {
3227                         io->flag = EXT4_IO_END_UNWRITTEN;
3228                         atomic_inc(&EXT4_I(inode)->i_aiodio_unwritten);
3229                 } else
3230                         ext4_set_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
3231                 if (ext4_should_dioread_nolock(inode))
3232                         map->m_flags |= EXT4_MAP_UNINIT;
3233                 goto out;
3234         }
3235         /* IO end_io complete, convert the filled extent to written */
3236         if ((flags & EXT4_GET_BLOCKS_CONVERT)) {
3237                 ret = ext4_convert_unwritten_extents_endio(handle, inode,
3238                                                         path);
3239                 if (ret >= 0) {
3240                         ext4_update_inode_fsync_trans(handle, inode, 1);
3241                         err = check_eofblocks_fl(handle, inode, map->m_lblk,
3242                                                  path, map->m_len);
3243                 } else
3244                         err = ret;
3245                 goto out2;
3246         }
3247         /* buffered IO case */
3248         /*
3249          * repeat fallocate creation request
3250          * we already have an unwritten extent
3251          */
3252         if (flags & EXT4_GET_BLOCKS_UNINIT_EXT)
3253                 goto map_out;
3254
3255         /* buffered READ or buffered write_begin() lookup */
3256         if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
3257                 /*
3258                  * We have blocks reserved already.  We
3259                  * return allocated blocks so that delalloc
3260                  * won't do block reservation for us.  But
3261                  * the buffer head will be unmapped so that
3262                  * a read from the block returns 0s.
3263                  */
3264                 map->m_flags |= EXT4_MAP_UNWRITTEN;
3265                 goto out1;
3266         }
3267
3268         /* buffered write, writepage time, convert*/
3269         ret = ext4_ext_convert_to_initialized(handle, inode, map, path);
3270         if (ret >= 0) {
3271                 ext4_update_inode_fsync_trans(handle, inode, 1);
3272                 err = check_eofblocks_fl(handle, inode, map->m_lblk, path,
3273                                          map->m_len);
3274                 if (err < 0)
3275                         goto out2;
3276         }
3277
3278 out:
3279         if (ret <= 0) {
3280                 err = ret;
3281                 goto out2;
3282         } else
3283                 allocated = ret;
3284         map->m_flags |= EXT4_MAP_NEW;
3285         /*
3286          * if we allocated more blocks than requested
3287          * we need to make sure we unmap the extra block
3288          * allocated. The actual needed block will get
3289          * unmapped later when we find the buffer_head marked
3290          * new.
3291          */
3292         if (allocated > map->m_len) {
3293                 unmap_underlying_metadata_blocks(inode->i_sb->s_bdev,
3294                                         newblock + map->m_len,
3295                                         allocated - map->m_len);
3296                 allocated = map->m_len;
3297         }
3298
3299         /*
3300          * If we have done fallocate with the offset that is already
3301          * delayed allocated, we would have block reservation
3302          * and quota reservation done in the delayed write path.
3303          * But fallocate would have already updated quota and block
3304          * count for this offset. So cancel these reservation
3305          */
3306         if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
3307                 ext4_da_update_reserve_space(inode, allocated, 0);
3308
3309 map_out:
3310         map->m_flags |= EXT4_MAP_MAPPED;
3311 out1:
3312         if (allocated > map->m_len)
3313                 allocated = map->m_len;
3314         ext4_ext_show_leaf(inode, path);
3315         map->m_pblk = newblock;
3316         map->m_len = allocated;
3317 out2:
3318         if (path) {
3319                 ext4_ext_drop_refs(path);
3320                 kfree(path);
3321         }
3322         return err ? err : allocated;
3323 }
3324
3325 /*
3326  * Block allocation/map/preallocation routine for extents based files
3327  *
3328  *
3329  * Need to be called with
3330  * down_read(&EXT4_I(inode)->i_data_sem) if not allocating file system block
3331  * (ie, create is zero). Otherwise down_write(&EXT4_I(inode)->i_data_sem)
3332  *
3333  * return > 0, number of of blocks already mapped/allocated
3334  *          if create == 0 and these are pre-allocated blocks
3335  *              buffer head is unmapped
3336  *          otherwise blocks are mapped
3337  *
3338  * return = 0, if plain look up failed (blocks have not been allocated)
3339  *          buffer head is unmapped
3340  *
3341  * return < 0, error case.
3342  */
3343 int ext4_ext_map_blocks(handle_t *handle, struct inode *inode,
3344                         struct ext4_map_blocks *map, int flags)
3345 {
3346         struct ext4_ext_path *path = NULL;
3347         struct ext4_extent newex, *ex;
3348         ext4_fsblk_t newblock = 0;
3349         int err = 0, depth, ret;
3350         unsigned int allocated = 0;
3351         unsigned int punched_out = 0;
3352         unsigned int result = 0;
3353         struct ext4_allocation_request ar;
3354         ext4_io_end_t *io = EXT4_I(inode)->cur_aio_dio;
3355         struct ext4_map_blocks punch_map;
3356
3357         ext_debug("blocks %u/%u requested for inode %lu\n",
3358                   map->m_lblk, map->m_len, inode->i_ino);
3359         trace_ext4_ext_map_blocks_enter(inode, map->m_lblk, map->m_len, flags);
3360
3361         /* check in cache */
3362         if (ext4_ext_in_cache(inode, map->m_lblk, &newex) &&
3363                 ((flags & EXT4_GET_BLOCKS_PUNCH_OUT_EXT) == 0)) {
3364                 if (!newex.ee_start_lo && !newex.ee_start_hi) {
3365                         if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
3366                                 /*
3367                                  * block isn't allocated yet and
3368                                  * user doesn't want to allocate it
3369                                  */
3370                                 goto out2;
3371                         }
3372                         /* we should allocate requested block */
3373                 } else {
3374                         /* block is already allocated */
3375                         newblock = map->m_lblk
3376                                    - le32_to_cpu(newex.ee_block)
3377                                    + ext4_ext_pblock(&newex);
3378                         /* number of remaining blocks in the extent */
3379                         allocated = ext4_ext_get_actual_len(&newex) -
3380                                 (map->m_lblk - le32_to_cpu(newex.ee_block));
3381                         goto out;
3382                 }
3383         }
3384
3385         /* find extent for this block */
3386         path = ext4_ext_find_extent(inode, map->m_lblk, NULL);
3387         if (IS_ERR(path)) {
3388                 err = PTR_ERR(path);
3389                 path = NULL;
3390                 goto out2;
3391         }
3392
3393         depth = ext_depth(inode);
3394
3395         /*
3396          * consistent leaf must not be empty;
3397          * this situation is possible, though, _during_ tree modification;
3398          * this is why assert can't be put in ext4_ext_find_extent()
3399          */
3400         if (unlikely(path[depth].p_ext == NULL && depth != 0)) {
3401                 EXT4_ERROR_INODE(inode, "bad extent address "
3402                                  "lblock: %lu, depth: %d pblock %lld",
3403                                  (unsigned long) map->m_lblk, depth,
3404                                  path[depth].p_block);
3405                 err = -EIO;
3406                 goto out2;
3407         }
3408
3409         ex = path[depth].p_ext;
3410         if (ex) {
3411                 ext4_lblk_t ee_block = le32_to_cpu(ex->ee_block);
3412                 ext4_fsblk_t ee_start = ext4_ext_pblock(ex);
3413                 unsigned short ee_len;
3414
3415                 /*
3416                  * Uninitialized extents are treated as holes, except that
3417                  * we split out initialized portions during a write.
3418                  */
3419                 ee_len = ext4_ext_get_actual_len(ex);
3420                 /* if found extent covers block, simply return it */
3421                 if (in_range(map->m_lblk, ee_block, ee_len)) {
3422                         newblock = map->m_lblk - ee_block + ee_start;
3423                         /* number of remaining blocks in the extent */
3424                         allocated = ee_len - (map->m_lblk - ee_block);
3425                         ext_debug("%u fit into %u:%d -> %llu\n", map->m_lblk,
3426                                   ee_block, ee_len, newblock);
3427
3428                         if ((flags & EXT4_GET_BLOCKS_PUNCH_OUT_EXT) == 0) {
3429                                 /*
3430                                  * Do not put uninitialized extent
3431                                  * in the cache
3432                                  */
3433                                 if (!ext4_ext_is_uninitialized(ex)) {
3434                                         ext4_ext_put_in_cache(inode, ee_block,
3435                                                 ee_len, ee_start);
3436                                         goto out;
3437                                 }
3438                                 ret = ext4_ext_handle_uninitialized_extents(
3439                                         handle, inode, map, path, flags,
3440                                         allocated, newblock);
3441                                 return ret;
3442                         }
3443
3444                         /*
3445                          * Punch out the map length, but only to the
3446                          * end of the extent
3447                          */
3448                         punched_out = allocated < map->m_len ?
3449                                 allocated : map->m_len;
3450
3451                         /*
3452                          * Sense extents need to be converted to
3453                          * uninitialized, they must fit in an
3454                          * uninitialized extent
3455                          */
3456                         if (punched_out > EXT_UNINIT_MAX_LEN)
3457                                 punched_out = EXT_UNINIT_MAX_LEN;
3458
3459                         punch_map.m_lblk = map->m_lblk;
3460                         punch_map.m_pblk = newblock;
3461                         punch_map.m_len = punched_out;
3462                         punch_map.m_flags = 0;
3463
3464                         /* Check to see if the extent needs to be split */
3465                         if (punch_map.m_len != ee_len ||
3466                                 punch_map.m_lblk != ee_block) {
3467
3468                                 ret = ext4_split_extent(handle, inode,
3469                                 path, &punch_map, 0,
3470                                 EXT4_GET_BLOCKS_PUNCH_OUT_EXT |
3471                                 EXT4_GET_BLOCKS_PRE_IO);
3472
3473                                 if (ret < 0) {
3474                                         err = ret;
3475                                         goto out2;
3476                                 }
3477                                 /*
3478                                  * find extent for the block at
3479                                  * the start of the hole
3480                                  */
3481                                 ext4_ext_drop_refs(path);
3482                                 kfree(path);
3483
3484                                 path = ext4_ext_find_extent(inode,
3485                                 map->m_lblk, NULL);
3486                                 if (IS_ERR(path)) {
3487                                         err = PTR_ERR(path);
3488                                         path = NULL;
3489                                         goto out2;
3490                                 }
3491
3492                                 depth = ext_depth(inode);
3493                                 ex = path[depth].p_ext;
3494                                 ee_len = ext4_ext_get_actual_len(ex);
3495                                 ee_block = le32_to_cpu(ex->ee_block);
3496                                 ee_start = ext4_ext_pblock(ex);
3497
3498                         }
3499
3500                         ext4_ext_mark_uninitialized(ex);
3501
3502                         err = ext4_ext_remove_space(inode, map->m_lblk,
3503                                 map->m_lblk + punched_out);
3504
3505                         goto out2;
3506                 }
3507         }
3508
3509         /*
3510          * requested block isn't allocated yet;
3511          * we couldn't try to create block if create flag is zero
3512          */
3513         if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
3514                 /*
3515                  * put just found gap into cache to speed up
3516                  * subsequent requests
3517                  */
3518                 ext4_ext_put_gap_in_cache(inode, path, map->m_lblk);
3519                 goto out2;
3520         }
3521         /*
3522          * Okay, we need to do block allocation.
3523          */
3524
3525         /* find neighbour allocated blocks */
3526         ar.lleft = map->m_lblk;
3527         err = ext4_ext_search_left(inode, path, &ar.lleft, &ar.pleft);
3528         if (err)
3529                 goto out2;
3530         ar.lright = map->m_lblk;
3531         err = ext4_ext_search_right(inode, path, &ar.lright, &ar.pright);
3532         if (err)
3533                 goto out2;
3534
3535         /*
3536          * See if request is beyond maximum number of blocks we can have in
3537          * a single extent. For an initialized extent this limit is
3538          * EXT_INIT_MAX_LEN and for an uninitialized extent this limit is
3539          * EXT_UNINIT_MAX_LEN.
3540          */
3541         if (map->m_len > EXT_INIT_MAX_LEN &&
3542             !(flags & EXT4_GET_BLOCKS_UNINIT_EXT))
3543                 map->m_len = EXT_INIT_MAX_LEN;
3544         else if (map->m_len > EXT_UNINIT_MAX_LEN &&
3545                  (flags & EXT4_GET_BLOCKS_UNINIT_EXT))
3546                 map->m_len = EXT_UNINIT_MAX_LEN;
3547
3548         /* Check if we can really insert (m_lblk)::(m_lblk + m_len) extent */
3549         newex.ee_block = cpu_to_le32(map->m_lblk);
3550         newex.ee_len = cpu_to_le16(map->m_len);
3551         err = ext4_ext_check_overlap(inode, &newex, path);
3552         if (err)
3553                 allocated = ext4_ext_get_actual_len(&newex);
3554         else
3555                 allocated = map->m_len;
3556
3557         /* allocate new block */
3558         ar.inode = inode;
3559         ar.goal = ext4_ext_find_goal(inode, path, map->m_lblk);
3560         ar.logical = map->m_lblk;
3561         ar.len = allocated;
3562         if (S_ISREG(inode->i_mode))
3563                 ar.flags = EXT4_MB_HINT_DATA;
3564         else
3565                 /* disable in-core preallocation for non-regular files */
3566                 ar.flags = 0;
3567         if (flags & EXT4_GET_BLOCKS_NO_NORMALIZE)
3568                 ar.flags |= EXT4_MB_HINT_NOPREALLOC;
3569         newblock = ext4_mb_new_blocks(handle, &ar, &err);
3570         if (!newblock)
3571                 goto out2;
3572         ext_debug("allocate new block: goal %llu, found %llu/%u\n",
3573                   ar.goal, newblock, allocated);
3574
3575         /* try to insert new extent into found leaf and return */
3576         ext4_ext_store_pblock(&newex, newblock);
3577         newex.ee_len = cpu_to_le16(ar.len);
3578         /* Mark uninitialized */
3579         if (flags & EXT4_GET_BLOCKS_UNINIT_EXT){
3580                 ext4_ext_mark_uninitialized(&newex);
3581                 /*
3582                  * io_end structure was created for every IO write to an
3583                  * uninitialized extent. To avoid unnecessary conversion,
3584                  * here we flag the IO that really needs the conversion.
3585                  * For non asycn direct IO case, flag the inode state
3586                  * that we need to perform conversion when IO is done.
3587                  */
3588                 if ((flags & EXT4_GET_BLOCKS_PRE_IO)) {
3589                         if (io && !(io->flag & EXT4_IO_END_UNWRITTEN)) {
3590                                 io->flag = EXT4_IO_END_UNWRITTEN;
3591                                 atomic_inc(&EXT4_I(inode)->i_aiodio_unwritten);
3592                         } else
3593                                 ext4_set_inode_state(inode,
3594                                                      EXT4_STATE_DIO_UNWRITTEN);
3595                 }
3596                 if (ext4_should_dioread_nolock(inode))
3597                         map->m_flags |= EXT4_MAP_UNINIT;
3598         }
3599
3600         err = check_eofblocks_fl(handle, inode, map->m_lblk, path, ar.len);
3601         if (!err)
3602                 err = ext4_ext_insert_extent(handle, inode, path,
3603                                              &newex, flags);
3604         if (err) {
3605                 int fb_flags = flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE ?
3606                         EXT4_FREE_BLOCKS_NO_QUOT_UPDATE : 0;
3607                 /* free data blocks we just allocated */
3608                 /* not a good idea to call discard here directly,
3609                  * but otherwise we'd need to call it every free() */
3610                 ext4_discard_preallocations(inode);
3611                 ext4_free_blocks(handle, inode, NULL, ext4_ext_pblock(&newex),
3612                                  ext4_ext_get_actual_len(&newex), fb_flags);
3613                 goto out2;
3614         }
3615
3616         /* previous routine could use block we allocated */
3617         newblock = ext4_ext_pblock(&newex);
3618         allocated = ext4_ext_get_actual_len(&newex);
3619         if (allocated > map->m_len)
3620                 allocated = map->m_len;
3621         map->m_flags |= EXT4_MAP_NEW;
3622
3623         /*
3624          * Update reserved blocks/metadata blocks after successful
3625          * block allocation which had been deferred till now.
3626          */
3627         if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
3628                 ext4_da_update_reserve_space(inode, allocated, 1);
3629
3630         /*
3631          * Cache the extent and update transaction to commit on fdatasync only
3632          * when it is _not_ an uninitialized extent.
3633          */
3634         if ((flags & EXT4_GET_BLOCKS_UNINIT_EXT) == 0) {
3635                 ext4_ext_put_in_cache(inode, map->m_lblk, allocated, newblock);
3636                 ext4_update_inode_fsync_trans(handle, inode, 1);
3637         } else
3638                 ext4_update_inode_fsync_trans(handle, inode, 0);
3639 out:
3640         if (allocated > map->m_len)
3641                 allocated = map->m_len;
3642         ext4_ext_show_leaf(inode, path);
3643         map->m_flags |= EXT4_MAP_MAPPED;
3644         map->m_pblk = newblock;
3645         map->m_len = allocated;
3646 out2:
3647         if (path) {
3648                 ext4_ext_drop_refs(path);
3649                 kfree(path);
3650         }
3651         trace_ext4_ext_map_blocks_exit(inode, map->m_lblk,
3652                 newblock, map->m_len, err ? err : allocated);
3653
3654         result = (flags & EXT4_GET_BLOCKS_PUNCH_OUT_EXT) ?
3655                         punched_out : allocated;
3656
3657         return err ? err : result;
3658 }
3659
3660 void ext4_ext_truncate(struct inode *inode)
3661 {
3662         struct address_space *mapping = inode->i_mapping;
3663         struct super_block *sb = inode->i_sb;
3664         ext4_lblk_t last_block;
3665         handle_t *handle;
3666         int err = 0;
3667
3668         /*
3669          * finish any pending end_io work so we won't run the risk of
3670          * converting any truncated blocks to initialized later
3671          */
3672         ext4_flush_completed_IO(inode);
3673
3674         /*
3675          * probably first extent we're gonna free will be last in block
3676          */
3677         err = ext4_writepage_trans_blocks(inode);
3678         handle = ext4_journal_start(inode, err);
3679         if (IS_ERR(handle))
3680                 return;
3681
3682         if (inode->i_size & (sb->s_blocksize - 1))
3683                 ext4_block_truncate_page(handle, mapping, inode->i_size);
3684
3685         if (ext4_orphan_add(handle, inode))
3686                 goto out_stop;
3687
3688         down_write(&EXT4_I(inode)->i_data_sem);
3689         ext4_ext_invalidate_cache(inode);
3690
3691         ext4_discard_preallocations(inode);
3692
3693         /*
3694          * TODO: optimization is possible here.
3695          * Probably we need not scan at all,
3696          * because page truncation is enough.
3697          */
3698
3699         /* we have to know where to truncate from in crash case */
3700         EXT4_I(inode)->i_disksize = inode->i_size;
3701         ext4_mark_inode_dirty(handle, inode);
3702
3703         last_block = (inode->i_size + sb->s_blocksize - 1)
3704                         >> EXT4_BLOCK_SIZE_BITS(sb);
3705         err = ext4_ext_remove_space(inode, last_block, EXT_MAX_BLOCKS - 1);
3706
3707         /* In a multi-transaction truncate, we only make the final
3708          * transaction synchronous.
3709          */
3710         if (IS_SYNC(inode))
3711                 ext4_handle_sync(handle);
3712
3713         up_write(&EXT4_I(inode)->i_data_sem);
3714
3715 out_stop:
3716         /*
3717          * If this was a simple ftruncate() and the file will remain alive,
3718          * then we need to clear up the orphan record which we created above.
3719          * However, if this was a real unlink then we were called by
3720          * ext4_delete_inode(), and we allow that function to clean up the
3721          * orphan info for us.
3722          */
3723         if (inode->i_nlink)
3724                 ext4_orphan_del(handle, inode);
3725
3726         inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
3727         ext4_mark_inode_dirty(handle, inode);
3728         ext4_journal_stop(handle);
3729 }
3730
3731 static void ext4_falloc_update_inode(struct inode *inode,
3732                                 int mode, loff_t new_size, int update_ctime)
3733 {
3734         struct timespec now;
3735
3736         if (update_ctime) {
3737                 now = current_fs_time(inode->i_sb);
3738                 if (!timespec_equal(&inode->i_ctime, &now))
3739                         inode->i_ctime = now;
3740         }
3741         /*
3742          * Update only when preallocation was requested beyond
3743          * the file size.
3744          */
3745         if (!(mode & FALLOC_FL_KEEP_SIZE)) {
3746                 if (new_size > i_size_read(inode))
3747                         i_size_write(inode, new_size);
3748                 if (new_size > EXT4_I(inode)->i_disksize)
3749                         ext4_update_i_disksize(inode, new_size);
3750         } else {
3751                 /*
3752                  * Mark that we allocate beyond EOF so the subsequent truncate
3753                  * can proceed even if the new size is the same as i_size.
3754                  */
3755                 if (new_size > i_size_read(inode))
3756                         ext4_set_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
3757         }
3758
3759 }
3760
3761 /*
3762  * preallocate space for a file. This implements ext4's fallocate file
3763  * operation, which gets called from sys_fallocate system call.
3764  * For block-mapped files, posix_fallocate should fall back to the method
3765  * of writing zeroes to the required new blocks (the same behavior which is
3766  * expected for file systems which do not support fallocate() system call).
3767  */
3768 long ext4_fallocate(struct file *file, int mode, loff_t offset, loff_t len)
3769 {
3770         struct inode *inode = file->f_path.dentry->d_inode;
3771         handle_t *handle;
3772         loff_t new_size;
3773         unsigned int max_blocks;
3774         int ret = 0;
3775         int ret2 = 0;
3776         int retries = 0;
3777         struct ext4_map_blocks map;
3778         unsigned int credits, blkbits = inode->i_blkbits;
3779
3780         /*
3781          * currently supporting (pre)allocate mode for extent-based
3782          * files _only_
3783          */
3784         if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
3785                 return -EOPNOTSUPP;
3786
3787         /* Return error if mode is not supported */
3788         if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE))
3789                 return -EOPNOTSUPP;
3790
3791         if (mode & FALLOC_FL_PUNCH_HOLE)
3792                 return ext4_punch_hole(file, offset, len);
3793
3794         trace_ext4_fallocate_enter(inode, offset, len, mode);
3795         map.m_lblk = offset >> blkbits;
3796         /*
3797          * We can't just convert len to max_blocks because
3798          * If blocksize = 4096 offset = 3072 and len = 2048
3799          */
3800         max_blocks = (EXT4_BLOCK_ALIGN(len + offset, blkbits) >> blkbits)
3801                 - map.m_lblk;
3802         /*
3803          * credits to insert 1 extent into extent tree
3804          */
3805         credits = ext4_chunk_trans_blocks(inode, max_blocks);
3806         mutex_lock(&inode->i_mutex);
3807         ret = inode_newsize_ok(inode, (len + offset));
3808         if (ret) {
3809                 mutex_unlock(&inode->i_mutex);
3810                 trace_ext4_fallocate_exit(inode, offset, max_blocks, ret);
3811                 return ret;
3812         }
3813 retry:
3814         while (ret >= 0 && ret < max_blocks) {
3815                 map.m_lblk = map.m_lblk + ret;
3816                 map.m_len = max_blocks = max_blocks - ret;
3817                 handle = ext4_journal_start(inode, credits);
3818                 if (IS_ERR(handle)) {
3819                         ret = PTR_ERR(handle);
3820                         break;
3821                 }
3822                 ret = ext4_map_blocks(handle, inode, &map,
3823                                       EXT4_GET_BLOCKS_CREATE_UNINIT_EXT |
3824                                       EXT4_GET_BLOCKS_NO_NORMALIZE);
3825                 if (ret <= 0) {
3826 #ifdef EXT4FS_DEBUG
3827                         WARN_ON(ret <= 0);
3828                         printk(KERN_ERR "%s: ext4_ext_map_blocks "
3829                                     "returned error inode#%lu, block=%u, "
3830                                     "max_blocks=%u", __func__,
3831                                     inode->i_ino, map.m_lblk, max_blocks);
3832 #endif
3833                         ext4_mark_inode_dirty(handle, inode);
3834                         ret2 = ext4_journal_stop(handle);
3835                         break;
3836                 }
3837                 if ((map.m_lblk + ret) >= (EXT4_BLOCK_ALIGN(offset + len,
3838                                                 blkbits) >> blkbits))
3839                         new_size = offset + len;
3840                 else
3841                         new_size = (map.m_lblk + ret) << blkbits;
3842
3843                 ext4_falloc_update_inode(inode, mode, new_size,
3844                                          (map.m_flags & EXT4_MAP_NEW));
3845                 ext4_mark_inode_dirty(handle, inode);
3846                 ret2 = ext4_journal_stop(handle);
3847                 if (ret2)
3848                         break;
3849         }
3850         if (ret == -ENOSPC &&
3851                         ext4_should_retry_alloc(inode->i_sb, &retries)) {
3852                 ret = 0;
3853                 goto retry;
3854         }
3855         mutex_unlock(&inode->i_mutex);
3856         trace_ext4_fallocate_exit(inode, offset, max_blocks,
3857                                 ret > 0 ? ret2 : ret);
3858         return ret > 0 ? ret2 : ret;
3859 }
3860
3861 /*
3862  * This function convert a range of blocks to written extents
3863  * The caller of this function will pass the start offset and the size.
3864  * all unwritten extents within this range will be converted to
3865  * written extents.
3866  *
3867  * This function is called from the direct IO end io call back
3868  * function, to convert the fallocated extents after IO is completed.
3869  * Returns 0 on success.
3870  */
3871 int ext4_convert_unwritten_extents(struct inode *inode, loff_t offset,
3872                                     ssize_t len)
3873 {
3874         handle_t *handle;
3875         unsigned int max_blocks;
3876         int ret = 0;
3877         int ret2 = 0;
3878         struct ext4_map_blocks map;
3879         unsigned int credits, blkbits = inode->i_blkbits;
3880
3881         map.m_lblk = offset >> blkbits;
3882         /*
3883          * We can't just convert len to max_blocks because
3884          * If blocksize = 4096 offset = 3072 and len = 2048
3885          */
3886         max_blocks = ((EXT4_BLOCK_ALIGN(len + offset, blkbits) >> blkbits) -
3887                       map.m_lblk);
3888         /*
3889          * credits to insert 1 extent into extent tree
3890          */
3891         credits = ext4_chunk_trans_blocks(inode, max_blocks);
3892         while (ret >= 0 && ret < max_blocks) {
3893                 map.m_lblk += ret;
3894                 map.m_len = (max_blocks -= ret);
3895                 handle = ext4_journal_start(inode, credits);
3896                 if (IS_ERR(handle)) {
3897                         ret = PTR_ERR(handle);
3898                         break;
3899                 }
3900                 ret = ext4_map_blocks(handle, inode, &map,
3901                                       EXT4_GET_BLOCKS_IO_CONVERT_EXT);
3902                 if (ret <= 0) {
3903                         WARN_ON(ret <= 0);
3904                         printk(KERN_ERR "%s: ext4_ext_map_blocks "
3905                                     "returned error inode#%lu, block=%u, "
3906                                     "max_blocks=%u", __func__,
3907                                     inode->i_ino, map.m_lblk, map.m_len);
3908                 }
3909                 ext4_mark_inode_dirty(handle, inode);
3910                 ret2 = ext4_journal_stop(handle);
3911                 if (ret <= 0 || ret2 )
3912                         break;
3913         }
3914         return ret > 0 ? ret2 : ret;
3915 }
3916
3917 /*
3918  * Callback function called for each extent to gather FIEMAP information.
3919  */
3920 static int ext4_ext_fiemap_cb(struct inode *inode, ext4_lblk_t next,
3921                        struct ext4_ext_cache *newex, struct ext4_extent *ex,
3922                        void *data)
3923 {
3924         __u64   logical;
3925         __u64   physical;
3926         __u64   length;
3927         __u32   flags = 0;
3928         int             ret = 0;
3929         struct fiemap_extent_info *fieinfo = data;
3930         unsigned char blksize_bits;
3931
3932         blksize_bits = inode->i_sb->s_blocksize_bits;
3933         logical = (__u64)newex->ec_block << blksize_bits;
3934
3935         if (newex->ec_start == 0) {
3936                 /*
3937                  * No extent in extent-tree contains block @newex->ec_start,
3938                  * then the block may stay in 1)a hole or 2)delayed-extent.
3939                  *
3940                  * Holes or delayed-extents are processed as follows.
3941                  * 1. lookup dirty pages with specified range in pagecache.
3942                  *    If no page is got, then there is no delayed-extent and
3943                  *    return with EXT_CONTINUE.
3944                  * 2. find the 1st mapped buffer,
3945                  * 3. check if the mapped buffer is both in the request range
3946                  *    and a delayed buffer. If not, there is no delayed-extent,
3947                  *    then return.
3948                  * 4. a delayed-extent is found, the extent will be collected.
3949                  */
3950                 ext4_lblk_t     end = 0;
3951                 pgoff_t         last_offset;
3952                 pgoff_t         offset;
3953                 pgoff_t         index;
3954                 pgoff_t         start_index = 0;
3955                 struct page     **pages = NULL;
3956                 struct buffer_head *bh = NULL;
3957                 struct buffer_head *head = NULL;
3958                 unsigned int nr_pages = PAGE_SIZE / sizeof(struct page *);
3959
3960                 pages = kmalloc(PAGE_SIZE, GFP_KERNEL);
3961                 if (pages == NULL)
3962                         return -ENOMEM;
3963
3964                 offset = logical >> PAGE_SHIFT;
3965 repeat:
3966                 last_offset = offset;
3967                 head = NULL;
3968                 ret = find_get_pages_tag(inode->i_mapping, &offset,
3969                                         PAGECACHE_TAG_DIRTY, nr_pages, pages);
3970
3971                 if (!(flags & FIEMAP_EXTENT_DELALLOC)) {
3972                         /* First time, try to find a mapped buffer. */
3973                         if (ret == 0) {
3974 out:
3975                                 for (index = 0; index < ret; index++)
3976                                         page_cache_release(pages[index]);
3977                                 /* just a hole. */
3978                                 kfree(pages);
3979                                 return EXT_CONTINUE;
3980                         }
3981                         index = 0;
3982
3983 next_page:
3984                         /* Try to find the 1st mapped buffer. */
3985                         end = ((__u64)pages[index]->index << PAGE_SHIFT) >>
3986                                   blksize_bits;
3987                         if (!page_has_buffers(pages[index]))
3988                                 goto out;
3989                         head = page_buffers(pages[index]);
3990                         if (!head)
3991                                 goto out;
3992
3993                         index++;
3994                         bh = head;
3995                         do {
3996                                 if (end >= newex->ec_block +
3997                                         newex->ec_len)
3998                                         /* The buffer is out of
3999                                          * the request range.
4000                                          */
4001                                         goto out;
4002
4003                                 if (buffer_mapped(bh) &&
4004                                     end >= newex->ec_block) {
4005                                         start_index = index - 1;
4006                                         /* get the 1st mapped buffer. */
4007                                         goto found_mapped_buffer;
4008                                 }
4009
4010                                 bh = bh->b_this_page;
4011                                 end++;
4012                         } while (bh != head);
4013
4014                         /* No mapped buffer in the range found in this page,
4015                          * We need to look up next page.
4016                          */
4017                         if (index >= ret) {
4018                                 /* There is no page left, but we need to limit
4019                                  * newex->ec_len.
4020                                  */
4021                                 newex->ec_len = end - newex->ec_block;
4022                                 goto out;
4023                         }
4024                         goto next_page;
4025                 } else {
4026                         /*Find contiguous delayed buffers. */
4027                         if (ret > 0 && pages[0]->index == last_offset)
4028                                 head = page_buffers(pages[0]);
4029                         bh = head;
4030                         index = 1;
4031                         start_index = 0;
4032                 }
4033
4034 found_mapped_buffer:
4035                 if (bh != NULL && buffer_delay(bh)) {
4036                         /* 1st or contiguous delayed buffer found. */
4037                         if (!(flags & FIEMAP_EXTENT_DELALLOC)) {
4038                                 /*
4039                                  * 1st delayed buffer found, record
4040                                  * the start of extent.
4041                                  */
4042                                 flags |= FIEMAP_EXTENT_DELALLOC;
4043                                 newex->ec_block = end;
4044                                 logical = (__u64)end << blksize_bits;
4045                         }
4046                         /* Find contiguous delayed buffers. */
4047                         do {
4048                                 if (!buffer_delay(bh))
4049                                         goto found_delayed_extent;
4050                                 bh = bh->b_this_page;
4051                                 end++;
4052                         } while (bh != head);
4053
4054                         for (; index < ret; index++) {
4055                                 if (!page_has_buffers(pages[index])) {
4056                                         bh = NULL;
4057                                         break;
4058                                 }
4059                                 head = page_buffers(pages[index]);
4060                                 if (!head) {
4061                                         bh = NULL;
4062                                         break;
4063                                 }
4064
4065                                 if (pages[index]->index !=
4066                                     pages[start_index]->index + index
4067                                     - start_index) {
4068                                         /* Blocks are not contiguous. */
4069                                         bh = NULL;
4070                                         break;
4071                                 }
4072                                 bh = head;
4073                                 do {
4074                                         if (!buffer_delay(bh))
4075                                                 /* Delayed-extent ends. */
4076                                                 goto found_delayed_extent;
4077                                         bh = bh->b_this_page;
4078                                         end++;
4079                                 } while (bh != head);
4080                         }
4081                 } else if (!(flags & FIEMAP_EXTENT_DELALLOC))
4082                         /* a hole found. */
4083                         goto out;
4084
4085 found_delayed_extent:
4086                 newex->ec_len = min(end - newex->ec_block,
4087                                                 (ext4_lblk_t)EXT_INIT_MAX_LEN);
4088                 if (ret == nr_pages && bh != NULL &&
4089                         newex->ec_len < EXT_INIT_MAX_LEN &&
4090                         buffer_delay(bh)) {
4091                         /* Have not collected an extent and continue. */
4092                         for (index = 0; index < ret; index++)
4093                                 page_cache_release(pages[index]);
4094                         goto repeat;
4095                 }
4096
4097                 for (index = 0; index < ret; index++)
4098                         page_cache_release(pages[index]);
4099                 kfree(pages);
4100         }
4101
4102         physical = (__u64)newex->ec_start << blksize_bits;
4103         length =   (__u64)newex->ec_len << blksize_bits;
4104
4105         if (ex && ext4_ext_is_uninitialized(ex))
4106                 flags |= FIEMAP_EXTENT_UNWRITTEN;
4107
4108         if (next == EXT_MAX_BLOCKS)
4109                 flags |= FIEMAP_EXTENT_LAST;
4110
4111         ret = fiemap_fill_next_extent(fieinfo, logical, physical,
4112                                         length, flags);
4113         if (ret < 0)
4114                 return ret;
4115         if (ret == 1)
4116                 return EXT_BREAK;
4117         return EXT_CONTINUE;
4118 }
4119
4120 /* fiemap flags we can handle specified here */
4121 #define EXT4_FIEMAP_FLAGS       (FIEMAP_FLAG_SYNC|FIEMAP_FLAG_XATTR)
4122
4123 static int ext4_xattr_fiemap(struct inode *inode,
4124                                 struct fiemap_extent_info *fieinfo)
4125 {
4126         __u64 physical = 0;
4127         __u64 length;
4128         __u32 flags = FIEMAP_EXTENT_LAST;
4129         int blockbits = inode->i_sb->s_blocksize_bits;
4130         int error = 0;
4131
4132         /* in-inode? */
4133         if (ext4_test_inode_state(inode, EXT4_STATE_XATTR)) {
4134                 struct ext4_iloc iloc;
4135                 int offset;     /* offset of xattr in inode */
4136
4137                 error = ext4_get_inode_loc(inode, &iloc);
4138                 if (error)
4139                         return error;
4140                 physical = iloc.bh->b_blocknr << blockbits;
4141                 offset = EXT4_GOOD_OLD_INODE_SIZE +
4142                                 EXT4_I(inode)->i_extra_isize;
4143                 physical += offset;
4144                 length = EXT4_SB(inode->i_sb)->s_inode_size - offset;
4145                 flags |= FIEMAP_EXTENT_DATA_INLINE;
4146                 brelse(iloc.bh);
4147         } else { /* external block */
4148                 physical = EXT4_I(inode)->i_file_acl << blockbits;
4149                 length = inode->i_sb->s_blocksize;
4150         }
4151
4152         if (physical)
4153                 error = fiemap_fill_next_extent(fieinfo, 0, physical,
4154                                                 length, flags);
4155         return (error < 0 ? error : 0);
4156 }
4157
4158 /*
4159  * ext4_ext_punch_hole
4160  *
4161  * Punches a hole of "length" bytes in a file starting
4162  * at byte "offset"
4163  *
4164  * @inode:  The inode of the file to punch a hole in
4165  * @offset: The starting byte offset of the hole
4166  * @length: The length of the hole
4167  *
4168  * Returns the number of blocks removed or negative on err
4169  */
4170 int ext4_ext_punch_hole(struct file *file, loff_t offset, loff_t length)
4171 {
4172         struct inode *inode = file->f_path.dentry->d_inode;
4173         struct super_block *sb = inode->i_sb;
4174         struct ext4_ext_cache cache_ex;
4175         ext4_lblk_t first_block, last_block, num_blocks, iblock, max_blocks;
4176         struct address_space *mapping = inode->i_mapping;
4177         struct ext4_map_blocks map;
4178         handle_t *handle;
4179         loff_t first_block_offset, last_block_offset, block_len;
4180         loff_t first_page, last_page, first_page_offset, last_page_offset;
4181         int ret, credits, blocks_released, err = 0;
4182
4183         first_block = (offset + sb->s_blocksize - 1) >>
4184                 EXT4_BLOCK_SIZE_BITS(sb);
4185         last_block = (offset + length) >> EXT4_BLOCK_SIZE_BITS(sb);
4186
4187         first_block_offset = first_block << EXT4_BLOCK_SIZE_BITS(sb);
4188         last_block_offset = last_block << EXT4_BLOCK_SIZE_BITS(sb);
4189
4190         first_page = (offset + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
4191         last_page = (offset + length) >> PAGE_CACHE_SHIFT;
4192
4193         first_page_offset = first_page << PAGE_CACHE_SHIFT;
4194         last_page_offset = last_page << PAGE_CACHE_SHIFT;
4195
4196         /*
4197          * Write out all dirty pages to avoid race conditions
4198          * Then release them.
4199          */
4200         if (mapping->nrpages && mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) {
4201                 err = filemap_write_and_wait_range(mapping,
4202                         first_page_offset == 0 ? 0 : first_page_offset-1,
4203                         last_page_offset);
4204
4205                         if (err)
4206                                 return err;
4207         }
4208
4209         /* Now release the pages */
4210         if (last_page_offset > first_page_offset) {
4211                 truncate_inode_pages_range(mapping, first_page_offset,
4212                                            last_page_offset-1);
4213         }
4214
4215         /* finish any pending end_io work */
4216         ext4_flush_completed_IO(inode);
4217
4218         credits = ext4_writepage_trans_blocks(inode);
4219         handle = ext4_journal_start(inode, credits);
4220         if (IS_ERR(handle))
4221                 return PTR_ERR(handle);
4222
4223         err = ext4_orphan_add(handle, inode);
4224         if (err)
4225                 goto out;
4226
4227         /*
4228          * Now we need to zero out the un block aligned data.
4229          * If the file is smaller than a block, just
4230          * zero out the middle
4231          */
4232         if (first_block > last_block)
4233                 ext4_block_zero_page_range(handle, mapping, offset, length);
4234         else {
4235                 /* zero out the head of the hole before the first block */
4236                 block_len  = first_block_offset - offset;
4237                 if (block_len > 0)
4238                         ext4_block_zero_page_range(handle, mapping,
4239                                                    offset, block_len);
4240
4241                 /* zero out the tail of the hole after the last block */
4242                 block_len = offset + length - last_block_offset;
4243                 if (block_len > 0) {
4244                         ext4_block_zero_page_range(handle, mapping,
4245                                         last_block_offset, block_len);
4246                 }
4247         }
4248
4249         /* If there are no blocks to remove, return now */
4250         if (first_block >= last_block)
4251                 goto out;
4252
4253         down_write(&EXT4_I(inode)->i_data_sem);
4254         ext4_ext_invalidate_cache(inode);
4255         ext4_discard_preallocations(inode);
4256
4257         /*
4258          * Loop over all the blocks and identify blocks
4259          * that need to be punched out
4260          */
4261         iblock = first_block;
4262         blocks_released = 0;
4263         while (iblock < last_block) {
4264                 max_blocks = last_block - iblock;
4265                 num_blocks = 1;
4266                 memset(&map, 0, sizeof(map));
4267                 map.m_lblk = iblock;
4268                 map.m_len = max_blocks;
4269                 ret = ext4_ext_map_blocks(handle, inode, &map,
4270                         EXT4_GET_BLOCKS_PUNCH_OUT_EXT);
4271
4272                 if (ret > 0) {
4273                         blocks_released += ret;
4274                         num_blocks = ret;
4275                 } else if (ret == 0) {
4276                         /*
4277                          * If map blocks could not find the block,
4278                          * then it is in a hole.  If the hole was
4279                          * not already cached, then map blocks should
4280                          * put it in the cache.  So we can get the hole
4281                          * out of the cache
4282                          */
4283                         memset(&cache_ex, 0, sizeof(cache_ex));
4284                         if ((ext4_ext_check_cache(inode, iblock, &cache_ex)) &&
4285                                 !cache_ex.ec_start) {
4286
4287                                 /* The hole is cached */
4288                                 num_blocks = cache_ex.ec_block +
4289                                 cache_ex.ec_len - iblock;
4290
4291                         } else {
4292                                 /* The block could not be identified */
4293                                 err = -EIO;
4294                                 break;
4295                         }
4296                 } else {
4297                         /* Map blocks error */
4298                         err = ret;
4299                         break;
4300                 }
4301
4302                 if (num_blocks == 0) {
4303                         /* This condition should never happen */
4304                         ext_debug("Block lookup failed");
4305                         err = -EIO;
4306                         break;
4307                 }
4308
4309                 iblock += num_blocks;
4310         }
4311
4312         if (blocks_released > 0) {
4313                 ext4_ext_invalidate_cache(inode);
4314                 ext4_discard_preallocations(inode);
4315         }
4316
4317         if (IS_SYNC(inode))
4318                 ext4_handle_sync(handle);
4319
4320         up_write(&EXT4_I(inode)->i_data_sem);
4321
4322 out:
4323         ext4_orphan_del(handle, inode);
4324         inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
4325         ext4_mark_inode_dirty(handle, inode);
4326         ext4_journal_stop(handle);
4327         return err;
4328 }
4329 int ext4_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
4330                 __u64 start, __u64 len)
4331 {
4332         ext4_lblk_t start_blk;
4333         int error = 0;
4334
4335         /* fallback to generic here if not in extents fmt */
4336         if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
4337                 return generic_block_fiemap(inode, fieinfo, start, len,
4338                         ext4_get_block);
4339
4340         if (fiemap_check_flags(fieinfo, EXT4_FIEMAP_FLAGS))
4341                 return -EBADR;
4342
4343         if (fieinfo->fi_flags & FIEMAP_FLAG_XATTR) {
4344                 error = ext4_xattr_fiemap(inode, fieinfo);
4345         } else {
4346                 ext4_lblk_t len_blks;
4347                 __u64 last_blk;
4348
4349                 start_blk = start >> inode->i_sb->s_blocksize_bits;
4350                 last_blk = (start + len - 1) >> inode->i_sb->s_blocksize_bits;
4351                 if (last_blk >= EXT_MAX_BLOCKS)
4352                         last_blk = EXT_MAX_BLOCKS-1;
4353                 len_blks = ((ext4_lblk_t) last_blk) - start_blk + 1;
4354
4355                 /*
4356                  * Walk the extent tree gathering extent information.
4357                  * ext4_ext_fiemap_cb will push extents back to user.
4358                  */
4359                 error = ext4_ext_walk_space(inode, start_blk, len_blks,
4360                                           ext4_ext_fiemap_cb, fieinfo);
4361         }
4362
4363         return error;
4364 }