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