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