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