]> asedeno.scripts.mit.edu Git - linux.git/blob - fs/ext4/extents.c
ext4: re-enable extent zeroout optimization on encrypted files
[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         /*
3723          * five cases:
3724          * 1. split the extent into three extents.
3725          * 2. split the extent into two extents, zeroout the head of the first
3726          *    extent.
3727          * 3. split the extent into two extents, zeroout the tail of the second
3728          *    extent.
3729          * 4. split the extent into two extents with out zeroout.
3730          * 5. no splitting needed, just possibly zeroout the head and / or the
3731          *    tail of the extent.
3732          */
3733         split_map.m_lblk = map->m_lblk;
3734         split_map.m_len = map->m_len;
3735
3736         if (max_zeroout && (allocated > split_map.m_len)) {
3737                 if (allocated <= max_zeroout) {
3738                         /* case 3 or 5 */
3739                         zero_ex1.ee_block =
3740                                  cpu_to_le32(split_map.m_lblk +
3741                                              split_map.m_len);
3742                         zero_ex1.ee_len =
3743                                 cpu_to_le16(allocated - split_map.m_len);
3744                         ext4_ext_store_pblock(&zero_ex1,
3745                                 ext4_ext_pblock(ex) + split_map.m_lblk +
3746                                 split_map.m_len - ee_block);
3747                         err = ext4_ext_zeroout(inode, &zero_ex1);
3748                         if (err)
3749                                 goto out;
3750                         split_map.m_len = allocated;
3751                 }
3752                 if (split_map.m_lblk - ee_block + split_map.m_len <
3753                                                                 max_zeroout) {
3754                         /* case 2 or 5 */
3755                         if (split_map.m_lblk != ee_block) {
3756                                 zero_ex2.ee_block = ex->ee_block;
3757                                 zero_ex2.ee_len = cpu_to_le16(split_map.m_lblk -
3758                                                         ee_block);
3759                                 ext4_ext_store_pblock(&zero_ex2,
3760                                                       ext4_ext_pblock(ex));
3761                                 err = ext4_ext_zeroout(inode, &zero_ex2);
3762                                 if (err)
3763                                         goto out;
3764                         }
3765
3766                         split_map.m_len += split_map.m_lblk - ee_block;
3767                         split_map.m_lblk = ee_block;
3768                         allocated = map->m_len;
3769                 }
3770         }
3771
3772         err = ext4_split_extent(handle, inode, ppath, &split_map, split_flag,
3773                                 flags);
3774         if (err > 0)
3775                 err = 0;
3776 out:
3777         /* If we have gotten a failure, don't zero out status tree */
3778         if (!err) {
3779                 err = ext4_zeroout_es(inode, &zero_ex1);
3780                 if (!err)
3781                         err = ext4_zeroout_es(inode, &zero_ex2);
3782         }
3783         return err ? err : allocated;
3784 }
3785
3786 /*
3787  * This function is called by ext4_ext_map_blocks() from
3788  * ext4_get_blocks_dio_write() when DIO to write
3789  * to an unwritten extent.
3790  *
3791  * Writing to an unwritten extent may result in splitting the unwritten
3792  * extent into multiple initialized/unwritten extents (up to three)
3793  * There are three possibilities:
3794  *   a> There is no split required: Entire extent should be unwritten
3795  *   b> Splits in two extents: Write is happening at either end of the extent
3796  *   c> Splits in three extents: Somone is writing in middle of the extent
3797  *
3798  * This works the same way in the case of initialized -> unwritten conversion.
3799  *
3800  * One of more index blocks maybe needed if the extent tree grow after
3801  * the unwritten extent split. To prevent ENOSPC occur at the IO
3802  * complete, we need to split the unwritten extent before DIO submit
3803  * the IO. The unwritten extent called at this time will be split
3804  * into three unwritten extent(at most). After IO complete, the part
3805  * being filled will be convert to initialized by the end_io callback function
3806  * via ext4_convert_unwritten_extents().
3807  *
3808  * Returns the size of unwritten extent to be written on success.
3809  */
3810 static int ext4_split_convert_extents(handle_t *handle,
3811                                         struct inode *inode,
3812                                         struct ext4_map_blocks *map,
3813                                         struct ext4_ext_path **ppath,
3814                                         int flags)
3815 {
3816         struct ext4_ext_path *path = *ppath;
3817         ext4_lblk_t eof_block;
3818         ext4_lblk_t ee_block;
3819         struct ext4_extent *ex;
3820         unsigned int ee_len;
3821         int split_flag = 0, depth;
3822
3823         ext_debug("%s: inode %lu, logical block %llu, max_blocks %u\n",
3824                   __func__, inode->i_ino,
3825                   (unsigned long long)map->m_lblk, map->m_len);
3826
3827         eof_block = (inode->i_size + inode->i_sb->s_blocksize - 1) >>
3828                 inode->i_sb->s_blocksize_bits;
3829         if (eof_block < map->m_lblk + map->m_len)
3830                 eof_block = map->m_lblk + map->m_len;
3831         /*
3832          * It is safe to convert extent to initialized via explicit
3833          * zeroout only if extent is fully insde i_size or new_size.
3834          */
3835         depth = ext_depth(inode);
3836         ex = path[depth].p_ext;
3837         ee_block = le32_to_cpu(ex->ee_block);
3838         ee_len = ext4_ext_get_actual_len(ex);
3839
3840         /* Convert to unwritten */
3841         if (flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN) {
3842                 split_flag |= EXT4_EXT_DATA_VALID1;
3843         /* Convert to initialized */
3844         } else if (flags & EXT4_GET_BLOCKS_CONVERT) {
3845                 split_flag |= ee_block + ee_len <= eof_block ?
3846                               EXT4_EXT_MAY_ZEROOUT : 0;
3847                 split_flag |= (EXT4_EXT_MARK_UNWRIT2 | EXT4_EXT_DATA_VALID2);
3848         }
3849         flags |= EXT4_GET_BLOCKS_PRE_IO;
3850         return ext4_split_extent(handle, inode, ppath, map, split_flag, flags);
3851 }
3852
3853 static int ext4_convert_unwritten_extents_endio(handle_t *handle,
3854                                                 struct inode *inode,
3855                                                 struct ext4_map_blocks *map,
3856                                                 struct ext4_ext_path **ppath)
3857 {
3858         struct ext4_ext_path *path = *ppath;
3859         struct ext4_extent *ex;
3860         ext4_lblk_t ee_block;
3861         unsigned int ee_len;
3862         int depth;
3863         int err = 0;
3864
3865         depth = ext_depth(inode);
3866         ex = path[depth].p_ext;
3867         ee_block = le32_to_cpu(ex->ee_block);
3868         ee_len = ext4_ext_get_actual_len(ex);
3869
3870         ext_debug("ext4_convert_unwritten_extents_endio: inode %lu, logical"
3871                 "block %llu, max_blocks %u\n", inode->i_ino,
3872                   (unsigned long long)ee_block, ee_len);
3873
3874         /* If extent is larger than requested it is a clear sign that we still
3875          * have some extent state machine issues left. So extent_split is still
3876          * required.
3877          * TODO: Once all related issues will be fixed this situation should be
3878          * illegal.
3879          */
3880         if (ee_block != map->m_lblk || ee_len > map->m_len) {
3881 #ifdef CONFIG_EXT4_DEBUG
3882                 ext4_warning(inode->i_sb, "Inode (%ld) finished: extent logical block %llu,"
3883                              " len %u; IO logical block %llu, len %u",
3884                              inode->i_ino, (unsigned long long)ee_block, ee_len,
3885                              (unsigned long long)map->m_lblk, map->m_len);
3886 #endif
3887                 err = ext4_split_convert_extents(handle, inode, map, ppath,
3888                                                  EXT4_GET_BLOCKS_CONVERT);
3889                 if (err < 0)
3890                         return err;
3891                 path = ext4_find_extent(inode, map->m_lblk, ppath, 0);
3892                 if (IS_ERR(path))
3893                         return PTR_ERR(path);
3894                 depth = ext_depth(inode);
3895                 ex = path[depth].p_ext;
3896         }
3897
3898         err = ext4_ext_get_access(handle, inode, path + depth);
3899         if (err)
3900                 goto out;
3901         /* first mark the extent as initialized */
3902         ext4_ext_mark_initialized(ex);
3903
3904         /* note: ext4_ext_correct_indexes() isn't needed here because
3905          * borders are not changed
3906          */
3907         ext4_ext_try_to_merge(handle, inode, path, ex);
3908
3909         /* Mark modified extent as dirty */
3910         err = ext4_ext_dirty(handle, inode, path + path->p_depth);
3911 out:
3912         ext4_ext_show_leaf(inode, path);
3913         return err;
3914 }
3915
3916 /*
3917  * Handle EOFBLOCKS_FL flag, clearing it if necessary
3918  */
3919 static int check_eofblocks_fl(handle_t *handle, struct inode *inode,
3920                               ext4_lblk_t lblk,
3921                               struct ext4_ext_path *path,
3922                               unsigned int len)
3923 {
3924         int i, depth;
3925         struct ext4_extent_header *eh;
3926         struct ext4_extent *last_ex;
3927
3928         if (!ext4_test_inode_flag(inode, EXT4_INODE_EOFBLOCKS))
3929                 return 0;
3930
3931         depth = ext_depth(inode);
3932         eh = path[depth].p_hdr;
3933
3934         /*
3935          * We're going to remove EOFBLOCKS_FL entirely in future so we
3936          * do not care for this case anymore. Simply remove the flag
3937          * if there are no extents.
3938          */
3939         if (unlikely(!eh->eh_entries))
3940                 goto out;
3941         last_ex = EXT_LAST_EXTENT(eh);
3942         /*
3943          * We should clear the EOFBLOCKS_FL flag if we are writing the
3944          * last block in the last extent in the file.  We test this by
3945          * first checking to see if the caller to
3946          * ext4_ext_get_blocks() was interested in the last block (or
3947          * a block beyond the last block) in the current extent.  If
3948          * this turns out to be false, we can bail out from this
3949          * function immediately.
3950          */
3951         if (lblk + len < le32_to_cpu(last_ex->ee_block) +
3952             ext4_ext_get_actual_len(last_ex))
3953                 return 0;
3954         /*
3955          * If the caller does appear to be planning to write at or
3956          * beyond the end of the current extent, we then test to see
3957          * if the current extent is the last extent in the file, by
3958          * checking to make sure it was reached via the rightmost node
3959          * at each level of the tree.
3960          */
3961         for (i = depth-1; i >= 0; i--)
3962                 if (path[i].p_idx != EXT_LAST_INDEX(path[i].p_hdr))
3963                         return 0;
3964 out:
3965         ext4_clear_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
3966         return ext4_mark_inode_dirty(handle, inode);
3967 }
3968
3969 static int
3970 convert_initialized_extent(handle_t *handle, struct inode *inode,
3971                            struct ext4_map_blocks *map,
3972                            struct ext4_ext_path **ppath,
3973                            unsigned int allocated)
3974 {
3975         struct ext4_ext_path *path = *ppath;
3976         struct ext4_extent *ex;
3977         ext4_lblk_t ee_block;
3978         unsigned int ee_len;
3979         int depth;
3980         int err = 0;
3981
3982         /*
3983          * Make sure that the extent is no bigger than we support with
3984          * unwritten extent
3985          */
3986         if (map->m_len > EXT_UNWRITTEN_MAX_LEN)
3987                 map->m_len = EXT_UNWRITTEN_MAX_LEN / 2;
3988
3989         depth = ext_depth(inode);
3990         ex = path[depth].p_ext;
3991         ee_block = le32_to_cpu(ex->ee_block);
3992         ee_len = ext4_ext_get_actual_len(ex);
3993
3994         ext_debug("%s: inode %lu, logical"
3995                 "block %llu, max_blocks %u\n", __func__, inode->i_ino,
3996                   (unsigned long long)ee_block, ee_len);
3997
3998         if (ee_block != map->m_lblk || ee_len > map->m_len) {
3999                 err = ext4_split_convert_extents(handle, inode, map, ppath,
4000                                 EXT4_GET_BLOCKS_CONVERT_UNWRITTEN);
4001                 if (err < 0)
4002                         return err;
4003                 path = ext4_find_extent(inode, map->m_lblk, ppath, 0);
4004                 if (IS_ERR(path))
4005                         return PTR_ERR(path);
4006                 depth = ext_depth(inode);
4007                 ex = path[depth].p_ext;
4008                 if (!ex) {
4009                         EXT4_ERROR_INODE(inode, "unexpected hole at %lu",
4010                                          (unsigned long) map->m_lblk);
4011                         return -EFSCORRUPTED;
4012                 }
4013         }
4014
4015         err = ext4_ext_get_access(handle, inode, path + depth);
4016         if (err)
4017                 return err;
4018         /* first mark the extent as unwritten */
4019         ext4_ext_mark_unwritten(ex);
4020
4021         /* note: ext4_ext_correct_indexes() isn't needed here because
4022          * borders are not changed
4023          */
4024         ext4_ext_try_to_merge(handle, inode, path, ex);
4025
4026         /* Mark modified extent as dirty */
4027         err = ext4_ext_dirty(handle, inode, path + path->p_depth);
4028         if (err)
4029                 return err;
4030         ext4_ext_show_leaf(inode, path);
4031
4032         ext4_update_inode_fsync_trans(handle, inode, 1);
4033         err = check_eofblocks_fl(handle, inode, map->m_lblk, path, map->m_len);
4034         if (err)
4035                 return err;
4036         map->m_flags |= EXT4_MAP_UNWRITTEN;
4037         if (allocated > map->m_len)
4038                 allocated = map->m_len;
4039         map->m_len = allocated;
4040         return allocated;
4041 }
4042
4043 static int
4044 ext4_ext_handle_unwritten_extents(handle_t *handle, struct inode *inode,
4045                         struct ext4_map_blocks *map,
4046                         struct ext4_ext_path **ppath, int flags,
4047                         unsigned int allocated, ext4_fsblk_t newblock)
4048 {
4049         struct ext4_ext_path *path = *ppath;
4050         int ret = 0;
4051         int err = 0;
4052
4053         ext_debug("ext4_ext_handle_unwritten_extents: inode %lu, logical "
4054                   "block %llu, max_blocks %u, flags %x, allocated %u\n",
4055                   inode->i_ino, (unsigned long long)map->m_lblk, map->m_len,
4056                   flags, allocated);
4057         ext4_ext_show_leaf(inode, path);
4058
4059         /*
4060          * When writing into unwritten space, we should not fail to
4061          * allocate metadata blocks for the new extent block if needed.
4062          */
4063         flags |= EXT4_GET_BLOCKS_METADATA_NOFAIL;
4064
4065         trace_ext4_ext_handle_unwritten_extents(inode, map, flags,
4066                                                     allocated, newblock);
4067
4068         /* get_block() before submit the IO, split the extent */
4069         if (flags & EXT4_GET_BLOCKS_PRE_IO) {
4070                 ret = ext4_split_convert_extents(handle, inode, map, ppath,
4071                                          flags | EXT4_GET_BLOCKS_CONVERT);
4072                 if (ret <= 0)
4073                         goto out;
4074                 map->m_flags |= EXT4_MAP_UNWRITTEN;
4075                 goto out;
4076         }
4077         /* IO end_io complete, convert the filled extent to written */
4078         if (flags & EXT4_GET_BLOCKS_CONVERT) {
4079                 if (flags & EXT4_GET_BLOCKS_ZERO) {
4080                         if (allocated > map->m_len)
4081                                 allocated = map->m_len;
4082                         err = ext4_issue_zeroout(inode, map->m_lblk, newblock,
4083                                                  allocated);
4084                         if (err < 0)
4085                                 goto out2;
4086                 }
4087                 ret = ext4_convert_unwritten_extents_endio(handle, inode, map,
4088                                                            ppath);
4089                 if (ret >= 0) {
4090                         ext4_update_inode_fsync_trans(handle, inode, 1);
4091                         err = check_eofblocks_fl(handle, inode, map->m_lblk,
4092                                                  path, map->m_len);
4093                 } else
4094                         err = ret;
4095                 map->m_flags |= EXT4_MAP_MAPPED;
4096                 map->m_pblk = newblock;
4097                 if (allocated > map->m_len)
4098                         allocated = map->m_len;
4099                 map->m_len = allocated;
4100                 goto out2;
4101         }
4102         /* buffered IO case */
4103         /*
4104          * repeat fallocate creation request
4105          * we already have an unwritten extent
4106          */
4107         if (flags & EXT4_GET_BLOCKS_UNWRIT_EXT) {
4108                 map->m_flags |= EXT4_MAP_UNWRITTEN;
4109                 goto map_out;
4110         }
4111
4112         /* buffered READ or buffered write_begin() lookup */
4113         if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
4114                 /*
4115                  * We have blocks reserved already.  We
4116                  * return allocated blocks so that delalloc
4117                  * won't do block reservation for us.  But
4118                  * the buffer head will be unmapped so that
4119                  * a read from the block returns 0s.
4120                  */
4121                 map->m_flags |= EXT4_MAP_UNWRITTEN;
4122                 goto out1;
4123         }
4124
4125         /* buffered write, writepage time, convert*/
4126         ret = ext4_ext_convert_to_initialized(handle, inode, map, ppath, flags);
4127         if (ret >= 0)
4128                 ext4_update_inode_fsync_trans(handle, inode, 1);
4129 out:
4130         if (ret <= 0) {
4131                 err = ret;
4132                 goto out2;
4133         } else
4134                 allocated = ret;
4135         map->m_flags |= EXT4_MAP_NEW;
4136         if (allocated > map->m_len)
4137                 allocated = map->m_len;
4138         map->m_len = allocated;
4139
4140 map_out:
4141         map->m_flags |= EXT4_MAP_MAPPED;
4142         if ((flags & EXT4_GET_BLOCKS_KEEP_SIZE) == 0) {
4143                 err = check_eofblocks_fl(handle, inode, map->m_lblk, path,
4144                                          map->m_len);
4145                 if (err < 0)
4146                         goto out2;
4147         }
4148 out1:
4149         if (allocated > map->m_len)
4150                 allocated = map->m_len;
4151         ext4_ext_show_leaf(inode, path);
4152         map->m_pblk = newblock;
4153         map->m_len = allocated;
4154 out2:
4155         return err ? err : allocated;
4156 }
4157
4158 /*
4159  * get_implied_cluster_alloc - check to see if the requested
4160  * allocation (in the map structure) overlaps with a cluster already
4161  * allocated in an extent.
4162  *      @sb     The filesystem superblock structure
4163  *      @map    The requested lblk->pblk mapping
4164  *      @ex     The extent structure which might contain an implied
4165  *                      cluster allocation
4166  *
4167  * This function is called by ext4_ext_map_blocks() after we failed to
4168  * find blocks that were already in the inode's extent tree.  Hence,
4169  * we know that the beginning of the requested region cannot overlap
4170  * the extent from the inode's extent tree.  There are three cases we
4171  * want to catch.  The first is this case:
4172  *
4173  *               |--- cluster # N--|
4174  *    |--- extent ---|  |---- requested region ---|
4175  *                      |==========|
4176  *
4177  * The second case that we need to test for is this one:
4178  *
4179  *   |--------- cluster # N ----------------|
4180  *         |--- requested region --|   |------- extent ----|
4181  *         |=======================|
4182  *
4183  * The third case is when the requested region lies between two extents
4184  * within the same cluster:
4185  *          |------------- cluster # N-------------|
4186  * |----- ex -----|                  |---- ex_right ----|
4187  *                  |------ requested region ------|
4188  *                  |================|
4189  *
4190  * In each of the above cases, we need to set the map->m_pblk and
4191  * map->m_len so it corresponds to the return the extent labelled as
4192  * "|====|" from cluster #N, since it is already in use for data in
4193  * cluster EXT4_B2C(sbi, map->m_lblk).  We will then return 1 to
4194  * signal to ext4_ext_map_blocks() that map->m_pblk should be treated
4195  * as a new "allocated" block region.  Otherwise, we will return 0 and
4196  * ext4_ext_map_blocks() will then allocate one or more new clusters
4197  * by calling ext4_mb_new_blocks().
4198  */
4199 static int get_implied_cluster_alloc(struct super_block *sb,
4200                                      struct ext4_map_blocks *map,
4201                                      struct ext4_extent *ex,
4202                                      struct ext4_ext_path *path)
4203 {
4204         struct ext4_sb_info *sbi = EXT4_SB(sb);
4205         ext4_lblk_t c_offset = EXT4_LBLK_COFF(sbi, map->m_lblk);
4206         ext4_lblk_t ex_cluster_start, ex_cluster_end;
4207         ext4_lblk_t rr_cluster_start;
4208         ext4_lblk_t ee_block = le32_to_cpu(ex->ee_block);
4209         ext4_fsblk_t ee_start = ext4_ext_pblock(ex);
4210         unsigned short ee_len = ext4_ext_get_actual_len(ex);
4211
4212         /* The extent passed in that we are trying to match */
4213         ex_cluster_start = EXT4_B2C(sbi, ee_block);
4214         ex_cluster_end = EXT4_B2C(sbi, ee_block + ee_len - 1);
4215
4216         /* The requested region passed into ext4_map_blocks() */
4217         rr_cluster_start = EXT4_B2C(sbi, map->m_lblk);
4218
4219         if ((rr_cluster_start == ex_cluster_end) ||
4220             (rr_cluster_start == ex_cluster_start)) {
4221                 if (rr_cluster_start == ex_cluster_end)
4222                         ee_start += ee_len - 1;
4223                 map->m_pblk = EXT4_PBLK_CMASK(sbi, ee_start) + c_offset;
4224                 map->m_len = min(map->m_len,
4225                                  (unsigned) sbi->s_cluster_ratio - c_offset);
4226                 /*
4227                  * Check for and handle this case:
4228                  *
4229                  *   |--------- cluster # N-------------|
4230                  *                     |------- extent ----|
4231                  *         |--- requested region ---|
4232                  *         |===========|
4233                  */
4234
4235                 if (map->m_lblk < ee_block)
4236                         map->m_len = min(map->m_len, ee_block - map->m_lblk);
4237
4238                 /*
4239                  * Check for the case where there is already another allocated
4240                  * block to the right of 'ex' but before the end of the cluster.
4241                  *
4242                  *          |------------- cluster # N-------------|
4243                  * |----- ex -----|                  |---- ex_right ----|
4244                  *                  |------ requested region ------|
4245                  *                  |================|
4246                  */
4247                 if (map->m_lblk > ee_block) {
4248                         ext4_lblk_t next = ext4_ext_next_allocated_block(path);
4249                         map->m_len = min(map->m_len, next - map->m_lblk);
4250                 }
4251
4252                 trace_ext4_get_implied_cluster_alloc_exit(sb, map, 1);
4253                 return 1;
4254         }
4255
4256         trace_ext4_get_implied_cluster_alloc_exit(sb, map, 0);
4257         return 0;
4258 }
4259
4260
4261 /*
4262  * Block allocation/map/preallocation routine for extents based files
4263  *
4264  *
4265  * Need to be called with
4266  * down_read(&EXT4_I(inode)->i_data_sem) if not allocating file system block
4267  * (ie, create is zero). Otherwise down_write(&EXT4_I(inode)->i_data_sem)
4268  *
4269  * return > 0, number of of blocks already mapped/allocated
4270  *          if create == 0 and these are pre-allocated blocks
4271  *              buffer head is unmapped
4272  *          otherwise blocks are mapped
4273  *
4274  * return = 0, if plain look up failed (blocks have not been allocated)
4275  *          buffer head is unmapped
4276  *
4277  * return < 0, error case.
4278  */
4279 int ext4_ext_map_blocks(handle_t *handle, struct inode *inode,
4280                         struct ext4_map_blocks *map, int flags)
4281 {
4282         struct ext4_ext_path *path = NULL;
4283         struct ext4_extent newex, *ex, *ex2;
4284         struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4285         ext4_fsblk_t newblock = 0;
4286         int free_on_err = 0, err = 0, depth, ret;
4287         unsigned int allocated = 0, offset = 0;
4288         unsigned int allocated_clusters = 0;
4289         struct ext4_allocation_request ar;
4290         ext4_lblk_t cluster_offset;
4291         bool map_from_cluster = false;
4292
4293         ext_debug("blocks %u/%u requested for inode %lu\n",
4294                   map->m_lblk, map->m_len, inode->i_ino);
4295         trace_ext4_ext_map_blocks_enter(inode, map->m_lblk, map->m_len, flags);
4296
4297         /* find extent for this block */
4298         path = ext4_find_extent(inode, map->m_lblk, NULL, 0);
4299         if (IS_ERR(path)) {
4300                 err = PTR_ERR(path);
4301                 path = NULL;
4302                 goto out2;
4303         }
4304
4305         depth = ext_depth(inode);
4306
4307         /*
4308          * consistent leaf must not be empty;
4309          * this situation is possible, though, _during_ tree modification;
4310          * this is why assert can't be put in ext4_find_extent()
4311          */
4312         if (unlikely(path[depth].p_ext == NULL && depth != 0)) {
4313                 EXT4_ERROR_INODE(inode, "bad extent address "
4314                                  "lblock: %lu, depth: %d pblock %lld",
4315                                  (unsigned long) map->m_lblk, depth,
4316                                  path[depth].p_block);
4317                 err = -EFSCORRUPTED;
4318                 goto out2;
4319         }
4320
4321         ex = path[depth].p_ext;
4322         if (ex) {
4323                 ext4_lblk_t ee_block = le32_to_cpu(ex->ee_block);
4324                 ext4_fsblk_t ee_start = ext4_ext_pblock(ex);
4325                 unsigned short ee_len;
4326
4327
4328                 /*
4329                  * unwritten extents are treated as holes, except that
4330                  * we split out initialized portions during a write.
4331                  */
4332                 ee_len = ext4_ext_get_actual_len(ex);
4333
4334                 trace_ext4_ext_show_extent(inode, ee_block, ee_start, ee_len);
4335
4336                 /* if found extent covers block, simply return it */
4337                 if (in_range(map->m_lblk, ee_block, ee_len)) {
4338                         newblock = map->m_lblk - ee_block + ee_start;
4339                         /* number of remaining blocks in the extent */
4340                         allocated = ee_len - (map->m_lblk - ee_block);
4341                         ext_debug("%u fit into %u:%d -> %llu\n", map->m_lblk,
4342                                   ee_block, ee_len, newblock);
4343
4344                         /*
4345                          * If the extent is initialized check whether the
4346                          * caller wants to convert it to unwritten.
4347                          */
4348                         if ((!ext4_ext_is_unwritten(ex)) &&
4349                             (flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN)) {
4350                                 allocated = convert_initialized_extent(
4351                                                 handle, inode, map, &path,
4352                                                 allocated);
4353                                 goto out2;
4354                         } else if (!ext4_ext_is_unwritten(ex))
4355                                 goto out;
4356
4357                         ret = ext4_ext_handle_unwritten_extents(
4358                                 handle, inode, map, &path, flags,
4359                                 allocated, newblock);
4360                         if (ret < 0)
4361                                 err = ret;
4362                         else
4363                                 allocated = ret;
4364                         goto out2;
4365                 }
4366         }
4367
4368         /*
4369          * requested block isn't allocated yet;
4370          * we couldn't try to create block if create flag is zero
4371          */
4372         if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
4373                 ext4_lblk_t hole_start, hole_len;
4374
4375                 hole_start = map->m_lblk;
4376                 hole_len = ext4_ext_determine_hole(inode, path, &hole_start);
4377                 /*
4378                  * put just found gap into cache to speed up
4379                  * subsequent requests
4380                  */
4381                 ext4_ext_put_gap_in_cache(inode, hole_start, hole_len);
4382
4383                 /* Update hole_len to reflect hole size after map->m_lblk */
4384                 if (hole_start != map->m_lblk)
4385                         hole_len -= map->m_lblk - hole_start;
4386                 map->m_pblk = 0;
4387                 map->m_len = min_t(unsigned int, map->m_len, hole_len);
4388
4389                 goto out2;
4390         }
4391
4392         /*
4393          * Okay, we need to do block allocation.
4394          */
4395         newex.ee_block = cpu_to_le32(map->m_lblk);
4396         cluster_offset = EXT4_LBLK_COFF(sbi, map->m_lblk);
4397
4398         /*
4399          * If we are doing bigalloc, check to see if the extent returned
4400          * by ext4_find_extent() implies a cluster we can use.
4401          */
4402         if (cluster_offset && ex &&
4403             get_implied_cluster_alloc(inode->i_sb, map, ex, path)) {
4404                 ar.len = allocated = map->m_len;
4405                 newblock = map->m_pblk;
4406                 map_from_cluster = true;
4407                 goto got_allocated_blocks;
4408         }
4409
4410         /* find neighbour allocated blocks */
4411         ar.lleft = map->m_lblk;
4412         err = ext4_ext_search_left(inode, path, &ar.lleft, &ar.pleft);
4413         if (err)
4414                 goto out2;
4415         ar.lright = map->m_lblk;
4416         ex2 = NULL;
4417         err = ext4_ext_search_right(inode, path, &ar.lright, &ar.pright, &ex2);
4418         if (err)
4419                 goto out2;
4420
4421         /* Check if the extent after searching to the right implies a
4422          * cluster we can use. */
4423         if ((sbi->s_cluster_ratio > 1) && ex2 &&
4424             get_implied_cluster_alloc(inode->i_sb, map, ex2, path)) {
4425                 ar.len = allocated = map->m_len;
4426                 newblock = map->m_pblk;
4427                 map_from_cluster = true;
4428                 goto got_allocated_blocks;
4429         }
4430
4431         /*
4432          * See if request is beyond maximum number of blocks we can have in
4433          * a single extent. For an initialized extent this limit is
4434          * EXT_INIT_MAX_LEN and for an unwritten extent this limit is
4435          * EXT_UNWRITTEN_MAX_LEN.
4436          */
4437         if (map->m_len > EXT_INIT_MAX_LEN &&
4438             !(flags & EXT4_GET_BLOCKS_UNWRIT_EXT))
4439                 map->m_len = EXT_INIT_MAX_LEN;
4440         else if (map->m_len > EXT_UNWRITTEN_MAX_LEN &&
4441                  (flags & EXT4_GET_BLOCKS_UNWRIT_EXT))
4442                 map->m_len = EXT_UNWRITTEN_MAX_LEN;
4443
4444         /* Check if we can really insert (m_lblk)::(m_lblk + m_len) extent */
4445         newex.ee_len = cpu_to_le16(map->m_len);
4446         err = ext4_ext_check_overlap(sbi, inode, &newex, path);
4447         if (err)
4448                 allocated = ext4_ext_get_actual_len(&newex);
4449         else
4450                 allocated = map->m_len;
4451
4452         /* allocate new block */
4453         ar.inode = inode;
4454         ar.goal = ext4_ext_find_goal(inode, path, map->m_lblk);
4455         ar.logical = map->m_lblk;
4456         /*
4457          * We calculate the offset from the beginning of the cluster
4458          * for the logical block number, since when we allocate a
4459          * physical cluster, the physical block should start at the
4460          * same offset from the beginning of the cluster.  This is
4461          * needed so that future calls to get_implied_cluster_alloc()
4462          * work correctly.
4463          */
4464         offset = EXT4_LBLK_COFF(sbi, map->m_lblk);
4465         ar.len = EXT4_NUM_B2C(sbi, offset+allocated);
4466         ar.goal -= offset;
4467         ar.logical -= offset;
4468         if (S_ISREG(inode->i_mode))
4469                 ar.flags = EXT4_MB_HINT_DATA;
4470         else
4471                 /* disable in-core preallocation for non-regular files */
4472                 ar.flags = 0;
4473         if (flags & EXT4_GET_BLOCKS_NO_NORMALIZE)
4474                 ar.flags |= EXT4_MB_HINT_NOPREALLOC;
4475         if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
4476                 ar.flags |= EXT4_MB_DELALLOC_RESERVED;
4477         if (flags & EXT4_GET_BLOCKS_METADATA_NOFAIL)
4478                 ar.flags |= EXT4_MB_USE_RESERVED;
4479         newblock = ext4_mb_new_blocks(handle, &ar, &err);
4480         if (!newblock)
4481                 goto out2;
4482         ext_debug("allocate new block: goal %llu, found %llu/%u\n",
4483                   ar.goal, newblock, allocated);
4484         free_on_err = 1;
4485         allocated_clusters = ar.len;
4486         ar.len = EXT4_C2B(sbi, ar.len) - offset;
4487         if (ar.len > allocated)
4488                 ar.len = allocated;
4489
4490 got_allocated_blocks:
4491         /* try to insert new extent into found leaf and return */
4492         ext4_ext_store_pblock(&newex, newblock + offset);
4493         newex.ee_len = cpu_to_le16(ar.len);
4494         /* Mark unwritten */
4495         if (flags & EXT4_GET_BLOCKS_UNWRIT_EXT){
4496                 ext4_ext_mark_unwritten(&newex);
4497                 map->m_flags |= EXT4_MAP_UNWRITTEN;
4498         }
4499
4500         err = 0;
4501         if ((flags & EXT4_GET_BLOCKS_KEEP_SIZE) == 0)
4502                 err = check_eofblocks_fl(handle, inode, map->m_lblk,
4503                                          path, ar.len);
4504         if (!err)
4505                 err = ext4_ext_insert_extent(handle, inode, &path,
4506                                              &newex, flags);
4507
4508         if (err && free_on_err) {
4509                 int fb_flags = flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE ?
4510                         EXT4_FREE_BLOCKS_NO_QUOT_UPDATE : 0;
4511                 /* free data blocks we just allocated */
4512                 /* not a good idea to call discard here directly,
4513                  * but otherwise we'd need to call it every free() */
4514                 ext4_discard_preallocations(inode);
4515                 ext4_free_blocks(handle, inode, NULL, newblock,
4516                                  EXT4_C2B(sbi, allocated_clusters), fb_flags);
4517                 goto out2;
4518         }
4519
4520         /* previous routine could use block we allocated */
4521         newblock = ext4_ext_pblock(&newex);
4522         allocated = ext4_ext_get_actual_len(&newex);
4523         if (allocated > map->m_len)
4524                 allocated = map->m_len;
4525         map->m_flags |= EXT4_MAP_NEW;
4526
4527         /*
4528          * Reduce the reserved cluster count to reflect successful deferred
4529          * allocation of delayed allocated clusters or direct allocation of
4530          * clusters discovered to be delayed allocated.  Once allocated, a
4531          * cluster is not included in the reserved count.
4532          */
4533         if (test_opt(inode->i_sb, DELALLOC) && !map_from_cluster) {
4534                 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) {
4535                         /*
4536                          * When allocating delayed allocated clusters, simply
4537                          * reduce the reserved cluster count and claim quota
4538                          */
4539                         ext4_da_update_reserve_space(inode, allocated_clusters,
4540                                                         1);
4541                 } else {
4542                         ext4_lblk_t lblk, len;
4543                         unsigned int n;
4544
4545                         /*
4546                          * When allocating non-delayed allocated clusters
4547                          * (from fallocate, filemap, DIO, or clusters
4548                          * allocated when delalloc has been disabled by
4549                          * ext4_nonda_switch), reduce the reserved cluster
4550                          * count by the number of allocated clusters that
4551                          * have previously been delayed allocated.  Quota
4552                          * has been claimed by ext4_mb_new_blocks() above,
4553                          * so release the quota reservations made for any
4554                          * previously delayed allocated clusters.
4555                          */
4556                         lblk = EXT4_LBLK_CMASK(sbi, map->m_lblk);
4557                         len = allocated_clusters << sbi->s_cluster_bits;
4558                         n = ext4_es_delayed_clu(inode, lblk, len);
4559                         if (n > 0)
4560                                 ext4_da_update_reserve_space(inode, (int) n, 0);
4561                 }
4562         }
4563
4564         /*
4565          * Cache the extent and update transaction to commit on fdatasync only
4566          * when it is _not_ an unwritten extent.
4567          */
4568         if ((flags & EXT4_GET_BLOCKS_UNWRIT_EXT) == 0)
4569                 ext4_update_inode_fsync_trans(handle, inode, 1);
4570         else
4571                 ext4_update_inode_fsync_trans(handle, inode, 0);
4572 out:
4573         if (allocated > map->m_len)
4574                 allocated = map->m_len;
4575         ext4_ext_show_leaf(inode, path);
4576         map->m_flags |= EXT4_MAP_MAPPED;
4577         map->m_pblk = newblock;
4578         map->m_len = allocated;
4579 out2:
4580         ext4_ext_drop_refs(path);
4581         kfree(path);
4582
4583         trace_ext4_ext_map_blocks_exit(inode, flags, map,
4584                                        err ? err : allocated);
4585         return err ? err : allocated;
4586 }
4587
4588 int ext4_ext_truncate(handle_t *handle, struct inode *inode)
4589 {
4590         struct super_block *sb = inode->i_sb;
4591         ext4_lblk_t last_block;
4592         int err = 0;
4593
4594         /*
4595          * TODO: optimization is possible here.
4596          * Probably we need not scan at all,
4597          * because page truncation is enough.
4598          */
4599
4600         /* we have to know where to truncate from in crash case */
4601         EXT4_I(inode)->i_disksize = inode->i_size;
4602         err = ext4_mark_inode_dirty(handle, inode);
4603         if (err)
4604                 return err;
4605
4606         last_block = (inode->i_size + sb->s_blocksize - 1)
4607                         >> EXT4_BLOCK_SIZE_BITS(sb);
4608 retry:
4609         err = ext4_es_remove_extent(inode, last_block,
4610                                     EXT_MAX_BLOCKS - last_block);
4611         if (err == -ENOMEM) {
4612                 cond_resched();
4613                 congestion_wait(BLK_RW_ASYNC, HZ/50);
4614                 goto retry;
4615         }
4616         if (err)
4617                 return err;
4618         return ext4_ext_remove_space(inode, last_block, EXT_MAX_BLOCKS - 1);
4619 }
4620
4621 static int ext4_alloc_file_blocks(struct file *file, ext4_lblk_t offset,
4622                                   ext4_lblk_t len, loff_t new_size,
4623                                   int flags)
4624 {
4625         struct inode *inode = file_inode(file);
4626         handle_t *handle;
4627         int ret = 0;
4628         int ret2 = 0;
4629         int retries = 0;
4630         int depth = 0;
4631         struct ext4_map_blocks map;
4632         unsigned int credits;
4633         loff_t epos;
4634
4635         BUG_ON(!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS));
4636         map.m_lblk = offset;
4637         map.m_len = len;
4638         /*
4639          * Don't normalize the request if it can fit in one extent so
4640          * that it doesn't get unnecessarily split into multiple
4641          * extents.
4642          */
4643         if (len <= EXT_UNWRITTEN_MAX_LEN)
4644                 flags |= EXT4_GET_BLOCKS_NO_NORMALIZE;
4645
4646         /*
4647          * credits to insert 1 extent into extent tree
4648          */
4649         credits = ext4_chunk_trans_blocks(inode, len);
4650         depth = ext_depth(inode);
4651
4652 retry:
4653         while (ret >= 0 && len) {
4654                 /*
4655                  * Recalculate credits when extent tree depth changes.
4656                  */
4657                 if (depth != ext_depth(inode)) {
4658                         credits = ext4_chunk_trans_blocks(inode, len);
4659                         depth = ext_depth(inode);
4660                 }
4661
4662                 handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS,
4663                                             credits);
4664                 if (IS_ERR(handle)) {
4665                         ret = PTR_ERR(handle);
4666                         break;
4667                 }
4668                 ret = ext4_map_blocks(handle, inode, &map, flags);
4669                 if (ret <= 0) {
4670                         ext4_debug("inode #%lu: block %u: len %u: "
4671                                    "ext4_ext_map_blocks returned %d",
4672                                    inode->i_ino, map.m_lblk,
4673                                    map.m_len, ret);
4674                         ext4_mark_inode_dirty(handle, inode);
4675                         ret2 = ext4_journal_stop(handle);
4676                         break;
4677                 }
4678                 map.m_lblk += ret;
4679                 map.m_len = len = len - ret;
4680                 epos = (loff_t)map.m_lblk << inode->i_blkbits;
4681                 inode->i_ctime = current_time(inode);
4682                 if (new_size) {
4683                         if (epos > new_size)
4684                                 epos = new_size;
4685                         if (ext4_update_inode_size(inode, epos) & 0x1)
4686                                 inode->i_mtime = inode->i_ctime;
4687                 } else {
4688                         if (epos > inode->i_size)
4689                                 ext4_set_inode_flag(inode,
4690                                                     EXT4_INODE_EOFBLOCKS);
4691                 }
4692                 ext4_mark_inode_dirty(handle, inode);
4693                 ext4_update_inode_fsync_trans(handle, inode, 1);
4694                 ret2 = ext4_journal_stop(handle);
4695                 if (ret2)
4696                         break;
4697         }
4698         if (ret == -ENOSPC &&
4699                         ext4_should_retry_alloc(inode->i_sb, &retries)) {
4700                 ret = 0;
4701                 goto retry;
4702         }
4703
4704         return ret > 0 ? ret2 : ret;
4705 }
4706
4707 static long ext4_zero_range(struct file *file, loff_t offset,
4708                             loff_t len, int mode)
4709 {
4710         struct inode *inode = file_inode(file);
4711         handle_t *handle = NULL;
4712         unsigned int max_blocks;
4713         loff_t new_size = 0;
4714         int ret = 0;
4715         int flags;
4716         int credits;
4717         int partial_begin, partial_end;
4718         loff_t start, end;
4719         ext4_lblk_t lblk;
4720         unsigned int blkbits = inode->i_blkbits;
4721
4722         trace_ext4_zero_range(inode, offset, len, mode);
4723
4724         if (!S_ISREG(inode->i_mode))
4725                 return -EINVAL;
4726
4727         /* Call ext4_force_commit to flush all data in case of data=journal. */
4728         if (ext4_should_journal_data(inode)) {
4729                 ret = ext4_force_commit(inode->i_sb);
4730                 if (ret)
4731                         return ret;
4732         }
4733
4734         /*
4735          * Round up offset. This is not fallocate, we neet to zero out
4736          * blocks, so convert interior block aligned part of the range to
4737          * unwritten and possibly manually zero out unaligned parts of the
4738          * range.
4739          */
4740         start = round_up(offset, 1 << blkbits);
4741         end = round_down((offset + len), 1 << blkbits);
4742
4743         if (start < offset || end > offset + len)
4744                 return -EINVAL;
4745         partial_begin = offset & ((1 << blkbits) - 1);
4746         partial_end = (offset + len) & ((1 << blkbits) - 1);
4747
4748         lblk = start >> blkbits;
4749         max_blocks = (end >> blkbits);
4750         if (max_blocks < lblk)
4751                 max_blocks = 0;
4752         else
4753                 max_blocks -= lblk;
4754
4755         inode_lock(inode);
4756
4757         /*
4758          * Indirect files do not support unwritten extnets
4759          */
4760         if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
4761                 ret = -EOPNOTSUPP;
4762                 goto out_mutex;
4763         }
4764
4765         if (!(mode & FALLOC_FL_KEEP_SIZE) &&
4766             (offset + len > i_size_read(inode) ||
4767              offset + len > EXT4_I(inode)->i_disksize)) {
4768                 new_size = offset + len;
4769                 ret = inode_newsize_ok(inode, new_size);
4770                 if (ret)
4771                         goto out_mutex;
4772         }
4773
4774         flags = EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT;
4775         if (mode & FALLOC_FL_KEEP_SIZE)
4776                 flags |= EXT4_GET_BLOCKS_KEEP_SIZE;
4777
4778         /* Wait all existing dio workers, newcomers will block on i_mutex */
4779         inode_dio_wait(inode);
4780
4781         /* Preallocate the range including the unaligned edges */
4782         if (partial_begin || partial_end) {
4783                 ret = ext4_alloc_file_blocks(file,
4784                                 round_down(offset, 1 << blkbits) >> blkbits,
4785                                 (round_up((offset + len), 1 << blkbits) -
4786                                  round_down(offset, 1 << blkbits)) >> blkbits,
4787                                 new_size, flags);
4788                 if (ret)
4789                         goto out_mutex;
4790
4791         }
4792
4793         /* Zero range excluding the unaligned edges */
4794         if (max_blocks > 0) {
4795                 flags |= (EXT4_GET_BLOCKS_CONVERT_UNWRITTEN |
4796                           EXT4_EX_NOCACHE);
4797
4798                 /*
4799                  * Prevent page faults from reinstantiating pages we have
4800                  * released from page cache.
4801                  */
4802                 down_write(&EXT4_I(inode)->i_mmap_sem);
4803
4804                 ret = ext4_break_layouts(inode);
4805                 if (ret) {
4806                         up_write(&EXT4_I(inode)->i_mmap_sem);
4807                         goto out_mutex;
4808                 }
4809
4810                 ret = ext4_update_disksize_before_punch(inode, offset, len);
4811                 if (ret) {
4812                         up_write(&EXT4_I(inode)->i_mmap_sem);
4813                         goto out_mutex;
4814                 }
4815                 /* Now release the pages and zero block aligned part of pages */
4816                 truncate_pagecache_range(inode, start, end - 1);
4817                 inode->i_mtime = inode->i_ctime = current_time(inode);
4818
4819                 ret = ext4_alloc_file_blocks(file, lblk, max_blocks, new_size,
4820                                              flags);
4821                 up_write(&EXT4_I(inode)->i_mmap_sem);
4822                 if (ret)
4823                         goto out_mutex;
4824         }
4825         if (!partial_begin && !partial_end)
4826                 goto out_mutex;
4827
4828         /*
4829          * In worst case we have to writeout two nonadjacent unwritten
4830          * blocks and update the inode
4831          */
4832         credits = (2 * ext4_ext_index_trans_blocks(inode, 2)) + 1;
4833         if (ext4_should_journal_data(inode))
4834                 credits += 2;
4835         handle = ext4_journal_start(inode, EXT4_HT_MISC, credits);
4836         if (IS_ERR(handle)) {
4837                 ret = PTR_ERR(handle);
4838                 ext4_std_error(inode->i_sb, ret);
4839                 goto out_mutex;
4840         }
4841
4842         inode->i_mtime = inode->i_ctime = current_time(inode);
4843         if (new_size) {
4844                 ext4_update_inode_size(inode, new_size);
4845         } else {
4846                 /*
4847                 * Mark that we allocate beyond EOF so the subsequent truncate
4848                 * can proceed even if the new size is the same as i_size.
4849                 */
4850                 if ((offset + len) > i_size_read(inode))
4851                         ext4_set_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
4852         }
4853         ext4_mark_inode_dirty(handle, inode);
4854
4855         /* Zero out partial block at the edges of the range */
4856         ret = ext4_zero_partial_blocks(handle, inode, offset, len);
4857         if (ret >= 0)
4858                 ext4_update_inode_fsync_trans(handle, inode, 1);
4859
4860         if (file->f_flags & O_SYNC)
4861                 ext4_handle_sync(handle);
4862
4863         ext4_journal_stop(handle);
4864 out_mutex:
4865         inode_unlock(inode);
4866         return ret;
4867 }
4868
4869 /*
4870  * preallocate space for a file. This implements ext4's fallocate file
4871  * operation, which gets called from sys_fallocate system call.
4872  * For block-mapped files, posix_fallocate should fall back to the method
4873  * of writing zeroes to the required new blocks (the same behavior which is
4874  * expected for file systems which do not support fallocate() system call).
4875  */
4876 long ext4_fallocate(struct file *file, int mode, loff_t offset, loff_t len)
4877 {
4878         struct inode *inode = file_inode(file);
4879         loff_t new_size = 0;
4880         unsigned int max_blocks;
4881         int ret = 0;
4882         int flags;
4883         ext4_lblk_t lblk;
4884         unsigned int blkbits = inode->i_blkbits;
4885
4886         /*
4887          * Encrypted inodes can't handle collapse range or insert
4888          * range since we would need to re-encrypt blocks with a
4889          * different IV or XTS tweak (which are based on the logical
4890          * block number).
4891          */
4892         if (IS_ENCRYPTED(inode) &&
4893             (mode & (FALLOC_FL_COLLAPSE_RANGE | FALLOC_FL_INSERT_RANGE)))
4894                 return -EOPNOTSUPP;
4895
4896         /* Return error if mode is not supported */
4897         if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE |
4898                      FALLOC_FL_COLLAPSE_RANGE | FALLOC_FL_ZERO_RANGE |
4899                      FALLOC_FL_INSERT_RANGE))
4900                 return -EOPNOTSUPP;
4901
4902         if (mode & FALLOC_FL_PUNCH_HOLE)
4903                 return ext4_punch_hole(inode, offset, len);
4904
4905         ret = ext4_convert_inline_data(inode);
4906         if (ret)
4907                 return ret;
4908
4909         if (mode & FALLOC_FL_COLLAPSE_RANGE)
4910                 return ext4_collapse_range(inode, offset, len);
4911
4912         if (mode & FALLOC_FL_INSERT_RANGE)
4913                 return ext4_insert_range(inode, offset, len);
4914
4915         if (mode & FALLOC_FL_ZERO_RANGE)
4916                 return ext4_zero_range(file, offset, len, mode);
4917
4918         trace_ext4_fallocate_enter(inode, offset, len, mode);
4919         lblk = offset >> blkbits;
4920
4921         max_blocks = EXT4_MAX_BLOCKS(len, offset, blkbits);
4922         flags = EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT;
4923         if (mode & FALLOC_FL_KEEP_SIZE)
4924                 flags |= EXT4_GET_BLOCKS_KEEP_SIZE;
4925
4926         inode_lock(inode);
4927
4928         /*
4929          * We only support preallocation for extent-based files only
4930          */
4931         if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
4932                 ret = -EOPNOTSUPP;
4933                 goto out;
4934         }
4935
4936         if (!(mode & FALLOC_FL_KEEP_SIZE) &&
4937             (offset + len > i_size_read(inode) ||
4938              offset + len > EXT4_I(inode)->i_disksize)) {
4939                 new_size = offset + len;
4940                 ret = inode_newsize_ok(inode, new_size);
4941                 if (ret)
4942                         goto out;
4943         }
4944
4945         /* Wait all existing dio workers, newcomers will block on i_mutex */
4946         inode_dio_wait(inode);
4947
4948         ret = ext4_alloc_file_blocks(file, lblk, max_blocks, new_size, flags);
4949         if (ret)
4950                 goto out;
4951
4952         if (file->f_flags & O_SYNC && EXT4_SB(inode->i_sb)->s_journal) {
4953                 ret = jbd2_complete_transaction(EXT4_SB(inode->i_sb)->s_journal,
4954                                                 EXT4_I(inode)->i_sync_tid);
4955         }
4956 out:
4957         inode_unlock(inode);
4958         trace_ext4_fallocate_exit(inode, offset, max_blocks, ret);
4959         return ret;
4960 }
4961
4962 /*
4963  * This function convert a range of blocks to written extents
4964  * The caller of this function will pass the start offset and the size.
4965  * all unwritten extents within this range will be converted to
4966  * written extents.
4967  *
4968  * This function is called from the direct IO end io call back
4969  * function, to convert the fallocated extents after IO is completed.
4970  * Returns 0 on success.
4971  */
4972 int ext4_convert_unwritten_extents(handle_t *handle, struct inode *inode,
4973                                    loff_t offset, ssize_t len)
4974 {
4975         unsigned int max_blocks;
4976         int ret = 0;
4977         int ret2 = 0;
4978         struct ext4_map_blocks map;
4979         unsigned int blkbits = inode->i_blkbits;
4980         unsigned int credits = 0;
4981
4982         map.m_lblk = offset >> blkbits;
4983         max_blocks = EXT4_MAX_BLOCKS(len, offset, blkbits);
4984
4985         if (!handle) {
4986                 /*
4987                  * credits to insert 1 extent into extent tree
4988                  */
4989                 credits = ext4_chunk_trans_blocks(inode, max_blocks);
4990         }
4991         while (ret >= 0 && ret < max_blocks) {
4992                 map.m_lblk += ret;
4993                 map.m_len = (max_blocks -= ret);
4994                 if (credits) {
4995                         handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS,
4996                                                     credits);
4997                         if (IS_ERR(handle)) {
4998                                 ret = PTR_ERR(handle);
4999                                 break;
5000                         }
5001                 }
5002                 ret = ext4_map_blocks(handle, inode, &map,
5003                                       EXT4_GET_BLOCKS_IO_CONVERT_EXT);
5004                 if (ret <= 0)
5005                         ext4_warning(inode->i_sb,
5006                                      "inode #%lu: block %u: len %u: "
5007                                      "ext4_ext_map_blocks returned %d",
5008                                      inode->i_ino, map.m_lblk,
5009                                      map.m_len, ret);
5010                 ext4_mark_inode_dirty(handle, inode);
5011                 if (credits)
5012                         ret2 = ext4_journal_stop(handle);
5013                 if (ret <= 0 || ret2)
5014                         break;
5015         }
5016         return ret > 0 ? ret2 : ret;
5017 }
5018
5019 int ext4_convert_unwritten_io_end_vec(handle_t *handle, ext4_io_end_t *io_end)
5020 {
5021         int ret, err = 0;
5022         struct ext4_io_end_vec *io_end_vec;
5023
5024         /*
5025          * This is somewhat ugly but the idea is clear: When transaction is
5026          * reserved, everything goes into it. Otherwise we rather start several
5027          * smaller transactions for conversion of each extent separately.
5028          */
5029         if (handle) {
5030                 handle = ext4_journal_start_reserved(handle,
5031                                                      EXT4_HT_EXT_CONVERT);
5032                 if (IS_ERR(handle))
5033                         return PTR_ERR(handle);
5034         }
5035
5036         list_for_each_entry(io_end_vec, &io_end->list_vec, list) {
5037                 ret = ext4_convert_unwritten_extents(handle, io_end->inode,
5038                                                      io_end_vec->offset,
5039                                                      io_end_vec->size);
5040                 if (ret)
5041                         break;
5042         }
5043
5044         if (handle)
5045                 err = ext4_journal_stop(handle);
5046
5047         return ret < 0 ? ret : err;
5048 }
5049
5050 /*
5051  * If newes is not existing extent (newes->ec_pblk equals zero) find
5052  * delayed extent at start of newes and update newes accordingly and
5053  * return start of the next delayed extent.
5054  *
5055  * If newes is existing extent (newes->ec_pblk is not equal zero)
5056  * return start of next delayed extent or EXT_MAX_BLOCKS if no delayed
5057  * extent found. Leave newes unmodified.
5058  */
5059 static int ext4_find_delayed_extent(struct inode *inode,
5060                                     struct extent_status *newes)
5061 {
5062         struct extent_status es;
5063         ext4_lblk_t block, next_del;
5064
5065         if (newes->es_pblk == 0) {
5066                 ext4_es_find_extent_range(inode, &ext4_es_is_delayed,
5067                                           newes->es_lblk,
5068                                           newes->es_lblk + newes->es_len - 1,
5069                                           &es);
5070
5071                 /*
5072                  * No extent in extent-tree contains block @newes->es_pblk,
5073                  * then the block may stay in 1)a hole or 2)delayed-extent.
5074                  */
5075                 if (es.es_len == 0)
5076                         /* A hole found. */
5077                         return 0;
5078
5079                 if (es.es_lblk > newes->es_lblk) {
5080                         /* A hole found. */
5081                         newes->es_len = min(es.es_lblk - newes->es_lblk,
5082                                             newes->es_len);
5083                         return 0;
5084                 }
5085
5086                 newes->es_len = es.es_lblk + es.es_len - newes->es_lblk;
5087         }
5088
5089         block = newes->es_lblk + newes->es_len;
5090         ext4_es_find_extent_range(inode, &ext4_es_is_delayed, block,
5091                                   EXT_MAX_BLOCKS, &es);
5092         if (es.es_len == 0)
5093                 next_del = EXT_MAX_BLOCKS;
5094         else
5095                 next_del = es.es_lblk;
5096
5097         return next_del;
5098 }
5099
5100 static int ext4_xattr_fiemap(struct inode *inode,
5101                                 struct fiemap_extent_info *fieinfo)
5102 {
5103         __u64 physical = 0;
5104         __u64 length;
5105         __u32 flags = FIEMAP_EXTENT_LAST;
5106         int blockbits = inode->i_sb->s_blocksize_bits;
5107         int error = 0;
5108
5109         /* in-inode? */
5110         if (ext4_test_inode_state(inode, EXT4_STATE_XATTR)) {
5111                 struct ext4_iloc iloc;
5112                 int offset;     /* offset of xattr in inode */
5113
5114                 error = ext4_get_inode_loc(inode, &iloc);
5115                 if (error)
5116                         return error;
5117                 physical = (__u64)iloc.bh->b_blocknr << blockbits;
5118                 offset = EXT4_GOOD_OLD_INODE_SIZE +
5119                                 EXT4_I(inode)->i_extra_isize;
5120                 physical += offset;
5121                 length = EXT4_SB(inode->i_sb)->s_inode_size - offset;
5122                 flags |= FIEMAP_EXTENT_DATA_INLINE;
5123                 brelse(iloc.bh);
5124         } else { /* external block */
5125                 physical = (__u64)EXT4_I(inode)->i_file_acl << blockbits;
5126                 length = inode->i_sb->s_blocksize;
5127         }
5128
5129         if (physical)
5130                 error = fiemap_fill_next_extent(fieinfo, 0, physical,
5131                                                 length, flags);
5132         return (error < 0 ? error : 0);
5133 }
5134
5135 static int _ext4_fiemap(struct inode *inode,
5136                         struct fiemap_extent_info *fieinfo,
5137                         __u64 start, __u64 len,
5138                         int (*fill)(struct inode *, ext4_lblk_t,
5139                                     ext4_lblk_t,
5140                                     struct fiemap_extent_info *))
5141 {
5142         ext4_lblk_t start_blk;
5143         u32 ext4_fiemap_flags = FIEMAP_FLAG_SYNC|FIEMAP_FLAG_XATTR;
5144
5145         int error = 0;
5146
5147         if (ext4_has_inline_data(inode)) {
5148                 int has_inline = 1;
5149
5150                 error = ext4_inline_data_fiemap(inode, fieinfo, &has_inline,
5151                                                 start, len);
5152
5153                 if (has_inline)
5154                         return error;
5155         }
5156
5157         if (fieinfo->fi_flags & FIEMAP_FLAG_CACHE) {
5158                 error = ext4_ext_precache(inode);
5159                 if (error)
5160                         return error;
5161                 fieinfo->fi_flags &= ~FIEMAP_FLAG_CACHE;
5162         }
5163
5164         /* fallback to generic here if not in extents fmt */
5165         if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) &&
5166             fill == ext4_fill_fiemap_extents)
5167                 return generic_block_fiemap(inode, fieinfo, start, len,
5168                         ext4_get_block);
5169
5170         if (fill == ext4_fill_es_cache_info)
5171                 ext4_fiemap_flags &= FIEMAP_FLAG_XATTR;
5172         if (fiemap_check_flags(fieinfo, ext4_fiemap_flags))
5173                 return -EBADR;
5174
5175         if (fieinfo->fi_flags & FIEMAP_FLAG_XATTR) {
5176                 error = ext4_xattr_fiemap(inode, fieinfo);
5177         } else {
5178                 ext4_lblk_t len_blks;
5179                 __u64 last_blk;
5180
5181                 start_blk = start >> inode->i_sb->s_blocksize_bits;
5182                 last_blk = (start + len - 1) >> inode->i_sb->s_blocksize_bits;
5183                 if (last_blk >= EXT_MAX_BLOCKS)
5184                         last_blk = EXT_MAX_BLOCKS-1;
5185                 len_blks = ((ext4_lblk_t) last_blk) - start_blk + 1;
5186
5187                 /*
5188                  * Walk the extent tree gathering extent information
5189                  * and pushing extents back to the user.
5190                  */
5191                 error = fill(inode, start_blk, len_blks, fieinfo);
5192         }
5193         return error;
5194 }
5195
5196 int ext4_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
5197                 __u64 start, __u64 len)
5198 {
5199         return _ext4_fiemap(inode, fieinfo, start, len,
5200                             ext4_fill_fiemap_extents);
5201 }
5202
5203 int ext4_get_es_cache(struct inode *inode, struct fiemap_extent_info *fieinfo,
5204                       __u64 start, __u64 len)
5205 {
5206         if (ext4_has_inline_data(inode)) {
5207                 int has_inline;
5208
5209                 down_read(&EXT4_I(inode)->xattr_sem);
5210                 has_inline = ext4_has_inline_data(inode);
5211                 up_read(&EXT4_I(inode)->xattr_sem);
5212                 if (has_inline)
5213                         return 0;
5214         }
5215
5216         return _ext4_fiemap(inode, fieinfo, start, len,
5217                             ext4_fill_es_cache_info);
5218 }
5219
5220
5221 /*
5222  * ext4_access_path:
5223  * Function to access the path buffer for marking it dirty.
5224  * It also checks if there are sufficient credits left in the journal handle
5225  * to update path.
5226  */
5227 static int
5228 ext4_access_path(handle_t *handle, struct inode *inode,
5229                 struct ext4_ext_path *path)
5230 {
5231         int credits, err;
5232
5233         if (!ext4_handle_valid(handle))
5234                 return 0;
5235
5236         /*
5237          * Check if need to extend journal credits
5238          * 3 for leaf, sb, and inode plus 2 (bmap and group
5239          * descriptor) for each block group; assume two block
5240          * groups
5241          */
5242         credits = ext4_writepage_trans_blocks(inode);
5243         err = ext4_datasem_ensure_credits(handle, inode, 7, credits, 0);
5244         if (err < 0)
5245                 return err;
5246
5247         err = ext4_ext_get_access(handle, inode, path);
5248         return err;
5249 }
5250
5251 /*
5252  * ext4_ext_shift_path_extents:
5253  * Shift the extents of a path structure lying between path[depth].p_ext
5254  * and EXT_LAST_EXTENT(path[depth].p_hdr), by @shift blocks. @SHIFT tells
5255  * if it is right shift or left shift operation.
5256  */
5257 static int
5258 ext4_ext_shift_path_extents(struct ext4_ext_path *path, ext4_lblk_t shift,
5259                             struct inode *inode, handle_t *handle,
5260                             enum SHIFT_DIRECTION SHIFT)
5261 {
5262         int depth, err = 0;
5263         struct ext4_extent *ex_start, *ex_last;
5264         bool update = false;
5265         depth = path->p_depth;
5266
5267         while (depth >= 0) {
5268                 if (depth == path->p_depth) {
5269                         ex_start = path[depth].p_ext;
5270                         if (!ex_start)
5271                                 return -EFSCORRUPTED;
5272
5273                         ex_last = EXT_LAST_EXTENT(path[depth].p_hdr);
5274
5275                         err = ext4_access_path(handle, inode, path + depth);
5276                         if (err)
5277                                 goto out;
5278
5279                         if (ex_start == EXT_FIRST_EXTENT(path[depth].p_hdr))
5280                                 update = true;
5281
5282                         while (ex_start <= ex_last) {
5283                                 if (SHIFT == SHIFT_LEFT) {
5284                                         le32_add_cpu(&ex_start->ee_block,
5285                                                 -shift);
5286                                         /* Try to merge to the left. */
5287                                         if ((ex_start >
5288                                             EXT_FIRST_EXTENT(path[depth].p_hdr))
5289                                             &&
5290                                             ext4_ext_try_to_merge_right(inode,
5291                                             path, ex_start - 1))
5292                                                 ex_last--;
5293                                         else
5294                                                 ex_start++;
5295                                 } else {
5296                                         le32_add_cpu(&ex_last->ee_block, shift);
5297                                         ext4_ext_try_to_merge_right(inode, path,
5298                                                 ex_last);
5299                                         ex_last--;
5300                                 }
5301                         }
5302                         err = ext4_ext_dirty(handle, inode, path + depth);
5303                         if (err)
5304                                 goto out;
5305
5306                         if (--depth < 0 || !update)
5307                                 break;
5308                 }
5309
5310                 /* Update index too */
5311                 err = ext4_access_path(handle, inode, path + depth);
5312                 if (err)
5313                         goto out;
5314
5315                 if (SHIFT == SHIFT_LEFT)
5316                         le32_add_cpu(&path[depth].p_idx->ei_block, -shift);
5317                 else
5318                         le32_add_cpu(&path[depth].p_idx->ei_block, shift);
5319                 err = ext4_ext_dirty(handle, inode, path + depth);
5320                 if (err)
5321                         goto out;
5322
5323                 /* we are done if current index is not a starting index */
5324                 if (path[depth].p_idx != EXT_FIRST_INDEX(path[depth].p_hdr))
5325                         break;
5326
5327                 depth--;
5328         }
5329
5330 out:
5331         return err;
5332 }
5333
5334 /*
5335  * ext4_ext_shift_extents:
5336  * All the extents which lies in the range from @start to the last allocated
5337  * block for the @inode are shifted either towards left or right (depending
5338  * upon @SHIFT) by @shift blocks.
5339  * On success, 0 is returned, error otherwise.
5340  */
5341 static int
5342 ext4_ext_shift_extents(struct inode *inode, handle_t *handle,
5343                        ext4_lblk_t start, ext4_lblk_t shift,
5344                        enum SHIFT_DIRECTION SHIFT)
5345 {
5346         struct ext4_ext_path *path;
5347         int ret = 0, depth;
5348         struct ext4_extent *extent;
5349         ext4_lblk_t stop, *iterator, ex_start, ex_end;
5350
5351         /* Let path point to the last extent */
5352         path = ext4_find_extent(inode, EXT_MAX_BLOCKS - 1, NULL,
5353                                 EXT4_EX_NOCACHE);
5354         if (IS_ERR(path))
5355                 return PTR_ERR(path);
5356
5357         depth = path->p_depth;
5358         extent = path[depth].p_ext;
5359         if (!extent)
5360                 goto out;
5361
5362         stop = le32_to_cpu(extent->ee_block);
5363
5364        /*
5365         * For left shifts, make sure the hole on the left is big enough to
5366         * accommodate the shift.  For right shifts, make sure the last extent
5367         * won't be shifted beyond EXT_MAX_BLOCKS.
5368         */
5369         if (SHIFT == SHIFT_LEFT) {
5370                 path = ext4_find_extent(inode, start - 1, &path,
5371                                         EXT4_EX_NOCACHE);
5372                 if (IS_ERR(path))
5373                         return PTR_ERR(path);
5374                 depth = path->p_depth;
5375                 extent =  path[depth].p_ext;
5376                 if (extent) {
5377                         ex_start = le32_to_cpu(extent->ee_block);
5378                         ex_end = le32_to_cpu(extent->ee_block) +
5379                                 ext4_ext_get_actual_len(extent);
5380                 } else {
5381                         ex_start = 0;
5382                         ex_end = 0;
5383                 }
5384
5385                 if ((start == ex_start && shift > ex_start) ||
5386                     (shift > start - ex_end)) {
5387                         ret = -EINVAL;
5388                         goto out;
5389                 }
5390         } else {
5391                 if (shift > EXT_MAX_BLOCKS -
5392                     (stop + ext4_ext_get_actual_len(extent))) {
5393                         ret = -EINVAL;
5394                         goto out;
5395                 }
5396         }
5397
5398         /*
5399          * In case of left shift, iterator points to start and it is increased
5400          * till we reach stop. In case of right shift, iterator points to stop
5401          * and it is decreased till we reach start.
5402          */
5403         if (SHIFT == SHIFT_LEFT)
5404                 iterator = &start;
5405         else
5406                 iterator = &stop;
5407
5408         /*
5409          * Its safe to start updating extents.  Start and stop are unsigned, so
5410          * in case of right shift if extent with 0 block is reached, iterator
5411          * becomes NULL to indicate the end of the loop.
5412          */
5413         while (iterator && start <= stop) {
5414                 path = ext4_find_extent(inode, *iterator, &path,
5415                                         EXT4_EX_NOCACHE);
5416                 if (IS_ERR(path))
5417                         return PTR_ERR(path);
5418                 depth = path->p_depth;
5419                 extent = path[depth].p_ext;
5420                 if (!extent) {
5421                         EXT4_ERROR_INODE(inode, "unexpected hole at %lu",
5422                                          (unsigned long) *iterator);
5423                         return -EFSCORRUPTED;
5424                 }
5425                 if (SHIFT == SHIFT_LEFT && *iterator >
5426                     le32_to_cpu(extent->ee_block)) {
5427                         /* Hole, move to the next extent */
5428                         if (extent < EXT_LAST_EXTENT(path[depth].p_hdr)) {
5429                                 path[depth].p_ext++;
5430                         } else {
5431                                 *iterator = ext4_ext_next_allocated_block(path);
5432                                 continue;
5433                         }
5434                 }
5435
5436                 if (SHIFT == SHIFT_LEFT) {
5437                         extent = EXT_LAST_EXTENT(path[depth].p_hdr);
5438                         *iterator = le32_to_cpu(extent->ee_block) +
5439                                         ext4_ext_get_actual_len(extent);
5440                 } else {
5441                         extent = EXT_FIRST_EXTENT(path[depth].p_hdr);
5442                         if (le32_to_cpu(extent->ee_block) > 0)
5443                                 *iterator = le32_to_cpu(extent->ee_block) - 1;
5444                         else
5445                                 /* Beginning is reached, end of the loop */
5446                                 iterator = NULL;
5447                         /* Update path extent in case we need to stop */
5448                         while (le32_to_cpu(extent->ee_block) < start)
5449                                 extent++;
5450                         path[depth].p_ext = extent;
5451                 }
5452                 ret = ext4_ext_shift_path_extents(path, shift, inode,
5453                                 handle, SHIFT);
5454                 if (ret)
5455                         break;
5456         }
5457 out:
5458         ext4_ext_drop_refs(path);
5459         kfree(path);
5460         return ret;
5461 }
5462
5463 /*
5464  * ext4_collapse_range:
5465  * This implements the fallocate's collapse range functionality for ext4
5466  * Returns: 0 and non-zero on error.
5467  */
5468 int ext4_collapse_range(struct inode *inode, loff_t offset, loff_t len)
5469 {
5470         struct super_block *sb = inode->i_sb;
5471         ext4_lblk_t punch_start, punch_stop;
5472         handle_t *handle;
5473         unsigned int credits;
5474         loff_t new_size, ioffset;
5475         int ret;
5476
5477         /*
5478          * We need to test this early because xfstests assumes that a
5479          * collapse range of (0, 1) will return EOPNOTSUPP if the file
5480          * system does not support collapse range.
5481          */
5482         if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
5483                 return -EOPNOTSUPP;
5484
5485         /* Collapse range works only on fs block size aligned offsets. */
5486         if (offset & (EXT4_CLUSTER_SIZE(sb) - 1) ||
5487             len & (EXT4_CLUSTER_SIZE(sb) - 1))
5488                 return -EINVAL;
5489
5490         if (!S_ISREG(inode->i_mode))
5491                 return -EINVAL;
5492
5493         trace_ext4_collapse_range(inode, offset, len);
5494
5495         punch_start = offset >> EXT4_BLOCK_SIZE_BITS(sb);
5496         punch_stop = (offset + len) >> EXT4_BLOCK_SIZE_BITS(sb);
5497
5498         /* Call ext4_force_commit to flush all data in case of data=journal. */
5499         if (ext4_should_journal_data(inode)) {
5500                 ret = ext4_force_commit(inode->i_sb);
5501                 if (ret)
5502                         return ret;
5503         }
5504
5505         inode_lock(inode);
5506         /*
5507          * There is no need to overlap collapse range with EOF, in which case
5508          * it is effectively a truncate operation
5509          */
5510         if (offset + len >= i_size_read(inode)) {
5511                 ret = -EINVAL;
5512                 goto out_mutex;
5513         }
5514
5515         /* Currently just for extent based files */
5516         if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
5517                 ret = -EOPNOTSUPP;
5518                 goto out_mutex;
5519         }
5520
5521         /* Wait for existing dio to complete */
5522         inode_dio_wait(inode);
5523
5524         /*
5525          * Prevent page faults from reinstantiating pages we have released from
5526          * page cache.
5527          */
5528         down_write(&EXT4_I(inode)->i_mmap_sem);
5529
5530         ret = ext4_break_layouts(inode);
5531         if (ret)
5532                 goto out_mmap;
5533
5534         /*
5535          * Need to round down offset to be aligned with page size boundary
5536          * for page size > block size.
5537          */
5538         ioffset = round_down(offset, PAGE_SIZE);
5539         /*
5540          * Write tail of the last page before removed range since it will get
5541          * removed from the page cache below.
5542          */
5543         ret = filemap_write_and_wait_range(inode->i_mapping, ioffset, offset);
5544         if (ret)
5545                 goto out_mmap;
5546         /*
5547          * Write data that will be shifted to preserve them when discarding
5548          * page cache below. We are also protected from pages becoming dirty
5549          * by i_mmap_sem.
5550          */
5551         ret = filemap_write_and_wait_range(inode->i_mapping, offset + len,
5552                                            LLONG_MAX);
5553         if (ret)
5554                 goto out_mmap;
5555         truncate_pagecache(inode, ioffset);
5556
5557         credits = ext4_writepage_trans_blocks(inode);
5558         handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
5559         if (IS_ERR(handle)) {
5560                 ret = PTR_ERR(handle);
5561                 goto out_mmap;
5562         }
5563
5564         down_write(&EXT4_I(inode)->i_data_sem);
5565         ext4_discard_preallocations(inode);
5566
5567         ret = ext4_es_remove_extent(inode, punch_start,
5568                                     EXT_MAX_BLOCKS - punch_start);
5569         if (ret) {
5570                 up_write(&EXT4_I(inode)->i_data_sem);
5571                 goto out_stop;
5572         }
5573
5574         ret = ext4_ext_remove_space(inode, punch_start, punch_stop - 1);
5575         if (ret) {
5576                 up_write(&EXT4_I(inode)->i_data_sem);
5577                 goto out_stop;
5578         }
5579         ext4_discard_preallocations(inode);
5580
5581         ret = ext4_ext_shift_extents(inode, handle, punch_stop,
5582                                      punch_stop - punch_start, SHIFT_LEFT);
5583         if (ret) {
5584                 up_write(&EXT4_I(inode)->i_data_sem);
5585                 goto out_stop;
5586         }
5587
5588         new_size = i_size_read(inode) - len;
5589         i_size_write(inode, new_size);
5590         EXT4_I(inode)->i_disksize = new_size;
5591
5592         up_write(&EXT4_I(inode)->i_data_sem);
5593         if (IS_SYNC(inode))
5594                 ext4_handle_sync(handle);
5595         inode->i_mtime = inode->i_ctime = current_time(inode);
5596         ext4_mark_inode_dirty(handle, inode);
5597         ext4_update_inode_fsync_trans(handle, inode, 1);
5598
5599 out_stop:
5600         ext4_journal_stop(handle);
5601 out_mmap:
5602         up_write(&EXT4_I(inode)->i_mmap_sem);
5603 out_mutex:
5604         inode_unlock(inode);
5605         return ret;
5606 }
5607
5608 /*
5609  * ext4_insert_range:
5610  * This function implements the FALLOC_FL_INSERT_RANGE flag of fallocate.
5611  * The data blocks starting from @offset to the EOF are shifted by @len
5612  * towards right to create a hole in the @inode. Inode size is increased
5613  * by len bytes.
5614  * Returns 0 on success, error otherwise.
5615  */
5616 int ext4_insert_range(struct inode *inode, loff_t offset, loff_t len)
5617 {
5618         struct super_block *sb = inode->i_sb;
5619         handle_t *handle;
5620         struct ext4_ext_path *path;
5621         struct ext4_extent *extent;
5622         ext4_lblk_t offset_lblk, len_lblk, ee_start_lblk = 0;
5623         unsigned int credits, ee_len;
5624         int ret = 0, depth, split_flag = 0;
5625         loff_t ioffset;
5626
5627         /*
5628          * We need to test this early because xfstests assumes that an
5629          * insert range of (0, 1) will return EOPNOTSUPP if the file
5630          * system does not support insert range.
5631          */
5632         if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
5633                 return -EOPNOTSUPP;
5634
5635         /* Insert range works only on fs block size aligned offsets. */
5636         if (offset & (EXT4_CLUSTER_SIZE(sb) - 1) ||
5637                         len & (EXT4_CLUSTER_SIZE(sb) - 1))
5638                 return -EINVAL;
5639
5640         if (!S_ISREG(inode->i_mode))
5641                 return -EOPNOTSUPP;
5642
5643         trace_ext4_insert_range(inode, offset, len);
5644
5645         offset_lblk = offset >> EXT4_BLOCK_SIZE_BITS(sb);
5646         len_lblk = len >> EXT4_BLOCK_SIZE_BITS(sb);
5647
5648         /* Call ext4_force_commit to flush all data in case of data=journal */
5649         if (ext4_should_journal_data(inode)) {
5650                 ret = ext4_force_commit(inode->i_sb);
5651                 if (ret)
5652                         return ret;
5653         }
5654
5655         inode_lock(inode);
5656         /* Currently just for extent based files */
5657         if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
5658                 ret = -EOPNOTSUPP;
5659                 goto out_mutex;
5660         }
5661
5662         /* Check for wrap through zero */
5663         if (inode->i_size + len > inode->i_sb->s_maxbytes) {
5664                 ret = -EFBIG;
5665                 goto out_mutex;
5666         }
5667
5668         /* Offset should be less than i_size */
5669         if (offset >= i_size_read(inode)) {
5670                 ret = -EINVAL;
5671                 goto out_mutex;
5672         }
5673
5674         /* Wait for existing dio to complete */
5675         inode_dio_wait(inode);
5676
5677         /*
5678          * Prevent page faults from reinstantiating pages we have released from
5679          * page cache.
5680          */
5681         down_write(&EXT4_I(inode)->i_mmap_sem);
5682
5683         ret = ext4_break_layouts(inode);
5684         if (ret)
5685                 goto out_mmap;
5686
5687         /*
5688          * Need to round down to align start offset to page size boundary
5689          * for page size > block size.
5690          */
5691         ioffset = round_down(offset, PAGE_SIZE);
5692         /* Write out all dirty pages */
5693         ret = filemap_write_and_wait_range(inode->i_mapping, ioffset,
5694                         LLONG_MAX);
5695         if (ret)
5696                 goto out_mmap;
5697         truncate_pagecache(inode, ioffset);
5698
5699         credits = ext4_writepage_trans_blocks(inode);
5700         handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
5701         if (IS_ERR(handle)) {
5702                 ret = PTR_ERR(handle);
5703                 goto out_mmap;
5704         }
5705
5706         /* Expand file to avoid data loss if there is error while shifting */
5707         inode->i_size += len;
5708         EXT4_I(inode)->i_disksize += len;
5709         inode->i_mtime = inode->i_ctime = current_time(inode);
5710         ret = ext4_mark_inode_dirty(handle, inode);
5711         if (ret)
5712                 goto out_stop;
5713
5714         down_write(&EXT4_I(inode)->i_data_sem);
5715         ext4_discard_preallocations(inode);
5716
5717         path = ext4_find_extent(inode, offset_lblk, NULL, 0);
5718         if (IS_ERR(path)) {
5719                 up_write(&EXT4_I(inode)->i_data_sem);
5720                 goto out_stop;
5721         }
5722
5723         depth = ext_depth(inode);
5724         extent = path[depth].p_ext;
5725         if (extent) {
5726                 ee_start_lblk = le32_to_cpu(extent->ee_block);
5727                 ee_len = ext4_ext_get_actual_len(extent);
5728
5729                 /*
5730                  * If offset_lblk is not the starting block of extent, split
5731                  * the extent @offset_lblk
5732                  */
5733                 if ((offset_lblk > ee_start_lblk) &&
5734                                 (offset_lblk < (ee_start_lblk + ee_len))) {
5735                         if (ext4_ext_is_unwritten(extent))
5736                                 split_flag = EXT4_EXT_MARK_UNWRIT1 |
5737                                         EXT4_EXT_MARK_UNWRIT2;
5738                         ret = ext4_split_extent_at(handle, inode, &path,
5739                                         offset_lblk, split_flag,
5740                                         EXT4_EX_NOCACHE |
5741                                         EXT4_GET_BLOCKS_PRE_IO |
5742                                         EXT4_GET_BLOCKS_METADATA_NOFAIL);
5743                 }
5744
5745                 ext4_ext_drop_refs(path);
5746                 kfree(path);
5747                 if (ret < 0) {
5748                         up_write(&EXT4_I(inode)->i_data_sem);
5749                         goto out_stop;
5750                 }
5751         } else {
5752                 ext4_ext_drop_refs(path);
5753                 kfree(path);
5754         }
5755
5756         ret = ext4_es_remove_extent(inode, offset_lblk,
5757                         EXT_MAX_BLOCKS - offset_lblk);
5758         if (ret) {
5759                 up_write(&EXT4_I(inode)->i_data_sem);
5760                 goto out_stop;
5761         }
5762
5763         /*
5764          * if offset_lblk lies in a hole which is at start of file, use
5765          * ee_start_lblk to shift extents
5766          */
5767         ret = ext4_ext_shift_extents(inode, handle,
5768                 ee_start_lblk > offset_lblk ? ee_start_lblk : offset_lblk,
5769                 len_lblk, SHIFT_RIGHT);
5770
5771         up_write(&EXT4_I(inode)->i_data_sem);
5772         if (IS_SYNC(inode))
5773                 ext4_handle_sync(handle);
5774         if (ret >= 0)
5775                 ext4_update_inode_fsync_trans(handle, inode, 1);
5776
5777 out_stop:
5778         ext4_journal_stop(handle);
5779 out_mmap:
5780         up_write(&EXT4_I(inode)->i_mmap_sem);
5781 out_mutex:
5782         inode_unlock(inode);
5783         return ret;
5784 }
5785
5786 /**
5787  * ext4_swap_extents() - Swap extents between two inodes
5788  * @handle: handle for this transaction
5789  * @inode1:     First inode
5790  * @inode2:     Second inode
5791  * @lblk1:      Start block for first inode
5792  * @lblk2:      Start block for second inode
5793  * @count:      Number of blocks to swap
5794  * @unwritten: Mark second inode's extents as unwritten after swap
5795  * @erp:        Pointer to save error value
5796  *
5797  * This helper routine does exactly what is promise "swap extents". All other
5798  * stuff such as page-cache locking consistency, bh mapping consistency or
5799  * extent's data copying must be performed by caller.
5800  * Locking:
5801  *              i_mutex is held for both inodes
5802  *              i_data_sem is locked for write for both inodes
5803  * Assumptions:
5804  *              All pages from requested range are locked for both inodes
5805  */
5806 int
5807 ext4_swap_extents(handle_t *handle, struct inode *inode1,
5808                   struct inode *inode2, ext4_lblk_t lblk1, ext4_lblk_t lblk2,
5809                   ext4_lblk_t count, int unwritten, int *erp)
5810 {
5811         struct ext4_ext_path *path1 = NULL;
5812         struct ext4_ext_path *path2 = NULL;
5813         int replaced_count = 0;
5814
5815         BUG_ON(!rwsem_is_locked(&EXT4_I(inode1)->i_data_sem));
5816         BUG_ON(!rwsem_is_locked(&EXT4_I(inode2)->i_data_sem));
5817         BUG_ON(!inode_is_locked(inode1));
5818         BUG_ON(!inode_is_locked(inode2));
5819
5820         *erp = ext4_es_remove_extent(inode1, lblk1, count);
5821         if (unlikely(*erp))
5822                 return 0;
5823         *erp = ext4_es_remove_extent(inode2, lblk2, count);
5824         if (unlikely(*erp))
5825                 return 0;
5826
5827         while (count) {
5828                 struct ext4_extent *ex1, *ex2, tmp_ex;
5829                 ext4_lblk_t e1_blk, e2_blk;
5830                 int e1_len, e2_len, len;
5831                 int split = 0;
5832
5833                 path1 = ext4_find_extent(inode1, lblk1, NULL, EXT4_EX_NOCACHE);
5834                 if (IS_ERR(path1)) {
5835                         *erp = PTR_ERR(path1);
5836                         path1 = NULL;
5837                 finish:
5838                         count = 0;
5839                         goto repeat;
5840                 }
5841                 path2 = ext4_find_extent(inode2, lblk2, NULL, EXT4_EX_NOCACHE);
5842                 if (IS_ERR(path2)) {
5843                         *erp = PTR_ERR(path2);
5844                         path2 = NULL;
5845                         goto finish;
5846                 }
5847                 ex1 = path1[path1->p_depth].p_ext;
5848                 ex2 = path2[path2->p_depth].p_ext;
5849                 /* Do we have somthing to swap ? */
5850                 if (unlikely(!ex2 || !ex1))
5851                         goto finish;
5852
5853                 e1_blk = le32_to_cpu(ex1->ee_block);
5854                 e2_blk = le32_to_cpu(ex2->ee_block);
5855                 e1_len = ext4_ext_get_actual_len(ex1);
5856                 e2_len = ext4_ext_get_actual_len(ex2);
5857
5858                 /* Hole handling */
5859                 if (!in_range(lblk1, e1_blk, e1_len) ||
5860                     !in_range(lblk2, e2_blk, e2_len)) {
5861                         ext4_lblk_t next1, next2;
5862
5863                         /* if hole after extent, then go to next extent */
5864                         next1 = ext4_ext_next_allocated_block(path1);
5865                         next2 = ext4_ext_next_allocated_block(path2);
5866                         /* If hole before extent, then shift to that extent */
5867                         if (e1_blk > lblk1)
5868                                 next1 = e1_blk;
5869                         if (e2_blk > lblk2)
5870                                 next2 = e2_blk;
5871                         /* Do we have something to swap */
5872                         if (next1 == EXT_MAX_BLOCKS || next2 == EXT_MAX_BLOCKS)
5873                                 goto finish;
5874                         /* Move to the rightest boundary */
5875                         len = next1 - lblk1;
5876                         if (len < next2 - lblk2)
5877                                 len = next2 - lblk2;
5878                         if (len > count)
5879                                 len = count;
5880                         lblk1 += len;
5881                         lblk2 += len;
5882                         count -= len;
5883                         goto repeat;
5884                 }
5885
5886                 /* Prepare left boundary */
5887                 if (e1_blk < lblk1) {
5888                         split = 1;
5889                         *erp = ext4_force_split_extent_at(handle, inode1,
5890                                                 &path1, lblk1, 0);
5891                         if (unlikely(*erp))
5892                                 goto finish;
5893                 }
5894                 if (e2_blk < lblk2) {
5895                         split = 1;
5896                         *erp = ext4_force_split_extent_at(handle, inode2,
5897                                                 &path2,  lblk2, 0);
5898                         if (unlikely(*erp))
5899                                 goto finish;
5900                 }
5901                 /* ext4_split_extent_at() may result in leaf extent split,
5902                  * path must to be revalidated. */
5903                 if (split)
5904                         goto repeat;
5905
5906                 /* Prepare right boundary */
5907                 len = count;
5908                 if (len > e1_blk + e1_len - lblk1)
5909                         len = e1_blk + e1_len - lblk1;
5910                 if (len > e2_blk + e2_len - lblk2)
5911                         len = e2_blk + e2_len - lblk2;
5912
5913                 if (len != e1_len) {
5914                         split = 1;
5915                         *erp = ext4_force_split_extent_at(handle, inode1,
5916                                                 &path1, lblk1 + len, 0);
5917                         if (unlikely(*erp))
5918                                 goto finish;
5919                 }
5920                 if (len != e2_len) {
5921                         split = 1;
5922                         *erp = ext4_force_split_extent_at(handle, inode2,
5923                                                 &path2, lblk2 + len, 0);
5924                         if (*erp)
5925                                 goto finish;
5926                 }
5927                 /* ext4_split_extent_at() may result in leaf extent split,
5928                  * path must to be revalidated. */
5929                 if (split)
5930                         goto repeat;
5931
5932                 BUG_ON(e2_len != e1_len);
5933                 *erp = ext4_ext_get_access(handle, inode1, path1 + path1->p_depth);
5934                 if (unlikely(*erp))
5935                         goto finish;
5936                 *erp = ext4_ext_get_access(handle, inode2, path2 + path2->p_depth);
5937                 if (unlikely(*erp))
5938                         goto finish;
5939
5940                 /* Both extents are fully inside boundaries. Swap it now */
5941                 tmp_ex = *ex1;
5942                 ext4_ext_store_pblock(ex1, ext4_ext_pblock(ex2));
5943                 ext4_ext_store_pblock(ex2, ext4_ext_pblock(&tmp_ex));
5944                 ex1->ee_len = cpu_to_le16(e2_len);
5945                 ex2->ee_len = cpu_to_le16(e1_len);
5946                 if (unwritten)
5947                         ext4_ext_mark_unwritten(ex2);
5948                 if (ext4_ext_is_unwritten(&tmp_ex))
5949                         ext4_ext_mark_unwritten(ex1);
5950
5951                 ext4_ext_try_to_merge(handle, inode2, path2, ex2);
5952                 ext4_ext_try_to_merge(handle, inode1, path1, ex1);
5953                 *erp = ext4_ext_dirty(handle, inode2, path2 +
5954                                       path2->p_depth);
5955                 if (unlikely(*erp))
5956                         goto finish;
5957                 *erp = ext4_ext_dirty(handle, inode1, path1 +
5958                                       path1->p_depth);
5959                 /*
5960                  * Looks scarry ah..? second inode already points to new blocks,
5961                  * and it was successfully dirtied. But luckily error may happen
5962                  * only due to journal error, so full transaction will be
5963                  * aborted anyway.
5964                  */
5965                 if (unlikely(*erp))
5966                         goto finish;
5967                 lblk1 += len;
5968                 lblk2 += len;
5969                 replaced_count += len;
5970                 count -= len;
5971
5972         repeat:
5973                 ext4_ext_drop_refs(path1);
5974                 kfree(path1);
5975                 ext4_ext_drop_refs(path2);
5976                 kfree(path2);
5977                 path1 = path2 = NULL;
5978         }
5979         return replaced_count;
5980 }
5981
5982 /*
5983  * ext4_clu_mapped - determine whether any block in a logical cluster has
5984  *                   been mapped to a physical cluster
5985  *
5986  * @inode - file containing the logical cluster
5987  * @lclu - logical cluster of interest
5988  *
5989  * Returns 1 if any block in the logical cluster is mapped, signifying
5990  * that a physical cluster has been allocated for it.  Otherwise,
5991  * returns 0.  Can also return negative error codes.  Derived from
5992  * ext4_ext_map_blocks().
5993  */
5994 int ext4_clu_mapped(struct inode *inode, ext4_lblk_t lclu)
5995 {
5996         struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5997         struct ext4_ext_path *path;
5998         int depth, mapped = 0, err = 0;
5999         struct ext4_extent *extent;
6000         ext4_lblk_t first_lblk, first_lclu, last_lclu;
6001
6002         /* search for the extent closest to the first block in the cluster */
6003         path = ext4_find_extent(inode, EXT4_C2B(sbi, lclu), NULL, 0);
6004         if (IS_ERR(path)) {
6005                 err = PTR_ERR(path);
6006                 path = NULL;
6007                 goto out;
6008         }
6009
6010         depth = ext_depth(inode);
6011
6012         /*
6013          * A consistent leaf must not be empty.  This situation is possible,
6014          * though, _during_ tree modification, and it's why an assert can't
6015          * be put in ext4_find_extent().
6016          */
6017         if (unlikely(path[depth].p_ext == NULL && depth != 0)) {
6018                 EXT4_ERROR_INODE(inode,
6019                     "bad extent address - lblock: %lu, depth: %d, pblock: %lld",
6020                                  (unsigned long) EXT4_C2B(sbi, lclu),
6021                                  depth, path[depth].p_block);
6022                 err = -EFSCORRUPTED;
6023                 goto out;
6024         }
6025
6026         extent = path[depth].p_ext;
6027
6028         /* can't be mapped if the extent tree is empty */
6029         if (extent == NULL)
6030                 goto out;
6031
6032         first_lblk = le32_to_cpu(extent->ee_block);
6033         first_lclu = EXT4_B2C(sbi, first_lblk);
6034
6035         /*
6036          * Three possible outcomes at this point - found extent spanning
6037          * the target cluster, to the left of the target cluster, or to the
6038          * right of the target cluster.  The first two cases are handled here.
6039          * The last case indicates the target cluster is not mapped.
6040          */
6041         if (lclu >= first_lclu) {
6042                 last_lclu = EXT4_B2C(sbi, first_lblk +
6043                                      ext4_ext_get_actual_len(extent) - 1);
6044                 if (lclu <= last_lclu) {
6045                         mapped = 1;
6046                 } else {
6047                         first_lblk = ext4_ext_next_allocated_block(path);
6048                         first_lclu = EXT4_B2C(sbi, first_lblk);
6049                         if (lclu == first_lclu)
6050                                 mapped = 1;
6051                 }
6052         }
6053
6054 out:
6055         ext4_ext_drop_refs(path);
6056         kfree(path);
6057
6058         return err ? err : mapped;
6059 }