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