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