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