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