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