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