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