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