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