ext4: check for zero length extent
[firefly-linux-kernel-4.4.55.git] / fs / ext4 / extents.c
1 /*
2  * Copyright (c) 2003-2006, Cluster File Systems, Inc, info@clusterfs.com
3  * Written by Alex Tomas <alex@clusterfs.com>
4  *
5  * Architecture independence:
6  *   Copyright (c) 2005, Bull S.A.
7  *   Written by Pierre Peiffer <pierre.peiffer@bull.net>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License version 2 as
11  * published by the Free Software Foundation.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public Licens
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-
21  */
22
23 /*
24  * Extents support for EXT4
25  *
26  * TODO:
27  *   - ext4*_error() should be used in some situations
28  *   - analyze all BUG()/BUG_ON(), use -EIO where appropriate
29  *   - smart tree reduction
30  */
31
32 #include <linux/fs.h>
33 #include <linux/time.h>
34 #include <linux/jbd2.h>
35 #include <linux/highuid.h>
36 #include <linux/pagemap.h>
37 #include <linux/quotaops.h>
38 #include <linux/string.h>
39 #include <linux/slab.h>
40 #include <linux/falloc.h>
41 #include <asm/uaccess.h>
42 #include <linux/fiemap.h>
43 #include "ext4_jbd2.h"
44
45 #include <trace/events/ext4.h>
46
47 static int ext4_split_extent(handle_t *handle,
48                                 struct inode *inode,
49                                 struct ext4_ext_path *path,
50                                 struct ext4_map_blocks *map,
51                                 int split_flag,
52                                 int flags);
53
54 static int ext4_ext_truncate_extend_restart(handle_t *handle,
55                                             struct inode *inode,
56                                             int needed)
57 {
58         int err;
59
60         if (!ext4_handle_valid(handle))
61                 return 0;
62         if (handle->h_buffer_credits > needed)
63                 return 0;
64         err = ext4_journal_extend(handle, needed);
65         if (err <= 0)
66                 return err;
67         err = ext4_truncate_restart_trans(handle, inode, needed);
68         if (err == 0)
69                 err = -EAGAIN;
70
71         return err;
72 }
73
74 /*
75  * could return:
76  *  - EROFS
77  *  - ENOMEM
78  */
79 static int ext4_ext_get_access(handle_t *handle, struct inode *inode,
80                                 struct ext4_ext_path *path)
81 {
82         if (path->p_bh) {
83                 /* path points to block */
84                 return ext4_journal_get_write_access(handle, path->p_bh);
85         }
86         /* path points to leaf/index in inode body */
87         /* we use in-core data, no need to protect them */
88         return 0;
89 }
90
91 /*
92  * could return:
93  *  - EROFS
94  *  - ENOMEM
95  *  - EIO
96  */
97 #define ext4_ext_dirty(handle, inode, path) \
98                 __ext4_ext_dirty(__func__, __LINE__, (handle), (inode), (path))
99 static int __ext4_ext_dirty(const char *where, unsigned int line,
100                             handle_t *handle, struct inode *inode,
101                             struct ext4_ext_path *path)
102 {
103         int err;
104         if (path->p_bh) {
105                 /* path points to block */
106                 err = __ext4_handle_dirty_metadata(where, line, handle,
107                                                    inode, path->p_bh);
108         } else {
109                 /* path points to leaf/index in inode body */
110                 err = ext4_mark_inode_dirty(handle, inode);
111         }
112         return err;
113 }
114
115 static ext4_fsblk_t ext4_ext_find_goal(struct inode *inode,
116                               struct ext4_ext_path *path,
117                               ext4_lblk_t block)
118 {
119         if (path) {
120                 int depth = path->p_depth;
121                 struct ext4_extent *ex;
122
123                 /*
124                  * Try to predict block placement assuming that we are
125                  * filling in a file which will eventually be
126                  * non-sparse --- i.e., in the case of libbfd writing
127                  * an ELF object sections out-of-order but in a way
128                  * the eventually results in a contiguous object or
129                  * executable file, or some database extending a table
130                  * space file.  However, this is actually somewhat
131                  * non-ideal if we are writing a sparse file such as
132                  * qemu or KVM writing a raw image file that is going
133                  * to stay fairly sparse, since it will end up
134                  * fragmenting the file system's free space.  Maybe we
135                  * should have some hueristics or some way to allow
136                  * userspace to pass a hint to file system,
137                  * especially if the latter case turns out to be
138                  * common.
139                  */
140                 ex = path[depth].p_ext;
141                 if (ex) {
142                         ext4_fsblk_t ext_pblk = ext4_ext_pblock(ex);
143                         ext4_lblk_t ext_block = le32_to_cpu(ex->ee_block);
144
145                         if (block > ext_block)
146                                 return ext_pblk + (block - ext_block);
147                         else
148                                 return ext_pblk - (ext_block - block);
149                 }
150
151                 /* it looks like index is empty;
152                  * try to find starting block from index itself */
153                 if (path[depth].p_bh)
154                         return path[depth].p_bh->b_blocknr;
155         }
156
157         /* OK. use inode's group */
158         return ext4_inode_to_goal_block(inode);
159 }
160
161 /*
162  * Allocation for a meta data block
163  */
164 static ext4_fsblk_t
165 ext4_ext_new_meta_block(handle_t *handle, struct inode *inode,
166                         struct ext4_ext_path *path,
167                         struct ext4_extent *ex, int *err, unsigned int flags)
168 {
169         ext4_fsblk_t goal, newblock;
170
171         goal = ext4_ext_find_goal(inode, path, le32_to_cpu(ex->ee_block));
172         newblock = ext4_new_meta_blocks(handle, inode, goal, flags,
173                                         NULL, err);
174         return newblock;
175 }
176
177 static inline int ext4_ext_space_block(struct inode *inode, int check)
178 {
179         int size;
180
181         size = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
182                         / sizeof(struct ext4_extent);
183 #ifdef AGGRESSIVE_TEST
184         if (!check && size > 6)
185                 size = 6;
186 #endif
187         return size;
188 }
189
190 static inline int ext4_ext_space_block_idx(struct inode *inode, int check)
191 {
192         int size;
193
194         size = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
195                         / sizeof(struct ext4_extent_idx);
196 #ifdef AGGRESSIVE_TEST
197         if (!check && size > 5)
198                 size = 5;
199 #endif
200         return size;
201 }
202
203 static inline int ext4_ext_space_root(struct inode *inode, int check)
204 {
205         int size;
206
207         size = sizeof(EXT4_I(inode)->i_data);
208         size -= sizeof(struct ext4_extent_header);
209         size /= sizeof(struct ext4_extent);
210 #ifdef AGGRESSIVE_TEST
211         if (!check && size > 3)
212                 size = 3;
213 #endif
214         return size;
215 }
216
217 static inline int ext4_ext_space_root_idx(struct inode *inode, int check)
218 {
219         int size;
220
221         size = sizeof(EXT4_I(inode)->i_data);
222         size -= sizeof(struct ext4_extent_header);
223         size /= sizeof(struct ext4_extent_idx);
224 #ifdef AGGRESSIVE_TEST
225         if (!check && size > 4)
226                 size = 4;
227 #endif
228         return size;
229 }
230
231 /*
232  * Calculate the number of metadata blocks needed
233  * to allocate @blocks
234  * Worse case is one block per extent
235  */
236 int ext4_ext_calc_metadata_amount(struct inode *inode, ext4_lblk_t lblock)
237 {
238         struct ext4_inode_info *ei = EXT4_I(inode);
239         int idxs;
240
241         idxs = ((inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
242                 / sizeof(struct ext4_extent_idx));
243
244         /*
245          * If the new delayed allocation block is contiguous with the
246          * previous da block, it can share index blocks with the
247          * previous block, so we only need to allocate a new index
248          * block every idxs leaf blocks.  At ldxs**2 blocks, we need
249          * an additional index block, and at ldxs**3 blocks, yet
250          * another index blocks.
251          */
252         if (ei->i_da_metadata_calc_len &&
253             ei->i_da_metadata_calc_last_lblock+1 == lblock) {
254                 int num = 0;
255
256                 if ((ei->i_da_metadata_calc_len % idxs) == 0)
257                         num++;
258                 if ((ei->i_da_metadata_calc_len % (idxs*idxs)) == 0)
259                         num++;
260                 if ((ei->i_da_metadata_calc_len % (idxs*idxs*idxs)) == 0) {
261                         num++;
262                         ei->i_da_metadata_calc_len = 0;
263                 } else
264                         ei->i_da_metadata_calc_len++;
265                 ei->i_da_metadata_calc_last_lblock++;
266                 return num;
267         }
268
269         /*
270          * In the worst case we need a new set of index blocks at
271          * every level of the inode's extent tree.
272          */
273         ei->i_da_metadata_calc_len = 1;
274         ei->i_da_metadata_calc_last_lblock = lblock;
275         return ext_depth(inode) + 1;
276 }
277
278 static int
279 ext4_ext_max_entries(struct inode *inode, int depth)
280 {
281         int max;
282
283         if (depth == ext_depth(inode)) {
284                 if (depth == 0)
285                         max = ext4_ext_space_root(inode, 1);
286                 else
287                         max = ext4_ext_space_root_idx(inode, 1);
288         } else {
289                 if (depth == 0)
290                         max = ext4_ext_space_block(inode, 1);
291                 else
292                         max = ext4_ext_space_block_idx(inode, 1);
293         }
294
295         return max;
296 }
297
298 static int ext4_valid_extent(struct inode *inode, struct ext4_extent *ext)
299 {
300         ext4_fsblk_t block = ext4_ext_pblock(ext);
301         int len = ext4_ext_get_actual_len(ext);
302
303         if (len == 0)
304                 return 0;
305         return ext4_data_block_valid(EXT4_SB(inode->i_sb), block, len);
306 }
307
308 static int ext4_valid_extent_idx(struct inode *inode,
309                                 struct ext4_extent_idx *ext_idx)
310 {
311         ext4_fsblk_t block = ext4_idx_pblock(ext_idx);
312
313         return ext4_data_block_valid(EXT4_SB(inode->i_sb), block, 1);
314 }
315
316 static int ext4_valid_extent_entries(struct inode *inode,
317                                 struct ext4_extent_header *eh,
318                                 int depth)
319 {
320         unsigned short entries;
321         if (eh->eh_entries == 0)
322                 return 1;
323
324         entries = le16_to_cpu(eh->eh_entries);
325
326         if (depth == 0) {
327                 /* leaf entries */
328                 struct ext4_extent *ext = EXT_FIRST_EXTENT(eh);
329                 while (entries) {
330                         if (!ext4_valid_extent(inode, ext))
331                                 return 0;
332                         ext++;
333                         entries--;
334                 }
335         } else {
336                 struct ext4_extent_idx *ext_idx = EXT_FIRST_INDEX(eh);
337                 while (entries) {
338                         if (!ext4_valid_extent_idx(inode, ext_idx))
339                                 return 0;
340                         ext_idx++;
341                         entries--;
342                 }
343         }
344         return 1;
345 }
346
347 static int __ext4_ext_check(const char *function, unsigned int line,
348                             struct inode *inode, struct ext4_extent_header *eh,
349                             int depth)
350 {
351         const char *error_msg;
352         int max = 0;
353
354         if (unlikely(eh->eh_magic != EXT4_EXT_MAGIC)) {
355                 error_msg = "invalid magic";
356                 goto corrupted;
357         }
358         if (unlikely(le16_to_cpu(eh->eh_depth) != depth)) {
359                 error_msg = "unexpected eh_depth";
360                 goto corrupted;
361         }
362         if (unlikely(eh->eh_max == 0)) {
363                 error_msg = "invalid eh_max";
364                 goto corrupted;
365         }
366         max = ext4_ext_max_entries(inode, depth);
367         if (unlikely(le16_to_cpu(eh->eh_max) > max)) {
368                 error_msg = "too large eh_max";
369                 goto corrupted;
370         }
371         if (unlikely(le16_to_cpu(eh->eh_entries) > le16_to_cpu(eh->eh_max))) {
372                 error_msg = "invalid eh_entries";
373                 goto corrupted;
374         }
375         if (!ext4_valid_extent_entries(inode, eh, depth)) {
376                 error_msg = "invalid extent entries";
377                 goto corrupted;
378         }
379         return 0;
380
381 corrupted:
382         ext4_error_inode(inode, function, line, 0,
383                         "bad header/extent: %s - magic %x, "
384                         "entries %u, max %u(%u), depth %u(%u)",
385                         error_msg, le16_to_cpu(eh->eh_magic),
386                         le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max),
387                         max, le16_to_cpu(eh->eh_depth), depth);
388
389         return -EIO;
390 }
391
392 #define ext4_ext_check(inode, eh, depth)        \
393         __ext4_ext_check(__func__, __LINE__, inode, eh, depth)
394
395 int ext4_ext_check_inode(struct inode *inode)
396 {
397         return ext4_ext_check(inode, ext_inode_hdr(inode), ext_depth(inode));
398 }
399
400 #ifdef EXT_DEBUG
401 static void ext4_ext_show_path(struct inode *inode, struct ext4_ext_path *path)
402 {
403         int k, l = path->p_depth;
404
405         ext_debug("path:");
406         for (k = 0; k <= l; k++, path++) {
407                 if (path->p_idx) {
408                   ext_debug("  %d->%llu", le32_to_cpu(path->p_idx->ei_block),
409                             ext4_idx_pblock(path->p_idx));
410                 } else if (path->p_ext) {
411                         ext_debug("  %d:[%d]%d:%llu ",
412                                   le32_to_cpu(path->p_ext->ee_block),
413                                   ext4_ext_is_uninitialized(path->p_ext),
414                                   ext4_ext_get_actual_len(path->p_ext),
415                                   ext4_ext_pblock(path->p_ext));
416                 } else
417                         ext_debug("  []");
418         }
419         ext_debug("\n");
420 }
421
422 static void ext4_ext_show_leaf(struct inode *inode, struct ext4_ext_path *path)
423 {
424         int depth = ext_depth(inode);
425         struct ext4_extent_header *eh;
426         struct ext4_extent *ex;
427         int i;
428
429         if (!path)
430                 return;
431
432         eh = path[depth].p_hdr;
433         ex = EXT_FIRST_EXTENT(eh);
434
435         ext_debug("Displaying leaf extents for inode %lu\n", inode->i_ino);
436
437         for (i = 0; i < le16_to_cpu(eh->eh_entries); i++, ex++) {
438                 ext_debug("%d:[%d]%d:%llu ", le32_to_cpu(ex->ee_block),
439                           ext4_ext_is_uninitialized(ex),
440                           ext4_ext_get_actual_len(ex), ext4_ext_pblock(ex));
441         }
442         ext_debug("\n");
443 }
444
445 static void ext4_ext_show_move(struct inode *inode, struct ext4_ext_path *path,
446                         ext4_fsblk_t newblock, int level)
447 {
448         int depth = ext_depth(inode);
449         struct ext4_extent *ex;
450
451         if (depth != level) {
452                 struct ext4_extent_idx *idx;
453                 idx = path[level].p_idx;
454                 while (idx <= EXT_MAX_INDEX(path[level].p_hdr)) {
455                         ext_debug("%d: move %d:%llu in new index %llu\n", level,
456                                         le32_to_cpu(idx->ei_block),
457                                         ext4_idx_pblock(idx),
458                                         newblock);
459                         idx++;
460                 }
461
462                 return;
463         }
464
465         ex = path[depth].p_ext;
466         while (ex <= EXT_MAX_EXTENT(path[depth].p_hdr)) {
467                 ext_debug("move %d:%llu:[%d]%d in new leaf %llu\n",
468                                 le32_to_cpu(ex->ee_block),
469                                 ext4_ext_pblock(ex),
470                                 ext4_ext_is_uninitialized(ex),
471                                 ext4_ext_get_actual_len(ex),
472                                 newblock);
473                 ex++;
474         }
475 }
476
477 #else
478 #define ext4_ext_show_path(inode, path)
479 #define ext4_ext_show_leaf(inode, path)
480 #define ext4_ext_show_move(inode, path, newblock, level)
481 #endif
482
483 void ext4_ext_drop_refs(struct ext4_ext_path *path)
484 {
485         int depth = path->p_depth;
486         int i;
487
488         for (i = 0; i <= depth; i++, path++)
489                 if (path->p_bh) {
490                         brelse(path->p_bh);
491                         path->p_bh = NULL;
492                 }
493 }
494
495 /*
496  * ext4_ext_binsearch_idx:
497  * binary search for the closest index of the given block
498  * the header must be checked before calling this
499  */
500 static void
501 ext4_ext_binsearch_idx(struct inode *inode,
502                         struct ext4_ext_path *path, ext4_lblk_t block)
503 {
504         struct ext4_extent_header *eh = path->p_hdr;
505         struct ext4_extent_idx *r, *l, *m;
506
507
508         ext_debug("binsearch for %u(idx):  ", block);
509
510         l = EXT_FIRST_INDEX(eh) + 1;
511         r = EXT_LAST_INDEX(eh);
512         while (l <= r) {
513                 m = l + (r - l) / 2;
514                 if (block < le32_to_cpu(m->ei_block))
515                         r = m - 1;
516                 else
517                         l = m + 1;
518                 ext_debug("%p(%u):%p(%u):%p(%u) ", l, le32_to_cpu(l->ei_block),
519                                 m, le32_to_cpu(m->ei_block),
520                                 r, le32_to_cpu(r->ei_block));
521         }
522
523         path->p_idx = l - 1;
524         ext_debug("  -> %d->%lld ", le32_to_cpu(path->p_idx->ei_block),
525                   ext4_idx_pblock(path->p_idx));
526
527 #ifdef CHECK_BINSEARCH
528         {
529                 struct ext4_extent_idx *chix, *ix;
530                 int k;
531
532                 chix = ix = EXT_FIRST_INDEX(eh);
533                 for (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ix++) {
534                   if (k != 0 &&
535                       le32_to_cpu(ix->ei_block) <= le32_to_cpu(ix[-1].ei_block)) {
536                                 printk(KERN_DEBUG "k=%d, ix=0x%p, "
537                                        "first=0x%p\n", k,
538                                        ix, EXT_FIRST_INDEX(eh));
539                                 printk(KERN_DEBUG "%u <= %u\n",
540                                        le32_to_cpu(ix->ei_block),
541                                        le32_to_cpu(ix[-1].ei_block));
542                         }
543                         BUG_ON(k && le32_to_cpu(ix->ei_block)
544                                            <= le32_to_cpu(ix[-1].ei_block));
545                         if (block < le32_to_cpu(ix->ei_block))
546                                 break;
547                         chix = ix;
548                 }
549                 BUG_ON(chix != path->p_idx);
550         }
551 #endif
552
553 }
554
555 /*
556  * ext4_ext_binsearch:
557  * binary search for closest extent of the given block
558  * the header must be checked before calling this
559  */
560 static void
561 ext4_ext_binsearch(struct inode *inode,
562                 struct ext4_ext_path *path, ext4_lblk_t block)
563 {
564         struct ext4_extent_header *eh = path->p_hdr;
565         struct ext4_extent *r, *l, *m;
566
567         if (eh->eh_entries == 0) {
568                 /*
569                  * this leaf is empty:
570                  * we get such a leaf in split/add case
571                  */
572                 return;
573         }
574
575         ext_debug("binsearch for %u:  ", block);
576
577         l = EXT_FIRST_EXTENT(eh) + 1;
578         r = EXT_LAST_EXTENT(eh);
579
580         while (l <= r) {
581                 m = l + (r - l) / 2;
582                 if (block < le32_to_cpu(m->ee_block))
583                         r = m - 1;
584                 else
585                         l = m + 1;
586                 ext_debug("%p(%u):%p(%u):%p(%u) ", l, le32_to_cpu(l->ee_block),
587                                 m, le32_to_cpu(m->ee_block),
588                                 r, le32_to_cpu(r->ee_block));
589         }
590
591         path->p_ext = l - 1;
592         ext_debug("  -> %d:%llu:[%d]%d ",
593                         le32_to_cpu(path->p_ext->ee_block),
594                         ext4_ext_pblock(path->p_ext),
595                         ext4_ext_is_uninitialized(path->p_ext),
596                         ext4_ext_get_actual_len(path->p_ext));
597
598 #ifdef CHECK_BINSEARCH
599         {
600                 struct ext4_extent *chex, *ex;
601                 int k;
602
603                 chex = ex = EXT_FIRST_EXTENT(eh);
604                 for (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ex++) {
605                         BUG_ON(k && le32_to_cpu(ex->ee_block)
606                                           <= le32_to_cpu(ex[-1].ee_block));
607                         if (block < le32_to_cpu(ex->ee_block))
608                                 break;
609                         chex = ex;
610                 }
611                 BUG_ON(chex != path->p_ext);
612         }
613 #endif
614
615 }
616
617 int ext4_ext_tree_init(handle_t *handle, struct inode *inode)
618 {
619         struct ext4_extent_header *eh;
620
621         eh = ext_inode_hdr(inode);
622         eh->eh_depth = 0;
623         eh->eh_entries = 0;
624         eh->eh_magic = EXT4_EXT_MAGIC;
625         eh->eh_max = cpu_to_le16(ext4_ext_space_root(inode, 0));
626         ext4_mark_inode_dirty(handle, inode);
627         ext4_ext_invalidate_cache(inode);
628         return 0;
629 }
630
631 struct ext4_ext_path *
632 ext4_ext_find_extent(struct inode *inode, ext4_lblk_t block,
633                                         struct ext4_ext_path *path)
634 {
635         struct ext4_extent_header *eh;
636         struct buffer_head *bh;
637         short int depth, i, ppos = 0, alloc = 0;
638
639         eh = ext_inode_hdr(inode);
640         depth = ext_depth(inode);
641
642         /* account possible depth increase */
643         if (!path) {
644                 path = kzalloc(sizeof(struct ext4_ext_path) * (depth + 2),
645                                 GFP_NOFS);
646                 if (!path)
647                         return ERR_PTR(-ENOMEM);
648                 alloc = 1;
649         }
650         path[0].p_hdr = eh;
651         path[0].p_bh = NULL;
652
653         i = depth;
654         /* walk through the tree */
655         while (i) {
656                 int need_to_validate = 0;
657
658                 ext_debug("depth %d: num %d, max %d\n",
659                           ppos, le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
660
661                 ext4_ext_binsearch_idx(inode, path + ppos, block);
662                 path[ppos].p_block = ext4_idx_pblock(path[ppos].p_idx);
663                 path[ppos].p_depth = i;
664                 path[ppos].p_ext = NULL;
665
666                 bh = sb_getblk(inode->i_sb, path[ppos].p_block);
667                 if (unlikely(!bh))
668                         goto err;
669                 if (!bh_uptodate_or_lock(bh)) {
670                         trace_ext4_ext_load_extent(inode, block,
671                                                 path[ppos].p_block);
672                         if (bh_submit_read(bh) < 0) {
673                                 put_bh(bh);
674                                 goto err;
675                         }
676                         /* validate the extent entries */
677                         need_to_validate = 1;
678                 }
679                 eh = ext_block_hdr(bh);
680                 ppos++;
681                 if (unlikely(ppos > depth)) {
682                         put_bh(bh);
683                         EXT4_ERROR_INODE(inode,
684                                          "ppos %d > depth %d", ppos, depth);
685                         goto err;
686                 }
687                 path[ppos].p_bh = bh;
688                 path[ppos].p_hdr = eh;
689                 i--;
690
691                 if (need_to_validate && ext4_ext_check(inode, eh, i))
692                         goto err;
693         }
694
695         path[ppos].p_depth = i;
696         path[ppos].p_ext = NULL;
697         path[ppos].p_idx = NULL;
698
699         /* find extent */
700         ext4_ext_binsearch(inode, path + ppos, block);
701         /* if not an empty leaf */
702         if (path[ppos].p_ext)
703                 path[ppos].p_block = ext4_ext_pblock(path[ppos].p_ext);
704
705         ext4_ext_show_path(inode, path);
706
707         return path;
708
709 err:
710         ext4_ext_drop_refs(path);
711         if (alloc)
712                 kfree(path);
713         return ERR_PTR(-EIO);
714 }
715
716 /*
717  * ext4_ext_insert_index:
718  * insert new index [@logical;@ptr] into the block at @curp;
719  * check where to insert: before @curp or after @curp
720  */
721 static int ext4_ext_insert_index(handle_t *handle, struct inode *inode,
722                                  struct ext4_ext_path *curp,
723                                  int logical, ext4_fsblk_t ptr)
724 {
725         struct ext4_extent_idx *ix;
726         int len, err;
727
728         err = ext4_ext_get_access(handle, inode, curp);
729         if (err)
730                 return err;
731
732         if (unlikely(logical == le32_to_cpu(curp->p_idx->ei_block))) {
733                 EXT4_ERROR_INODE(inode,
734                                  "logical %d == ei_block %d!",
735                                  logical, le32_to_cpu(curp->p_idx->ei_block));
736                 return -EIO;
737         }
738
739         if (unlikely(le16_to_cpu(curp->p_hdr->eh_entries)
740                              >= le16_to_cpu(curp->p_hdr->eh_max))) {
741                 EXT4_ERROR_INODE(inode,
742                                  "eh_entries %d >= eh_max %d!",
743                                  le16_to_cpu(curp->p_hdr->eh_entries),
744                                  le16_to_cpu(curp->p_hdr->eh_max));
745                 return -EIO;
746         }
747
748         if (logical > le32_to_cpu(curp->p_idx->ei_block)) {
749                 /* insert after */
750                 ext_debug("insert new index %d after: %llu\n", logical, ptr);
751                 ix = curp->p_idx + 1;
752         } else {
753                 /* insert before */
754                 ext_debug("insert new index %d before: %llu\n", logical, ptr);
755                 ix = curp->p_idx;
756         }
757
758         len = EXT_LAST_INDEX(curp->p_hdr) - ix + 1;
759         BUG_ON(len < 0);
760         if (len > 0) {
761                 ext_debug("insert new index %d: "
762                                 "move %d indices from 0x%p to 0x%p\n",
763                                 logical, len, ix, ix + 1);
764                 memmove(ix + 1, ix, len * sizeof(struct ext4_extent_idx));
765         }
766
767         if (unlikely(ix > EXT_MAX_INDEX(curp->p_hdr))) {
768                 EXT4_ERROR_INODE(inode, "ix > EXT_MAX_INDEX!");
769                 return -EIO;
770         }
771
772         ix->ei_block = cpu_to_le32(logical);
773         ext4_idx_store_pblock(ix, ptr);
774         le16_add_cpu(&curp->p_hdr->eh_entries, 1);
775
776         if (unlikely(ix > EXT_LAST_INDEX(curp->p_hdr))) {
777                 EXT4_ERROR_INODE(inode, "ix > EXT_LAST_INDEX!");
778                 return -EIO;
779         }
780
781         err = ext4_ext_dirty(handle, inode, curp);
782         ext4_std_error(inode->i_sb, err);
783
784         return err;
785 }
786
787 /*
788  * ext4_ext_split:
789  * inserts new subtree into the path, using free index entry
790  * at depth @at:
791  * - allocates all needed blocks (new leaf and all intermediate index blocks)
792  * - makes decision where to split
793  * - moves remaining extents and index entries (right to the split point)
794  *   into the newly allocated blocks
795  * - initializes subtree
796  */
797 static int ext4_ext_split(handle_t *handle, struct inode *inode,
798                           unsigned int flags,
799                           struct ext4_ext_path *path,
800                           struct ext4_extent *newext, int at)
801 {
802         struct buffer_head *bh = NULL;
803         int depth = ext_depth(inode);
804         struct ext4_extent_header *neh;
805         struct ext4_extent_idx *fidx;
806         int i = at, k, m, a;
807         ext4_fsblk_t newblock, oldblock;
808         __le32 border;
809         ext4_fsblk_t *ablocks = NULL; /* array of allocated blocks */
810         int err = 0;
811
812         /* make decision: where to split? */
813         /* FIXME: now decision is simplest: at current extent */
814
815         /* if current leaf will be split, then we should use
816          * border from split point */
817         if (unlikely(path[depth].p_ext > EXT_MAX_EXTENT(path[depth].p_hdr))) {
818                 EXT4_ERROR_INODE(inode, "p_ext > EXT_MAX_EXTENT!");
819                 return -EIO;
820         }
821         if (path[depth].p_ext != EXT_MAX_EXTENT(path[depth].p_hdr)) {
822                 border = path[depth].p_ext[1].ee_block;
823                 ext_debug("leaf will be split."
824                                 " next leaf starts at %d\n",
825                                   le32_to_cpu(border));
826         } else {
827                 border = newext->ee_block;
828                 ext_debug("leaf will be added."
829                                 " next leaf starts at %d\n",
830                                 le32_to_cpu(border));
831         }
832
833         /*
834          * If error occurs, then we break processing
835          * and mark filesystem read-only. index won't
836          * be inserted and tree will be in consistent
837          * state. Next mount will repair buffers too.
838          */
839
840         /*
841          * Get array to track all allocated blocks.
842          * We need this to handle errors and free blocks
843          * upon them.
844          */
845         ablocks = kzalloc(sizeof(ext4_fsblk_t) * depth, GFP_NOFS);
846         if (!ablocks)
847                 return -ENOMEM;
848
849         /* allocate all needed blocks */
850         ext_debug("allocate %d blocks for indexes/leaf\n", depth - at);
851         for (a = 0; a < depth - at; a++) {
852                 newblock = ext4_ext_new_meta_block(handle, inode, path,
853                                                    newext, &err, flags);
854                 if (newblock == 0)
855                         goto cleanup;
856                 ablocks[a] = newblock;
857         }
858
859         /* initialize new leaf */
860         newblock = ablocks[--a];
861         if (unlikely(newblock == 0)) {
862                 EXT4_ERROR_INODE(inode, "newblock == 0!");
863                 err = -EIO;
864                 goto cleanup;
865         }
866         bh = sb_getblk(inode->i_sb, newblock);
867         if (!bh) {
868                 err = -EIO;
869                 goto cleanup;
870         }
871         lock_buffer(bh);
872
873         err = ext4_journal_get_create_access(handle, bh);
874         if (err)
875                 goto cleanup;
876
877         neh = ext_block_hdr(bh);
878         neh->eh_entries = 0;
879         neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0));
880         neh->eh_magic = EXT4_EXT_MAGIC;
881         neh->eh_depth = 0;
882
883         /* move remainder of path[depth] to the new leaf */
884         if (unlikely(path[depth].p_hdr->eh_entries !=
885                      path[depth].p_hdr->eh_max)) {
886                 EXT4_ERROR_INODE(inode, "eh_entries %d != eh_max %d!",
887                                  path[depth].p_hdr->eh_entries,
888                                  path[depth].p_hdr->eh_max);
889                 err = -EIO;
890                 goto cleanup;
891         }
892         /* start copy from next extent */
893         m = EXT_MAX_EXTENT(path[depth].p_hdr) - path[depth].p_ext++;
894         ext4_ext_show_move(inode, path, newblock, depth);
895         if (m) {
896                 struct ext4_extent *ex;
897                 ex = EXT_FIRST_EXTENT(neh);
898                 memmove(ex, path[depth].p_ext, sizeof(struct ext4_extent) * m);
899                 le16_add_cpu(&neh->eh_entries, m);
900         }
901
902         set_buffer_uptodate(bh);
903         unlock_buffer(bh);
904
905         err = ext4_handle_dirty_metadata(handle, inode, bh);
906         if (err)
907                 goto cleanup;
908         brelse(bh);
909         bh = NULL;
910
911         /* correct old leaf */
912         if (m) {
913                 err = ext4_ext_get_access(handle, inode, path + depth);
914                 if (err)
915                         goto cleanup;
916                 le16_add_cpu(&path[depth].p_hdr->eh_entries, -m);
917                 err = ext4_ext_dirty(handle, inode, path + depth);
918                 if (err)
919                         goto cleanup;
920
921         }
922
923         /* create intermediate indexes */
924         k = depth - at - 1;
925         if (unlikely(k < 0)) {
926                 EXT4_ERROR_INODE(inode, "k %d < 0!", k);
927                 err = -EIO;
928                 goto cleanup;
929         }
930         if (k)
931                 ext_debug("create %d intermediate indices\n", k);
932         /* insert new index into current index block */
933         /* current depth stored in i var */
934         i = depth - 1;
935         while (k--) {
936                 oldblock = newblock;
937                 newblock = ablocks[--a];
938                 bh = sb_getblk(inode->i_sb, newblock);
939                 if (!bh) {
940                         err = -EIO;
941                         goto cleanup;
942                 }
943                 lock_buffer(bh);
944
945                 err = ext4_journal_get_create_access(handle, bh);
946                 if (err)
947                         goto cleanup;
948
949                 neh = ext_block_hdr(bh);
950                 neh->eh_entries = cpu_to_le16(1);
951                 neh->eh_magic = EXT4_EXT_MAGIC;
952                 neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0));
953                 neh->eh_depth = cpu_to_le16(depth - i);
954                 fidx = EXT_FIRST_INDEX(neh);
955                 fidx->ei_block = border;
956                 ext4_idx_store_pblock(fidx, oldblock);
957
958                 ext_debug("int.index at %d (block %llu): %u -> %llu\n",
959                                 i, newblock, le32_to_cpu(border), oldblock);
960
961                 /* move remainder of path[i] to the new index block */
962                 if (unlikely(EXT_MAX_INDEX(path[i].p_hdr) !=
963                                         EXT_LAST_INDEX(path[i].p_hdr))) {
964                         EXT4_ERROR_INODE(inode,
965                                          "EXT_MAX_INDEX != EXT_LAST_INDEX ee_block %d!",
966                                          le32_to_cpu(path[i].p_ext->ee_block));
967                         err = -EIO;
968                         goto cleanup;
969                 }
970                 /* start copy indexes */
971                 m = EXT_MAX_INDEX(path[i].p_hdr) - path[i].p_idx++;
972                 ext_debug("cur 0x%p, last 0x%p\n", path[i].p_idx,
973                                 EXT_MAX_INDEX(path[i].p_hdr));
974                 ext4_ext_show_move(inode, path, newblock, i);
975                 if (m) {
976                         memmove(++fidx, path[i].p_idx,
977                                 sizeof(struct ext4_extent_idx) * m);
978                         le16_add_cpu(&neh->eh_entries, m);
979                 }
980                 set_buffer_uptodate(bh);
981                 unlock_buffer(bh);
982
983                 err = ext4_handle_dirty_metadata(handle, inode, bh);
984                 if (err)
985                         goto cleanup;
986                 brelse(bh);
987                 bh = NULL;
988
989                 /* correct old index */
990                 if (m) {
991                         err = ext4_ext_get_access(handle, inode, path + i);
992                         if (err)
993                                 goto cleanup;
994                         le16_add_cpu(&path[i].p_hdr->eh_entries, -m);
995                         err = ext4_ext_dirty(handle, inode, path + i);
996                         if (err)
997                                 goto cleanup;
998                 }
999
1000                 i--;
1001         }
1002
1003         /* insert new index */
1004         err = ext4_ext_insert_index(handle, inode, path + at,
1005                                     le32_to_cpu(border), newblock);
1006
1007 cleanup:
1008         if (bh) {
1009                 if (buffer_locked(bh))
1010                         unlock_buffer(bh);
1011                 brelse(bh);
1012         }
1013
1014         if (err) {
1015                 /* free all allocated blocks in error case */
1016                 for (i = 0; i < depth; i++) {
1017                         if (!ablocks[i])
1018                                 continue;
1019                         ext4_free_blocks(handle, inode, NULL, ablocks[i], 1,
1020                                          EXT4_FREE_BLOCKS_METADATA);
1021                 }
1022         }
1023         kfree(ablocks);
1024
1025         return err;
1026 }
1027
1028 /*
1029  * ext4_ext_grow_indepth:
1030  * implements tree growing procedure:
1031  * - allocates new block
1032  * - moves top-level data (index block or leaf) into the new block
1033  * - initializes new top-level, creating index that points to the
1034  *   just created block
1035  */
1036 static int ext4_ext_grow_indepth(handle_t *handle, struct inode *inode,
1037                                  unsigned int flags,
1038                                  struct ext4_extent *newext)
1039 {
1040         struct ext4_extent_header *neh;
1041         struct buffer_head *bh;
1042         ext4_fsblk_t newblock;
1043         int err = 0;
1044
1045         newblock = ext4_ext_new_meta_block(handle, inode, NULL,
1046                 newext, &err, flags);
1047         if (newblock == 0)
1048                 return err;
1049
1050         bh = sb_getblk(inode->i_sb, newblock);
1051         if (!bh) {
1052                 err = -EIO;
1053                 ext4_std_error(inode->i_sb, err);
1054                 return err;
1055         }
1056         lock_buffer(bh);
1057
1058         err = ext4_journal_get_create_access(handle, bh);
1059         if (err) {
1060                 unlock_buffer(bh);
1061                 goto out;
1062         }
1063
1064         /* move top-level index/leaf into new block */
1065         memmove(bh->b_data, EXT4_I(inode)->i_data,
1066                 sizeof(EXT4_I(inode)->i_data));
1067
1068         /* set size of new block */
1069         neh = ext_block_hdr(bh);
1070         /* old root could have indexes or leaves
1071          * so calculate e_max right way */
1072         if (ext_depth(inode))
1073                 neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0));
1074         else
1075                 neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0));
1076         neh->eh_magic = EXT4_EXT_MAGIC;
1077         set_buffer_uptodate(bh);
1078         unlock_buffer(bh);
1079
1080         err = ext4_handle_dirty_metadata(handle, inode, bh);
1081         if (err)
1082                 goto out;
1083
1084         /* Update top-level index: num,max,pointer */
1085         neh = ext_inode_hdr(inode);
1086         neh->eh_entries = cpu_to_le16(1);
1087         ext4_idx_store_pblock(EXT_FIRST_INDEX(neh), newblock);
1088         if (neh->eh_depth == 0) {
1089                 /* Root extent block becomes index block */
1090                 neh->eh_max = cpu_to_le16(ext4_ext_space_root_idx(inode, 0));
1091                 EXT_FIRST_INDEX(neh)->ei_block =
1092                         EXT_FIRST_EXTENT(neh)->ee_block;
1093         }
1094         ext_debug("new root: num %d(%d), lblock %d, ptr %llu\n",
1095                   le16_to_cpu(neh->eh_entries), le16_to_cpu(neh->eh_max),
1096                   le32_to_cpu(EXT_FIRST_INDEX(neh)->ei_block),
1097                   ext4_idx_pblock(EXT_FIRST_INDEX(neh)));
1098
1099         neh->eh_depth = cpu_to_le16(le16_to_cpu(neh->eh_depth) + 1);
1100         ext4_mark_inode_dirty(handle, inode);
1101 out:
1102         brelse(bh);
1103
1104         return err;
1105 }
1106
1107 /*
1108  * ext4_ext_create_new_leaf:
1109  * finds empty index and adds new leaf.
1110  * if no free index is found, then it requests in-depth growing.
1111  */
1112 static int ext4_ext_create_new_leaf(handle_t *handle, struct inode *inode,
1113                                     unsigned int flags,
1114                                     struct ext4_ext_path *path,
1115                                     struct ext4_extent *newext)
1116 {
1117         struct ext4_ext_path *curp;
1118         int depth, i, err = 0;
1119
1120 repeat:
1121         i = depth = ext_depth(inode);
1122
1123         /* walk up to the tree and look for free index entry */
1124         curp = path + depth;
1125         while (i > 0 && !EXT_HAS_FREE_INDEX(curp)) {
1126                 i--;
1127                 curp--;
1128         }
1129
1130         /* we use already allocated block for index block,
1131          * so subsequent data blocks should be contiguous */
1132         if (EXT_HAS_FREE_INDEX(curp)) {
1133                 /* if we found index with free entry, then use that
1134                  * entry: create all needed subtree and add new leaf */
1135                 err = ext4_ext_split(handle, inode, flags, path, newext, i);
1136                 if (err)
1137                         goto out;
1138
1139                 /* refill path */
1140                 ext4_ext_drop_refs(path);
1141                 path = ext4_ext_find_extent(inode,
1142                                     (ext4_lblk_t)le32_to_cpu(newext->ee_block),
1143                                     path);
1144                 if (IS_ERR(path))
1145                         err = PTR_ERR(path);
1146         } else {
1147                 /* tree is full, time to grow in depth */
1148                 err = ext4_ext_grow_indepth(handle, inode, flags, newext);
1149                 if (err)
1150                         goto out;
1151
1152                 /* refill path */
1153                 ext4_ext_drop_refs(path);
1154                 path = ext4_ext_find_extent(inode,
1155                                    (ext4_lblk_t)le32_to_cpu(newext->ee_block),
1156                                     path);
1157                 if (IS_ERR(path)) {
1158                         err = PTR_ERR(path);
1159                         goto out;
1160                 }
1161
1162                 /*
1163                  * only first (depth 0 -> 1) produces free space;
1164                  * in all other cases we have to split the grown tree
1165                  */
1166                 depth = ext_depth(inode);
1167                 if (path[depth].p_hdr->eh_entries == path[depth].p_hdr->eh_max) {
1168                         /* now we need to split */
1169                         goto repeat;
1170                 }
1171         }
1172
1173 out:
1174         return err;
1175 }
1176
1177 /*
1178  * search the closest allocated block to the left for *logical
1179  * and returns it at @logical + it's physical address at @phys
1180  * if *logical is the smallest allocated block, the function
1181  * returns 0 at @phys
1182  * return value contains 0 (success) or error code
1183  */
1184 static int ext4_ext_search_left(struct inode *inode,
1185                                 struct ext4_ext_path *path,
1186                                 ext4_lblk_t *logical, ext4_fsblk_t *phys)
1187 {
1188         struct ext4_extent_idx *ix;
1189         struct ext4_extent *ex;
1190         int depth, ee_len;
1191
1192         if (unlikely(path == NULL)) {
1193                 EXT4_ERROR_INODE(inode, "path == NULL *logical %d!", *logical);
1194                 return -EIO;
1195         }
1196         depth = path->p_depth;
1197         *phys = 0;
1198
1199         if (depth == 0 && path->p_ext == NULL)
1200                 return 0;
1201
1202         /* usually extent in the path covers blocks smaller
1203          * then *logical, but it can be that extent is the
1204          * first one in the file */
1205
1206         ex = path[depth].p_ext;
1207         ee_len = ext4_ext_get_actual_len(ex);
1208         if (*logical < le32_to_cpu(ex->ee_block)) {
1209                 if (unlikely(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex)) {
1210                         EXT4_ERROR_INODE(inode,
1211                                          "EXT_FIRST_EXTENT != ex *logical %d ee_block %d!",
1212                                          *logical, le32_to_cpu(ex->ee_block));
1213                         return -EIO;
1214                 }
1215                 while (--depth >= 0) {
1216                         ix = path[depth].p_idx;
1217                         if (unlikely(ix != EXT_FIRST_INDEX(path[depth].p_hdr))) {
1218                                 EXT4_ERROR_INODE(inode,
1219                                   "ix (%d) != EXT_FIRST_INDEX (%d) (depth %d)!",
1220                                   ix != NULL ? le32_to_cpu(ix->ei_block) : 0,
1221                                   EXT_FIRST_INDEX(path[depth].p_hdr) != NULL ?
1222                 le32_to_cpu(EXT_FIRST_INDEX(path[depth].p_hdr)->ei_block) : 0,
1223                                   depth);
1224                                 return -EIO;
1225                         }
1226                 }
1227                 return 0;
1228         }
1229
1230         if (unlikely(*logical < (le32_to_cpu(ex->ee_block) + ee_len))) {
1231                 EXT4_ERROR_INODE(inode,
1232                                  "logical %d < ee_block %d + ee_len %d!",
1233                                  *logical, le32_to_cpu(ex->ee_block), ee_len);
1234                 return -EIO;
1235         }
1236
1237         *logical = le32_to_cpu(ex->ee_block) + ee_len - 1;
1238         *phys = ext4_ext_pblock(ex) + ee_len - 1;
1239         return 0;
1240 }
1241
1242 /*
1243  * search the closest allocated block to the right for *logical
1244  * and returns it at @logical + it's physical address at @phys
1245  * if *logical is the largest allocated block, the function
1246  * returns 0 at @phys
1247  * return value contains 0 (success) or error code
1248  */
1249 static int ext4_ext_search_right(struct inode *inode,
1250                                  struct ext4_ext_path *path,
1251                                  ext4_lblk_t *logical, ext4_fsblk_t *phys,
1252                                  struct ext4_extent **ret_ex)
1253 {
1254         struct buffer_head *bh = NULL;
1255         struct ext4_extent_header *eh;
1256         struct ext4_extent_idx *ix;
1257         struct ext4_extent *ex;
1258         ext4_fsblk_t block;
1259         int depth;      /* Note, NOT eh_depth; depth from top of tree */
1260         int ee_len;
1261
1262         if (unlikely(path == NULL)) {
1263                 EXT4_ERROR_INODE(inode, "path == NULL *logical %d!", *logical);
1264                 return -EIO;
1265         }
1266         depth = path->p_depth;
1267         *phys = 0;
1268
1269         if (depth == 0 && path->p_ext == NULL)
1270                 return 0;
1271
1272         /* usually extent in the path covers blocks smaller
1273          * then *logical, but it can be that extent is the
1274          * first one in the file */
1275
1276         ex = path[depth].p_ext;
1277         ee_len = ext4_ext_get_actual_len(ex);
1278         if (*logical < le32_to_cpu(ex->ee_block)) {
1279                 if (unlikely(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex)) {
1280                         EXT4_ERROR_INODE(inode,
1281                                          "first_extent(path[%d].p_hdr) != ex",
1282                                          depth);
1283                         return -EIO;
1284                 }
1285                 while (--depth >= 0) {
1286                         ix = path[depth].p_idx;
1287                         if (unlikely(ix != EXT_FIRST_INDEX(path[depth].p_hdr))) {
1288                                 EXT4_ERROR_INODE(inode,
1289                                                  "ix != EXT_FIRST_INDEX *logical %d!",
1290                                                  *logical);
1291                                 return -EIO;
1292                         }
1293                 }
1294                 goto found_extent;
1295         }
1296
1297         if (unlikely(*logical < (le32_to_cpu(ex->ee_block) + ee_len))) {
1298                 EXT4_ERROR_INODE(inode,
1299                                  "logical %d < ee_block %d + ee_len %d!",
1300                                  *logical, le32_to_cpu(ex->ee_block), ee_len);
1301                 return -EIO;
1302         }
1303
1304         if (ex != EXT_LAST_EXTENT(path[depth].p_hdr)) {
1305                 /* next allocated block in this leaf */
1306                 ex++;
1307                 goto found_extent;
1308         }
1309
1310         /* go up and search for index to the right */
1311         while (--depth >= 0) {
1312                 ix = path[depth].p_idx;
1313                 if (ix != EXT_LAST_INDEX(path[depth].p_hdr))
1314                         goto got_index;
1315         }
1316
1317         /* we've gone up to the root and found no index to the right */
1318         return 0;
1319
1320 got_index:
1321         /* we've found index to the right, let's
1322          * follow it and find the closest allocated
1323          * block to the right */
1324         ix++;
1325         block = ext4_idx_pblock(ix);
1326         while (++depth < path->p_depth) {
1327                 bh = sb_bread(inode->i_sb, block);
1328                 if (bh == NULL)
1329                         return -EIO;
1330                 eh = ext_block_hdr(bh);
1331                 /* subtract from p_depth to get proper eh_depth */
1332                 if (ext4_ext_check(inode, eh, path->p_depth - depth)) {
1333                         put_bh(bh);
1334                         return -EIO;
1335                 }
1336                 ix = EXT_FIRST_INDEX(eh);
1337                 block = ext4_idx_pblock(ix);
1338                 put_bh(bh);
1339         }
1340
1341         bh = sb_bread(inode->i_sb, block);
1342         if (bh == NULL)
1343                 return -EIO;
1344         eh = ext_block_hdr(bh);
1345         if (ext4_ext_check(inode, eh, path->p_depth - depth)) {
1346                 put_bh(bh);
1347                 return -EIO;
1348         }
1349         ex = EXT_FIRST_EXTENT(eh);
1350 found_extent:
1351         *logical = le32_to_cpu(ex->ee_block);
1352         *phys = ext4_ext_pblock(ex);
1353         *ret_ex = ex;
1354         if (bh)
1355                 put_bh(bh);
1356         return 0;
1357 }
1358
1359 /*
1360  * ext4_ext_next_allocated_block:
1361  * returns allocated block in subsequent extent or EXT_MAX_BLOCKS.
1362  * NOTE: it considers block number from index entry as
1363  * allocated block. Thus, index entries have to be consistent
1364  * with leaves.
1365  */
1366 static ext4_lblk_t
1367 ext4_ext_next_allocated_block(struct ext4_ext_path *path)
1368 {
1369         int depth;
1370
1371         BUG_ON(path == NULL);
1372         depth = path->p_depth;
1373
1374         if (depth == 0 && path->p_ext == NULL)
1375                 return EXT_MAX_BLOCKS;
1376
1377         while (depth >= 0) {
1378                 if (depth == path->p_depth) {
1379                         /* leaf */
1380                         if (path[depth].p_ext &&
1381                                 path[depth].p_ext !=
1382                                         EXT_LAST_EXTENT(path[depth].p_hdr))
1383                           return le32_to_cpu(path[depth].p_ext[1].ee_block);
1384                 } else {
1385                         /* index */
1386                         if (path[depth].p_idx !=
1387                                         EXT_LAST_INDEX(path[depth].p_hdr))
1388                           return le32_to_cpu(path[depth].p_idx[1].ei_block);
1389                 }
1390                 depth--;
1391         }
1392
1393         return EXT_MAX_BLOCKS;
1394 }
1395
1396 /*
1397  * ext4_ext_next_leaf_block:
1398  * returns first allocated block from next leaf or EXT_MAX_BLOCKS
1399  */
1400 static ext4_lblk_t ext4_ext_next_leaf_block(struct ext4_ext_path *path)
1401 {
1402         int depth;
1403
1404         BUG_ON(path == NULL);
1405         depth = path->p_depth;
1406
1407         /* zero-tree has no leaf blocks at all */
1408         if (depth == 0)
1409                 return EXT_MAX_BLOCKS;
1410
1411         /* go to index block */
1412         depth--;
1413
1414         while (depth >= 0) {
1415                 if (path[depth].p_idx !=
1416                                 EXT_LAST_INDEX(path[depth].p_hdr))
1417                         return (ext4_lblk_t)
1418                                 le32_to_cpu(path[depth].p_idx[1].ei_block);
1419                 depth--;
1420         }
1421
1422         return EXT_MAX_BLOCKS;
1423 }
1424
1425 /*
1426  * ext4_ext_correct_indexes:
1427  * if leaf gets modified and modified extent is first in the leaf,
1428  * then we have to correct all indexes above.
1429  * TODO: do we need to correct tree in all cases?
1430  */
1431 static int ext4_ext_correct_indexes(handle_t *handle, struct inode *inode,
1432                                 struct ext4_ext_path *path)
1433 {
1434         struct ext4_extent_header *eh;
1435         int depth = ext_depth(inode);
1436         struct ext4_extent *ex;
1437         __le32 border;
1438         int k, err = 0;
1439
1440         eh = path[depth].p_hdr;
1441         ex = path[depth].p_ext;
1442
1443         if (unlikely(ex == NULL || eh == NULL)) {
1444                 EXT4_ERROR_INODE(inode,
1445                                  "ex %p == NULL or eh %p == NULL", ex, eh);
1446                 return -EIO;
1447         }
1448
1449         if (depth == 0) {
1450                 /* there is no tree at all */
1451                 return 0;
1452         }
1453
1454         if (ex != EXT_FIRST_EXTENT(eh)) {
1455                 /* we correct tree if first leaf got modified only */
1456                 return 0;
1457         }
1458
1459         /*
1460          * TODO: we need correction if border is smaller than current one
1461          */
1462         k = depth - 1;
1463         border = path[depth].p_ext->ee_block;
1464         err = ext4_ext_get_access(handle, inode, path + k);
1465         if (err)
1466                 return err;
1467         path[k].p_idx->ei_block = border;
1468         err = ext4_ext_dirty(handle, inode, path + k);
1469         if (err)
1470                 return err;
1471
1472         while (k--) {
1473                 /* change all left-side indexes */
1474                 if (path[k+1].p_idx != EXT_FIRST_INDEX(path[k+1].p_hdr))
1475                         break;
1476                 err = ext4_ext_get_access(handle, inode, path + k);
1477                 if (err)
1478                         break;
1479                 path[k].p_idx->ei_block = border;
1480                 err = ext4_ext_dirty(handle, inode, path + k);
1481                 if (err)
1482                         break;
1483         }
1484
1485         return err;
1486 }
1487
1488 int
1489 ext4_can_extents_be_merged(struct inode *inode, struct ext4_extent *ex1,
1490                                 struct ext4_extent *ex2)
1491 {
1492         unsigned short ext1_ee_len, ext2_ee_len, max_len;
1493
1494         /*
1495          * Make sure that either both extents are uninitialized, or
1496          * both are _not_.
1497          */
1498         if (ext4_ext_is_uninitialized(ex1) ^ ext4_ext_is_uninitialized(ex2))
1499                 return 0;
1500
1501         if (ext4_ext_is_uninitialized(ex1))
1502                 max_len = EXT_UNINIT_MAX_LEN;
1503         else
1504                 max_len = EXT_INIT_MAX_LEN;
1505
1506         ext1_ee_len = ext4_ext_get_actual_len(ex1);
1507         ext2_ee_len = ext4_ext_get_actual_len(ex2);
1508
1509         if (le32_to_cpu(ex1->ee_block) + ext1_ee_len !=
1510                         le32_to_cpu(ex2->ee_block))
1511                 return 0;
1512
1513         /*
1514          * To allow future support for preallocated extents to be added
1515          * as an RO_COMPAT feature, refuse to merge to extents if
1516          * this can result in the top bit of ee_len being set.
1517          */
1518         if (ext1_ee_len + ext2_ee_len > max_len)
1519                 return 0;
1520 #ifdef AGGRESSIVE_TEST
1521         if (ext1_ee_len >= 4)
1522                 return 0;
1523 #endif
1524
1525         if (ext4_ext_pblock(ex1) + ext1_ee_len == ext4_ext_pblock(ex2))
1526                 return 1;
1527         return 0;
1528 }
1529
1530 /*
1531  * This function tries to merge the "ex" extent to the next extent in the tree.
1532  * It always tries to merge towards right. If you want to merge towards
1533  * left, pass "ex - 1" as argument instead of "ex".
1534  * Returns 0 if the extents (ex and ex+1) were _not_ merged and returns
1535  * 1 if they got merged.
1536  */
1537 static int ext4_ext_try_to_merge_right(struct inode *inode,
1538                                  struct ext4_ext_path *path,
1539                                  struct ext4_extent *ex)
1540 {
1541         struct ext4_extent_header *eh;
1542         unsigned int depth, len;
1543         int merge_done = 0;
1544         int uninitialized = 0;
1545
1546         depth = ext_depth(inode);
1547         BUG_ON(path[depth].p_hdr == NULL);
1548         eh = path[depth].p_hdr;
1549
1550         while (ex < EXT_LAST_EXTENT(eh)) {
1551                 if (!ext4_can_extents_be_merged(inode, ex, ex + 1))
1552                         break;
1553                 /* merge with next extent! */
1554                 if (ext4_ext_is_uninitialized(ex))
1555                         uninitialized = 1;
1556                 ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
1557                                 + ext4_ext_get_actual_len(ex + 1));
1558                 if (uninitialized)
1559                         ext4_ext_mark_uninitialized(ex);
1560
1561                 if (ex + 1 < EXT_LAST_EXTENT(eh)) {
1562                         len = (EXT_LAST_EXTENT(eh) - ex - 1)
1563                                 * sizeof(struct ext4_extent);
1564                         memmove(ex + 1, ex + 2, len);
1565                 }
1566                 le16_add_cpu(&eh->eh_entries, -1);
1567                 merge_done = 1;
1568                 WARN_ON(eh->eh_entries == 0);
1569                 if (!eh->eh_entries)
1570                         EXT4_ERROR_INODE(inode, "eh->eh_entries = 0!");
1571         }
1572
1573         return merge_done;
1574 }
1575
1576 /*
1577  * This function tries to merge the @ex extent to neighbours in the tree.
1578  * return 1 if merge left else 0.
1579  */
1580 static int ext4_ext_try_to_merge(struct inode *inode,
1581                                   struct ext4_ext_path *path,
1582                                   struct ext4_extent *ex) {
1583         struct ext4_extent_header *eh;
1584         unsigned int depth;
1585         int merge_done = 0;
1586         int ret = 0;
1587
1588         depth = ext_depth(inode);
1589         BUG_ON(path[depth].p_hdr == NULL);
1590         eh = path[depth].p_hdr;
1591
1592         if (ex > EXT_FIRST_EXTENT(eh))
1593                 merge_done = ext4_ext_try_to_merge_right(inode, path, ex - 1);
1594
1595         if (!merge_done)
1596                 ret = ext4_ext_try_to_merge_right(inode, path, ex);
1597
1598         return ret;
1599 }
1600
1601 /*
1602  * check if a portion of the "newext" extent overlaps with an
1603  * existing extent.
1604  *
1605  * If there is an overlap discovered, it updates the length of the newext
1606  * such that there will be no overlap, and then returns 1.
1607  * If there is no overlap found, it returns 0.
1608  */
1609 static unsigned int ext4_ext_check_overlap(struct ext4_sb_info *sbi,
1610                                            struct inode *inode,
1611                                            struct ext4_extent *newext,
1612                                            struct ext4_ext_path *path)
1613 {
1614         ext4_lblk_t b1, b2;
1615         unsigned int depth, len1;
1616         unsigned int ret = 0;
1617
1618         b1 = le32_to_cpu(newext->ee_block);
1619         len1 = ext4_ext_get_actual_len(newext);
1620         depth = ext_depth(inode);
1621         if (!path[depth].p_ext)
1622                 goto out;
1623         b2 = le32_to_cpu(path[depth].p_ext->ee_block);
1624         b2 &= ~(sbi->s_cluster_ratio - 1);
1625
1626         /*
1627          * get the next allocated block if the extent in the path
1628          * is before the requested block(s)
1629          */
1630         if (b2 < b1) {
1631                 b2 = ext4_ext_next_allocated_block(path);
1632                 if (b2 == EXT_MAX_BLOCKS)
1633                         goto out;
1634                 b2 &= ~(sbi->s_cluster_ratio - 1);
1635         }
1636
1637         /* check for wrap through zero on extent logical start block*/
1638         if (b1 + len1 < b1) {
1639                 len1 = EXT_MAX_BLOCKS - b1;
1640                 newext->ee_len = cpu_to_le16(len1);
1641                 ret = 1;
1642         }
1643
1644         /* check for overlap */
1645         if (b1 + len1 > b2) {
1646                 newext->ee_len = cpu_to_le16(b2 - b1);
1647                 ret = 1;
1648         }
1649 out:
1650         return ret;
1651 }
1652
1653 /*
1654  * ext4_ext_insert_extent:
1655  * tries to merge requsted extent into the existing extent or
1656  * inserts requested extent as new one into the tree,
1657  * creating new leaf in the no-space case.
1658  */
1659 int ext4_ext_insert_extent(handle_t *handle, struct inode *inode,
1660                                 struct ext4_ext_path *path,
1661                                 struct ext4_extent *newext, int flag)
1662 {
1663         struct ext4_extent_header *eh;
1664         struct ext4_extent *ex, *fex;
1665         struct ext4_extent *nearex; /* nearest extent */
1666         struct ext4_ext_path *npath = NULL;
1667         int depth, len, err;
1668         ext4_lblk_t next;
1669         unsigned uninitialized = 0;
1670         int flags = 0;
1671
1672         if (unlikely(ext4_ext_get_actual_len(newext) == 0)) {
1673                 EXT4_ERROR_INODE(inode, "ext4_ext_get_actual_len(newext) == 0");
1674                 return -EIO;
1675         }
1676         depth = ext_depth(inode);
1677         ex = path[depth].p_ext;
1678         if (unlikely(path[depth].p_hdr == NULL)) {
1679                 EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
1680                 return -EIO;
1681         }
1682
1683         /* try to insert block into found extent and return */
1684         if (ex && !(flag & EXT4_GET_BLOCKS_PRE_IO)
1685                 && ext4_can_extents_be_merged(inode, ex, newext)) {
1686                 ext_debug("append [%d]%d block to %u:[%d]%d (from %llu)\n",
1687                           ext4_ext_is_uninitialized(newext),
1688                           ext4_ext_get_actual_len(newext),
1689                           le32_to_cpu(ex->ee_block),
1690                           ext4_ext_is_uninitialized(ex),
1691                           ext4_ext_get_actual_len(ex),
1692                           ext4_ext_pblock(ex));
1693                 err = ext4_ext_get_access(handle, inode, path + depth);
1694                 if (err)
1695                         return err;
1696
1697                 /*
1698                  * ext4_can_extents_be_merged should have checked that either
1699                  * both extents are uninitialized, or both aren't. Thus we
1700                  * need to check only one of them here.
1701                  */
1702                 if (ext4_ext_is_uninitialized(ex))
1703                         uninitialized = 1;
1704                 ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
1705                                         + ext4_ext_get_actual_len(newext));
1706                 if (uninitialized)
1707                         ext4_ext_mark_uninitialized(ex);
1708                 eh = path[depth].p_hdr;
1709                 nearex = ex;
1710                 goto merge;
1711         }
1712
1713         depth = ext_depth(inode);
1714         eh = path[depth].p_hdr;
1715         if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max))
1716                 goto has_space;
1717
1718         /* probably next leaf has space for us? */
1719         fex = EXT_LAST_EXTENT(eh);
1720         next = EXT_MAX_BLOCKS;
1721         if (le32_to_cpu(newext->ee_block) > le32_to_cpu(fex->ee_block))
1722                 next = ext4_ext_next_leaf_block(path);
1723         if (next != EXT_MAX_BLOCKS) {
1724                 ext_debug("next leaf block - %u\n", next);
1725                 BUG_ON(npath != NULL);
1726                 npath = ext4_ext_find_extent(inode, next, NULL);
1727                 if (IS_ERR(npath))
1728                         return PTR_ERR(npath);
1729                 BUG_ON(npath->p_depth != path->p_depth);
1730                 eh = npath[depth].p_hdr;
1731                 if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max)) {
1732                         ext_debug("next leaf isn't full(%d)\n",
1733                                   le16_to_cpu(eh->eh_entries));
1734                         path = npath;
1735                         goto has_space;
1736                 }
1737                 ext_debug("next leaf has no free space(%d,%d)\n",
1738                           le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
1739         }
1740
1741         /*
1742          * There is no free space in the found leaf.
1743          * We're gonna add a new leaf in the tree.
1744          */
1745         if (flag & EXT4_GET_BLOCKS_PUNCH_OUT_EXT)
1746                 flags = EXT4_MB_USE_ROOT_BLOCKS;
1747         err = ext4_ext_create_new_leaf(handle, inode, flags, path, newext);
1748         if (err)
1749                 goto cleanup;
1750         depth = ext_depth(inode);
1751         eh = path[depth].p_hdr;
1752
1753 has_space:
1754         nearex = path[depth].p_ext;
1755
1756         err = ext4_ext_get_access(handle, inode, path + depth);
1757         if (err)
1758                 goto cleanup;
1759
1760         if (!nearex) {
1761                 /* there is no extent in this leaf, create first one */
1762                 ext_debug("first extent in the leaf: %u:%llu:[%d]%d\n",
1763                                 le32_to_cpu(newext->ee_block),
1764                                 ext4_ext_pblock(newext),
1765                                 ext4_ext_is_uninitialized(newext),
1766                                 ext4_ext_get_actual_len(newext));
1767                 nearex = EXT_FIRST_EXTENT(eh);
1768         } else {
1769                 if (le32_to_cpu(newext->ee_block)
1770                            > le32_to_cpu(nearex->ee_block)) {
1771                         /* Insert after */
1772                         ext_debug("insert %u:%llu:[%d]%d before: "
1773                                         "nearest %p\n",
1774                                         le32_to_cpu(newext->ee_block),
1775                                         ext4_ext_pblock(newext),
1776                                         ext4_ext_is_uninitialized(newext),
1777                                         ext4_ext_get_actual_len(newext),
1778                                         nearex);
1779                         nearex++;
1780                 } else {
1781                         /* Insert before */
1782                         BUG_ON(newext->ee_block == nearex->ee_block);
1783                         ext_debug("insert %u:%llu:[%d]%d after: "
1784                                         "nearest %p\n",
1785                                         le32_to_cpu(newext->ee_block),
1786                                         ext4_ext_pblock(newext),
1787                                         ext4_ext_is_uninitialized(newext),
1788                                         ext4_ext_get_actual_len(newext),
1789                                         nearex);
1790                 }
1791                 len = EXT_LAST_EXTENT(eh) - nearex + 1;
1792                 if (len > 0) {
1793                         ext_debug("insert %u:%llu:[%d]%d: "
1794                                         "move %d extents from 0x%p to 0x%p\n",
1795                                         le32_to_cpu(newext->ee_block),
1796                                         ext4_ext_pblock(newext),
1797                                         ext4_ext_is_uninitialized(newext),
1798                                         ext4_ext_get_actual_len(newext),
1799                                         len, nearex, nearex + 1);
1800                         memmove(nearex + 1, nearex,
1801                                 len * sizeof(struct ext4_extent));
1802                 }
1803         }
1804
1805         le16_add_cpu(&eh->eh_entries, 1);
1806         path[depth].p_ext = nearex;
1807         nearex->ee_block = newext->ee_block;
1808         ext4_ext_store_pblock(nearex, ext4_ext_pblock(newext));
1809         nearex->ee_len = newext->ee_len;
1810
1811 merge:
1812         /* try to merge extents to the right */
1813         if (!(flag & EXT4_GET_BLOCKS_PRE_IO))
1814                 ext4_ext_try_to_merge(inode, path, nearex);
1815
1816         /* try to merge extents to the left */
1817
1818         /* time to correct all indexes above */
1819         err = ext4_ext_correct_indexes(handle, inode, path);
1820         if (err)
1821                 goto cleanup;
1822
1823         err = ext4_ext_dirty(handle, inode, path + depth);
1824
1825 cleanup:
1826         if (npath) {
1827                 ext4_ext_drop_refs(npath);
1828                 kfree(npath);
1829         }
1830         ext4_ext_invalidate_cache(inode);
1831         return err;
1832 }
1833
1834 static int ext4_ext_walk_space(struct inode *inode, ext4_lblk_t block,
1835                                ext4_lblk_t num, ext_prepare_callback func,
1836                                void *cbdata)
1837 {
1838         struct ext4_ext_path *path = NULL;
1839         struct ext4_ext_cache cbex;
1840         struct ext4_extent *ex;
1841         ext4_lblk_t next, start = 0, end = 0;
1842         ext4_lblk_t last = block + num;
1843         int depth, exists, err = 0;
1844
1845         BUG_ON(func == NULL);
1846         BUG_ON(inode == NULL);
1847
1848         while (block < last && block != EXT_MAX_BLOCKS) {
1849                 num = last - block;
1850                 /* find extent for this block */
1851                 down_read(&EXT4_I(inode)->i_data_sem);
1852                 path = ext4_ext_find_extent(inode, block, path);
1853                 up_read(&EXT4_I(inode)->i_data_sem);
1854                 if (IS_ERR(path)) {
1855                         err = PTR_ERR(path);
1856                         path = NULL;
1857                         break;
1858                 }
1859
1860                 depth = ext_depth(inode);
1861                 if (unlikely(path[depth].p_hdr == NULL)) {
1862                         EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
1863                         err = -EIO;
1864                         break;
1865                 }
1866                 ex = path[depth].p_ext;
1867                 next = ext4_ext_next_allocated_block(path);
1868
1869                 exists = 0;
1870                 if (!ex) {
1871                         /* there is no extent yet, so try to allocate
1872                          * all requested space */
1873                         start = block;
1874                         end = block + num;
1875                 } else if (le32_to_cpu(ex->ee_block) > block) {
1876                         /* need to allocate space before found extent */
1877                         start = block;
1878                         end = le32_to_cpu(ex->ee_block);
1879                         if (block + num < end)
1880                                 end = block + num;
1881                 } else if (block >= le32_to_cpu(ex->ee_block)
1882                                         + ext4_ext_get_actual_len(ex)) {
1883                         /* need to allocate space after found extent */
1884                         start = block;
1885                         end = block + num;
1886                         if (end >= next)
1887                                 end = next;
1888                 } else if (block >= le32_to_cpu(ex->ee_block)) {
1889                         /*
1890                          * some part of requested space is covered
1891                          * by found extent
1892                          */
1893                         start = block;
1894                         end = le32_to_cpu(ex->ee_block)
1895                                 + ext4_ext_get_actual_len(ex);
1896                         if (block + num < end)
1897                                 end = block + num;
1898                         exists = 1;
1899                 } else {
1900                         BUG();
1901                 }
1902                 BUG_ON(end <= start);
1903
1904                 if (!exists) {
1905                         cbex.ec_block = start;
1906                         cbex.ec_len = end - start;
1907                         cbex.ec_start = 0;
1908                 } else {
1909                         cbex.ec_block = le32_to_cpu(ex->ee_block);
1910                         cbex.ec_len = ext4_ext_get_actual_len(ex);
1911                         cbex.ec_start = ext4_ext_pblock(ex);
1912                 }
1913
1914                 if (unlikely(cbex.ec_len == 0)) {
1915                         EXT4_ERROR_INODE(inode, "cbex.ec_len == 0");
1916                         err = -EIO;
1917                         break;
1918                 }
1919                 err = func(inode, next, &cbex, ex, cbdata);
1920                 ext4_ext_drop_refs(path);
1921
1922                 if (err < 0)
1923                         break;
1924
1925                 if (err == EXT_REPEAT)
1926                         continue;
1927                 else if (err == EXT_BREAK) {
1928                         err = 0;
1929                         break;
1930                 }
1931
1932                 if (ext_depth(inode) != depth) {
1933                         /* depth was changed. we have to realloc path */
1934                         kfree(path);
1935                         path = NULL;
1936                 }
1937
1938                 block = cbex.ec_block + cbex.ec_len;
1939         }
1940
1941         if (path) {
1942                 ext4_ext_drop_refs(path);
1943                 kfree(path);
1944         }
1945
1946         return err;
1947 }
1948
1949 static void
1950 ext4_ext_put_in_cache(struct inode *inode, ext4_lblk_t block,
1951                         __u32 len, ext4_fsblk_t start)
1952 {
1953         struct ext4_ext_cache *cex;
1954         BUG_ON(len == 0);
1955         spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1956         trace_ext4_ext_put_in_cache(inode, block, len, start);
1957         cex = &EXT4_I(inode)->i_cached_extent;
1958         cex->ec_block = block;
1959         cex->ec_len = len;
1960         cex->ec_start = start;
1961         spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1962 }
1963
1964 /*
1965  * ext4_ext_put_gap_in_cache:
1966  * calculate boundaries of the gap that the requested block fits into
1967  * and cache this gap
1968  */
1969 static void
1970 ext4_ext_put_gap_in_cache(struct inode *inode, struct ext4_ext_path *path,
1971                                 ext4_lblk_t block)
1972 {
1973         int depth = ext_depth(inode);
1974         unsigned long len;
1975         ext4_lblk_t lblock;
1976         struct ext4_extent *ex;
1977
1978         ex = path[depth].p_ext;
1979         if (ex == NULL) {
1980                 /* there is no extent yet, so gap is [0;-] */
1981                 lblock = 0;
1982                 len = EXT_MAX_BLOCKS;
1983                 ext_debug("cache gap(whole file):");
1984         } else if (block < le32_to_cpu(ex->ee_block)) {
1985                 lblock = block;
1986                 len = le32_to_cpu(ex->ee_block) - block;
1987                 ext_debug("cache gap(before): %u [%u:%u]",
1988                                 block,
1989                                 le32_to_cpu(ex->ee_block),
1990                                  ext4_ext_get_actual_len(ex));
1991         } else if (block >= le32_to_cpu(ex->ee_block)
1992                         + ext4_ext_get_actual_len(ex)) {
1993                 ext4_lblk_t next;
1994                 lblock = le32_to_cpu(ex->ee_block)
1995                         + ext4_ext_get_actual_len(ex);
1996
1997                 next = ext4_ext_next_allocated_block(path);
1998                 ext_debug("cache gap(after): [%u:%u] %u",
1999                                 le32_to_cpu(ex->ee_block),
2000                                 ext4_ext_get_actual_len(ex),
2001                                 block);
2002                 BUG_ON(next == lblock);
2003                 len = next - lblock;
2004         } else {
2005                 lblock = len = 0;
2006                 BUG();
2007         }
2008
2009         ext_debug(" -> %u:%lu\n", lblock, len);
2010         ext4_ext_put_in_cache(inode, lblock, len, 0);
2011 }
2012
2013 /*
2014  * ext4_ext_check_cache()
2015  * Checks to see if the given block is in the cache.
2016  * If it is, the cached extent is stored in the given
2017  * cache extent pointer.  If the cached extent is a hole,
2018  * this routine should be used instead of
2019  * ext4_ext_in_cache if the calling function needs to
2020  * know the size of the hole.
2021  *
2022  * @inode: The files inode
2023  * @block: The block to look for in the cache
2024  * @ex:    Pointer where the cached extent will be stored
2025  *         if it contains block
2026  *
2027  * Return 0 if cache is invalid; 1 if the cache is valid
2028  */
2029 static int ext4_ext_check_cache(struct inode *inode, ext4_lblk_t block,
2030         struct ext4_ext_cache *ex){
2031         struct ext4_ext_cache *cex;
2032         struct ext4_sb_info *sbi;
2033         int ret = 0;
2034
2035         /*
2036          * We borrow i_block_reservation_lock to protect i_cached_extent
2037          */
2038         spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
2039         cex = &EXT4_I(inode)->i_cached_extent;
2040         sbi = EXT4_SB(inode->i_sb);
2041
2042         /* has cache valid data? */
2043         if (cex->ec_len == 0)
2044                 goto errout;
2045
2046         if (in_range(block, cex->ec_block, cex->ec_len)) {
2047                 memcpy(ex, cex, sizeof(struct ext4_ext_cache));
2048                 ext_debug("%u cached by %u:%u:%llu\n",
2049                                 block,
2050                                 cex->ec_block, cex->ec_len, cex->ec_start);
2051                 ret = 1;
2052         }
2053 errout:
2054         if (!ret)
2055                 sbi->extent_cache_misses++;
2056         else
2057                 sbi->extent_cache_hits++;
2058         trace_ext4_ext_in_cache(inode, block, ret);
2059         spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
2060         return ret;
2061 }
2062
2063 /*
2064  * ext4_ext_in_cache()
2065  * Checks to see if the given block is in the cache.
2066  * If it is, the cached extent is stored in the given
2067  * extent pointer.
2068  *
2069  * @inode: The files inode
2070  * @block: The block to look for in the cache
2071  * @ex:    Pointer where the cached extent will be stored
2072  *         if it contains block
2073  *
2074  * Return 0 if cache is invalid; 1 if the cache is valid
2075  */
2076 static int
2077 ext4_ext_in_cache(struct inode *inode, ext4_lblk_t block,
2078                         struct ext4_extent *ex)
2079 {
2080         struct ext4_ext_cache cex;
2081         int ret = 0;
2082
2083         if (ext4_ext_check_cache(inode, block, &cex)) {
2084                 ex->ee_block = cpu_to_le32(cex.ec_block);
2085                 ext4_ext_store_pblock(ex, cex.ec_start);
2086                 ex->ee_len = cpu_to_le16(cex.ec_len);
2087                 ret = 1;
2088         }
2089
2090         return ret;
2091 }
2092
2093
2094 /*
2095  * ext4_ext_rm_idx:
2096  * removes index from the index block.
2097  */
2098 static int ext4_ext_rm_idx(handle_t *handle, struct inode *inode,
2099                         struct ext4_ext_path *path)
2100 {
2101         int err;
2102         ext4_fsblk_t leaf;
2103
2104         /* free index block */
2105         path--;
2106         leaf = ext4_idx_pblock(path->p_idx);
2107         if (unlikely(path->p_hdr->eh_entries == 0)) {
2108                 EXT4_ERROR_INODE(inode, "path->p_hdr->eh_entries == 0");
2109                 return -EIO;
2110         }
2111         err = ext4_ext_get_access(handle, inode, path);
2112         if (err)
2113                 return err;
2114
2115         if (path->p_idx != EXT_LAST_INDEX(path->p_hdr)) {
2116                 int len = EXT_LAST_INDEX(path->p_hdr) - path->p_idx;
2117                 len *= sizeof(struct ext4_extent_idx);
2118                 memmove(path->p_idx, path->p_idx + 1, len);
2119         }
2120
2121         le16_add_cpu(&path->p_hdr->eh_entries, -1);
2122         err = ext4_ext_dirty(handle, inode, path);
2123         if (err)
2124                 return err;
2125         ext_debug("index is empty, remove it, free block %llu\n", leaf);
2126         trace_ext4_ext_rm_idx(inode, leaf);
2127
2128         ext4_free_blocks(handle, inode, NULL, leaf, 1,
2129                          EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET);
2130         return err;
2131 }
2132
2133 /*
2134  * ext4_ext_calc_credits_for_single_extent:
2135  * This routine returns max. credits that needed to insert an extent
2136  * to the extent tree.
2137  * When pass the actual path, the caller should calculate credits
2138  * under i_data_sem.
2139  */
2140 int ext4_ext_calc_credits_for_single_extent(struct inode *inode, int nrblocks,
2141                                                 struct ext4_ext_path *path)
2142 {
2143         if (path) {
2144                 int depth = ext_depth(inode);
2145                 int ret = 0;
2146
2147                 /* probably there is space in leaf? */
2148                 if (le16_to_cpu(path[depth].p_hdr->eh_entries)
2149                                 < le16_to_cpu(path[depth].p_hdr->eh_max)) {
2150
2151                         /*
2152                          *  There are some space in the leaf tree, no
2153                          *  need to account for leaf block credit
2154                          *
2155                          *  bitmaps and block group descriptor blocks
2156                          *  and other metadata blocks still need to be
2157                          *  accounted.
2158                          */
2159                         /* 1 bitmap, 1 block group descriptor */
2160                         ret = 2 + EXT4_META_TRANS_BLOCKS(inode->i_sb);
2161                         return ret;
2162                 }
2163         }
2164
2165         return ext4_chunk_trans_blocks(inode, nrblocks);
2166 }
2167
2168 /*
2169  * How many index/leaf blocks need to change/allocate to modify nrblocks?
2170  *
2171  * if nrblocks are fit in a single extent (chunk flag is 1), then
2172  * in the worse case, each tree level index/leaf need to be changed
2173  * if the tree split due to insert a new extent, then the old tree
2174  * index/leaf need to be updated too
2175  *
2176  * If the nrblocks are discontiguous, they could cause
2177  * the whole tree split more than once, but this is really rare.
2178  */
2179 int ext4_ext_index_trans_blocks(struct inode *inode, int nrblocks, int chunk)
2180 {
2181         int index;
2182         int depth = ext_depth(inode);
2183
2184         if (chunk)
2185                 index = depth * 2;
2186         else
2187                 index = depth * 3;
2188
2189         return index;
2190 }
2191
2192 static int ext4_remove_blocks(handle_t *handle, struct inode *inode,
2193                               struct ext4_extent *ex,
2194                               ext4_fsblk_t *partial_cluster,
2195                               ext4_lblk_t from, ext4_lblk_t to)
2196 {
2197         struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2198         unsigned short ee_len =  ext4_ext_get_actual_len(ex);
2199         ext4_fsblk_t pblk;
2200         int flags = EXT4_FREE_BLOCKS_FORGET;
2201
2202         if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode))
2203                 flags |= EXT4_FREE_BLOCKS_METADATA;
2204         /*
2205          * For bigalloc file systems, we never free a partial cluster
2206          * at the beginning of the extent.  Instead, we make a note
2207          * that we tried freeing the cluster, and check to see if we
2208          * need to free it on a subsequent call to ext4_remove_blocks,
2209          * or at the end of the ext4_truncate() operation.
2210          */
2211         flags |= EXT4_FREE_BLOCKS_NOFREE_FIRST_CLUSTER;
2212
2213         trace_ext4_remove_blocks(inode, ex, from, to, *partial_cluster);
2214         /*
2215          * If we have a partial cluster, and it's different from the
2216          * cluster of the last block, we need to explicitly free the
2217          * partial cluster here.
2218          */
2219         pblk = ext4_ext_pblock(ex) + ee_len - 1;
2220         if (*partial_cluster && (EXT4_B2C(sbi, pblk) != *partial_cluster)) {
2221                 ext4_free_blocks(handle, inode, NULL,
2222                                  EXT4_C2B(sbi, *partial_cluster),
2223                                  sbi->s_cluster_ratio, flags);
2224                 *partial_cluster = 0;
2225         }
2226
2227 #ifdef EXTENTS_STATS
2228         {
2229                 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2230                 spin_lock(&sbi->s_ext_stats_lock);
2231                 sbi->s_ext_blocks += ee_len;
2232                 sbi->s_ext_extents++;
2233                 if (ee_len < sbi->s_ext_min)
2234                         sbi->s_ext_min = ee_len;
2235                 if (ee_len > sbi->s_ext_max)
2236                         sbi->s_ext_max = ee_len;
2237                 if (ext_depth(inode) > sbi->s_depth_max)
2238                         sbi->s_depth_max = ext_depth(inode);
2239                 spin_unlock(&sbi->s_ext_stats_lock);
2240         }
2241 #endif
2242         if (from >= le32_to_cpu(ex->ee_block)
2243             && to == le32_to_cpu(ex->ee_block) + ee_len - 1) {
2244                 /* tail removal */
2245                 ext4_lblk_t num;
2246
2247                 num = le32_to_cpu(ex->ee_block) + ee_len - from;
2248                 pblk = ext4_ext_pblock(ex) + ee_len - num;
2249                 ext_debug("free last %u blocks starting %llu\n", num, pblk);
2250                 ext4_free_blocks(handle, inode, NULL, pblk, num, flags);
2251                 /*
2252                  * If the block range to be freed didn't start at the
2253                  * beginning of a cluster, and we removed the entire
2254                  * extent, save the partial cluster here, since we
2255                  * might need to delete if we determine that the
2256                  * truncate operation has removed all of the blocks in
2257                  * the cluster.
2258                  */
2259                 if (pblk & (sbi->s_cluster_ratio - 1) &&
2260                     (ee_len == num))
2261                         *partial_cluster = EXT4_B2C(sbi, pblk);
2262                 else
2263                         *partial_cluster = 0;
2264         } else if (from == le32_to_cpu(ex->ee_block)
2265                    && to <= le32_to_cpu(ex->ee_block) + ee_len - 1) {
2266                 /* head removal */
2267                 ext4_lblk_t num;
2268                 ext4_fsblk_t start;
2269
2270                 num = to - from;
2271                 start = ext4_ext_pblock(ex);
2272
2273                 ext_debug("free first %u blocks starting %llu\n", num, start);
2274                 ext4_free_blocks(handle, inode, NULL, start, num, flags);
2275
2276         } else {
2277                 printk(KERN_INFO "strange request: removal(2) "
2278                                 "%u-%u from %u:%u\n",
2279                                 from, to, le32_to_cpu(ex->ee_block), ee_len);
2280         }
2281         return 0;
2282 }
2283
2284
2285 /*
2286  * ext4_ext_rm_leaf() Removes the extents associated with the
2287  * blocks appearing between "start" and "end", and splits the extents
2288  * if "start" and "end" appear in the same extent
2289  *
2290  * @handle: The journal handle
2291  * @inode:  The files inode
2292  * @path:   The path to the leaf
2293  * @start:  The first block to remove
2294  * @end:   The last block to remove
2295  */
2296 static int
2297 ext4_ext_rm_leaf(handle_t *handle, struct inode *inode,
2298                  struct ext4_ext_path *path, ext4_fsblk_t *partial_cluster,
2299                  ext4_lblk_t start, ext4_lblk_t end)
2300 {
2301         struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2302         int err = 0, correct_index = 0;
2303         int depth = ext_depth(inode), credits;
2304         struct ext4_extent_header *eh;
2305         ext4_lblk_t a, b;
2306         unsigned num;
2307         ext4_lblk_t ex_ee_block;
2308         unsigned short ex_ee_len;
2309         unsigned uninitialized = 0;
2310         struct ext4_extent *ex;
2311
2312         /* the header must be checked already in ext4_ext_remove_space() */
2313         ext_debug("truncate since %u in leaf\n", start);
2314         if (!path[depth].p_hdr)
2315                 path[depth].p_hdr = ext_block_hdr(path[depth].p_bh);
2316         eh = path[depth].p_hdr;
2317         if (unlikely(path[depth].p_hdr == NULL)) {
2318                 EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
2319                 return -EIO;
2320         }
2321         /* find where to start removing */
2322         ex = EXT_LAST_EXTENT(eh);
2323
2324         ex_ee_block = le32_to_cpu(ex->ee_block);
2325         ex_ee_len = ext4_ext_get_actual_len(ex);
2326
2327         trace_ext4_ext_rm_leaf(inode, start, ex, *partial_cluster);
2328
2329         while (ex >= EXT_FIRST_EXTENT(eh) &&
2330                         ex_ee_block + ex_ee_len > start) {
2331
2332                 if (ext4_ext_is_uninitialized(ex))
2333                         uninitialized = 1;
2334                 else
2335                         uninitialized = 0;
2336
2337                 ext_debug("remove ext %u:[%d]%d\n", ex_ee_block,
2338                          uninitialized, ex_ee_len);
2339                 path[depth].p_ext = ex;
2340
2341                 a = ex_ee_block > start ? ex_ee_block : start;
2342                 b = ex_ee_block+ex_ee_len - 1 < end ?
2343                         ex_ee_block+ex_ee_len - 1 : end;
2344
2345                 ext_debug("  border %u:%u\n", a, b);
2346
2347                 /* If this extent is beyond the end of the hole, skip it */
2348                 if (end <= ex_ee_block) {
2349                         ex--;
2350                         ex_ee_block = le32_to_cpu(ex->ee_block);
2351                         ex_ee_len = ext4_ext_get_actual_len(ex);
2352                         continue;
2353                 } else if (b != ex_ee_block + ex_ee_len - 1) {
2354                         EXT4_ERROR_INODE(inode,"  bad truncate %u:%u\n",
2355                                          start, end);
2356                         err = -EIO;
2357                         goto out;
2358                 } else if (a != ex_ee_block) {
2359                         /* remove tail of the extent */
2360                         num = a - ex_ee_block;
2361                 } else {
2362                         /* remove whole extent: excellent! */
2363                         num = 0;
2364                 }
2365                 /*
2366                  * 3 for leaf, sb, and inode plus 2 (bmap and group
2367                  * descriptor) for each block group; assume two block
2368                  * groups plus ex_ee_len/blocks_per_block_group for
2369                  * the worst case
2370                  */
2371                 credits = 7 + 2*(ex_ee_len/EXT4_BLOCKS_PER_GROUP(inode->i_sb));
2372                 if (ex == EXT_FIRST_EXTENT(eh)) {
2373                         correct_index = 1;
2374                         credits += (ext_depth(inode)) + 1;
2375                 }
2376                 credits += EXT4_MAXQUOTAS_TRANS_BLOCKS(inode->i_sb);
2377
2378                 err = ext4_ext_truncate_extend_restart(handle, inode, credits);
2379                 if (err)
2380                         goto out;
2381
2382                 err = ext4_ext_get_access(handle, inode, path + depth);
2383                 if (err)
2384                         goto out;
2385
2386                 err = ext4_remove_blocks(handle, inode, ex, partial_cluster,
2387                                          a, b);
2388                 if (err)
2389                         goto out;
2390
2391                 if (num == 0)
2392                         /* this extent is removed; mark slot entirely unused */
2393                         ext4_ext_store_pblock(ex, 0);
2394
2395                 ex->ee_len = cpu_to_le16(num);
2396                 /*
2397                  * Do not mark uninitialized if all the blocks in the
2398                  * extent have been removed.
2399                  */
2400                 if (uninitialized && num)
2401                         ext4_ext_mark_uninitialized(ex);
2402                 /*
2403                  * If the extent was completely released,
2404                  * we need to remove it from the leaf
2405                  */
2406                 if (num == 0) {
2407                         if (end != EXT_MAX_BLOCKS - 1) {
2408                                 /*
2409                                  * For hole punching, we need to scoot all the
2410                                  * extents up when an extent is removed so that
2411                                  * we dont have blank extents in the middle
2412                                  */
2413                                 memmove(ex, ex+1, (EXT_LAST_EXTENT(eh) - ex) *
2414                                         sizeof(struct ext4_extent));
2415
2416                                 /* Now get rid of the one at the end */
2417                                 memset(EXT_LAST_EXTENT(eh), 0,
2418                                         sizeof(struct ext4_extent));
2419                         }
2420                         le16_add_cpu(&eh->eh_entries, -1);
2421                 } else
2422                         *partial_cluster = 0;
2423
2424                 err = ext4_ext_dirty(handle, inode, path + depth);
2425                 if (err)
2426                         goto out;
2427
2428                 ext_debug("new extent: %u:%u:%llu\n", ex_ee_block, num,
2429                                 ext4_ext_pblock(ex));
2430                 ex--;
2431                 ex_ee_block = le32_to_cpu(ex->ee_block);
2432                 ex_ee_len = ext4_ext_get_actual_len(ex);
2433         }
2434
2435         if (correct_index && eh->eh_entries)
2436                 err = ext4_ext_correct_indexes(handle, inode, path);
2437
2438         /*
2439          * If there is still a entry in the leaf node, check to see if
2440          * it references the partial cluster.  This is the only place
2441          * where it could; if it doesn't, we can free the cluster.
2442          */
2443         if (*partial_cluster && ex >= EXT_FIRST_EXTENT(eh) &&
2444             (EXT4_B2C(sbi, ext4_ext_pblock(ex) + ex_ee_len - 1) !=
2445              *partial_cluster)) {
2446                 int flags = EXT4_FREE_BLOCKS_FORGET;
2447
2448                 if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode))
2449                         flags |= EXT4_FREE_BLOCKS_METADATA;
2450
2451                 ext4_free_blocks(handle, inode, NULL,
2452                                  EXT4_C2B(sbi, *partial_cluster),
2453                                  sbi->s_cluster_ratio, flags);
2454                 *partial_cluster = 0;
2455         }
2456
2457         /* if this leaf is free, then we should
2458          * remove it from index block above */
2459         if (err == 0 && eh->eh_entries == 0 && path[depth].p_bh != NULL)
2460                 err = ext4_ext_rm_idx(handle, inode, path + depth);
2461
2462 out:
2463         return err;
2464 }
2465
2466 /*
2467  * ext4_ext_more_to_rm:
2468  * returns 1 if current index has to be freed (even partial)
2469  */
2470 static int
2471 ext4_ext_more_to_rm(struct ext4_ext_path *path)
2472 {
2473         BUG_ON(path->p_idx == NULL);
2474
2475         if (path->p_idx < EXT_FIRST_INDEX(path->p_hdr))
2476                 return 0;
2477
2478         /*
2479          * if truncate on deeper level happened, it wasn't partial,
2480          * so we have to consider current index for truncation
2481          */
2482         if (le16_to_cpu(path->p_hdr->eh_entries) == path->p_block)
2483                 return 0;
2484         return 1;
2485 }
2486
2487 static int ext4_ext_remove_space(struct inode *inode, ext4_lblk_t start)
2488 {
2489         struct super_block *sb = inode->i_sb;
2490         int depth = ext_depth(inode);
2491         struct ext4_ext_path *path;
2492         ext4_fsblk_t partial_cluster = 0;
2493         handle_t *handle;
2494         int i, err;
2495
2496         ext_debug("truncate since %u\n", start);
2497
2498         /* probably first extent we're gonna free will be last in block */
2499         handle = ext4_journal_start(inode, depth + 1);
2500         if (IS_ERR(handle))
2501                 return PTR_ERR(handle);
2502
2503 again:
2504         ext4_ext_invalidate_cache(inode);
2505
2506         trace_ext4_ext_remove_space(inode, start, depth);
2507
2508         /*
2509          * We start scanning from right side, freeing all the blocks
2510          * after i_size and walking into the tree depth-wise.
2511          */
2512         depth = ext_depth(inode);
2513         path = kzalloc(sizeof(struct ext4_ext_path) * (depth + 1), GFP_NOFS);
2514         if (path == NULL) {
2515                 ext4_journal_stop(handle);
2516                 return -ENOMEM;
2517         }
2518         path[0].p_depth = depth;
2519         path[0].p_hdr = ext_inode_hdr(inode);
2520         if (ext4_ext_check(inode, path[0].p_hdr, depth)) {
2521                 err = -EIO;
2522                 goto out;
2523         }
2524         i = err = 0;
2525
2526         while (i >= 0 && err == 0) {
2527                 if (i == depth) {
2528                         /* this is leaf block */
2529                         err = ext4_ext_rm_leaf(handle, inode, path,
2530                                                &partial_cluster, start,
2531                                                EXT_MAX_BLOCKS - 1);
2532                         /* root level has p_bh == NULL, brelse() eats this */
2533                         brelse(path[i].p_bh);
2534                         path[i].p_bh = NULL;
2535                         i--;
2536                         continue;
2537                 }
2538
2539                 /* this is index block */
2540                 if (!path[i].p_hdr) {
2541                         ext_debug("initialize header\n");
2542                         path[i].p_hdr = ext_block_hdr(path[i].p_bh);
2543                 }
2544
2545                 if (!path[i].p_idx) {
2546                         /* this level hasn't been touched yet */
2547                         path[i].p_idx = EXT_LAST_INDEX(path[i].p_hdr);
2548                         path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries)+1;
2549                         ext_debug("init index ptr: hdr 0x%p, num %d\n",
2550                                   path[i].p_hdr,
2551                                   le16_to_cpu(path[i].p_hdr->eh_entries));
2552                 } else {
2553                         /* we were already here, see at next index */
2554                         path[i].p_idx--;
2555                 }
2556
2557                 ext_debug("level %d - index, first 0x%p, cur 0x%p\n",
2558                                 i, EXT_FIRST_INDEX(path[i].p_hdr),
2559                                 path[i].p_idx);
2560                 if (ext4_ext_more_to_rm(path + i)) {
2561                         struct buffer_head *bh;
2562                         /* go to the next level */
2563                         ext_debug("move to level %d (block %llu)\n",
2564                                   i + 1, ext4_idx_pblock(path[i].p_idx));
2565                         memset(path + i + 1, 0, sizeof(*path));
2566                         bh = sb_bread(sb, ext4_idx_pblock(path[i].p_idx));
2567                         if (!bh) {
2568                                 /* should we reset i_size? */
2569                                 err = -EIO;
2570                                 break;
2571                         }
2572                         if (WARN_ON(i + 1 > depth)) {
2573                                 err = -EIO;
2574                                 break;
2575                         }
2576                         if (ext4_ext_check(inode, ext_block_hdr(bh),
2577                                                         depth - i - 1)) {
2578                                 err = -EIO;
2579                                 break;
2580                         }
2581                         path[i + 1].p_bh = bh;
2582
2583                         /* save actual number of indexes since this
2584                          * number is changed at the next iteration */
2585                         path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries);
2586                         i++;
2587                 } else {
2588                         /* we finished processing this index, go up */
2589                         if (path[i].p_hdr->eh_entries == 0 && i > 0) {
2590                                 /* index is empty, remove it;
2591                                  * handle must be already prepared by the
2592                                  * truncatei_leaf() */
2593                                 err = ext4_ext_rm_idx(handle, inode, path + i);
2594                         }
2595                         /* root level has p_bh == NULL, brelse() eats this */
2596                         brelse(path[i].p_bh);
2597                         path[i].p_bh = NULL;
2598                         i--;
2599                         ext_debug("return to level %d\n", i);
2600                 }
2601         }
2602
2603         trace_ext4_ext_remove_space_done(inode, start, depth, partial_cluster,
2604                         path->p_hdr->eh_entries);
2605
2606         /* If we still have something in the partial cluster and we have removed
2607          * even the first extent, then we should free the blocks in the partial
2608          * cluster as well. */
2609         if (partial_cluster && path->p_hdr->eh_entries == 0) {
2610                 int flags = EXT4_FREE_BLOCKS_FORGET;
2611
2612                 if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode))
2613                         flags |= EXT4_FREE_BLOCKS_METADATA;
2614
2615                 ext4_free_blocks(handle, inode, NULL,
2616                                  EXT4_C2B(EXT4_SB(sb), partial_cluster),
2617                                  EXT4_SB(sb)->s_cluster_ratio, flags);
2618                 partial_cluster = 0;
2619         }
2620
2621         /* TODO: flexible tree reduction should be here */
2622         if (path->p_hdr->eh_entries == 0) {
2623                 /*
2624                  * truncate to zero freed all the tree,
2625                  * so we need to correct eh_depth
2626                  */
2627                 err = ext4_ext_get_access(handle, inode, path);
2628                 if (err == 0) {
2629                         ext_inode_hdr(inode)->eh_depth = 0;
2630                         ext_inode_hdr(inode)->eh_max =
2631                                 cpu_to_le16(ext4_ext_space_root(inode, 0));
2632                         err = ext4_ext_dirty(handle, inode, path);
2633                 }
2634         }
2635 out:
2636         ext4_ext_drop_refs(path);
2637         kfree(path);
2638         if (err == -EAGAIN)
2639                 goto again;
2640         ext4_journal_stop(handle);
2641
2642         return err;
2643 }
2644
2645 /*
2646  * called at mount time
2647  */
2648 void ext4_ext_init(struct super_block *sb)
2649 {
2650         /*
2651          * possible initialization would be here
2652          */
2653
2654         if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_EXTENTS)) {
2655 #if defined(AGGRESSIVE_TEST) || defined(CHECK_BINSEARCH) || defined(EXTENTS_STATS)
2656                 printk(KERN_INFO "EXT4-fs: file extents enabled");
2657 #ifdef AGGRESSIVE_TEST
2658                 printk(", aggressive tests");
2659 #endif
2660 #ifdef CHECK_BINSEARCH
2661                 printk(", check binsearch");
2662 #endif
2663 #ifdef EXTENTS_STATS
2664                 printk(", stats");
2665 #endif
2666                 printk("\n");
2667 #endif
2668 #ifdef EXTENTS_STATS
2669                 spin_lock_init(&EXT4_SB(sb)->s_ext_stats_lock);
2670                 EXT4_SB(sb)->s_ext_min = 1 << 30;
2671                 EXT4_SB(sb)->s_ext_max = 0;
2672 #endif
2673         }
2674 }
2675
2676 /*
2677  * called at umount time
2678  */
2679 void ext4_ext_release(struct super_block *sb)
2680 {
2681         if (!EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_EXTENTS))
2682                 return;
2683
2684 #ifdef EXTENTS_STATS
2685         if (EXT4_SB(sb)->s_ext_blocks && EXT4_SB(sb)->s_ext_extents) {
2686                 struct ext4_sb_info *sbi = EXT4_SB(sb);
2687                 printk(KERN_ERR "EXT4-fs: %lu blocks in %lu extents (%lu ave)\n",
2688                         sbi->s_ext_blocks, sbi->s_ext_extents,
2689                         sbi->s_ext_blocks / sbi->s_ext_extents);
2690                 printk(KERN_ERR "EXT4-fs: extents: %lu min, %lu max, max depth %lu\n",
2691                         sbi->s_ext_min, sbi->s_ext_max, sbi->s_depth_max);
2692         }
2693 #endif
2694 }
2695
2696 /* FIXME!! we need to try to merge to left or right after zero-out  */
2697 static int ext4_ext_zeroout(struct inode *inode, struct ext4_extent *ex)
2698 {
2699         ext4_fsblk_t ee_pblock;
2700         unsigned int ee_len;
2701         int ret;
2702
2703         ee_len    = ext4_ext_get_actual_len(ex);
2704         ee_pblock = ext4_ext_pblock(ex);
2705
2706         ret = sb_issue_zeroout(inode->i_sb, ee_pblock, ee_len, GFP_NOFS);
2707         if (ret > 0)
2708                 ret = 0;
2709
2710         return ret;
2711 }
2712
2713 /*
2714  * used by extent splitting.
2715  */
2716 #define EXT4_EXT_MAY_ZEROOUT    0x1  /* safe to zeroout if split fails \
2717                                         due to ENOSPC */
2718 #define EXT4_EXT_MARK_UNINIT1   0x2  /* mark first half uninitialized */
2719 #define EXT4_EXT_MARK_UNINIT2   0x4  /* mark second half uninitialized */
2720
2721 /*
2722  * ext4_split_extent_at() splits an extent at given block.
2723  *
2724  * @handle: the journal handle
2725  * @inode: the file inode
2726  * @path: the path to the extent
2727  * @split: the logical block where the extent is splitted.
2728  * @split_flags: indicates if the extent could be zeroout if split fails, and
2729  *               the states(init or uninit) of new extents.
2730  * @flags: flags used to insert new extent to extent tree.
2731  *
2732  *
2733  * Splits extent [a, b] into two extents [a, @split) and [@split, b], states
2734  * of which are deterimined by split_flag.
2735  *
2736  * There are two cases:
2737  *  a> the extent are splitted into two extent.
2738  *  b> split is not needed, and just mark the extent.
2739  *
2740  * return 0 on success.
2741  */
2742 static int ext4_split_extent_at(handle_t *handle,
2743                              struct inode *inode,
2744                              struct ext4_ext_path *path,
2745                              ext4_lblk_t split,
2746                              int split_flag,
2747                              int flags)
2748 {
2749         ext4_fsblk_t newblock;
2750         ext4_lblk_t ee_block;
2751         struct ext4_extent *ex, newex, orig_ex;
2752         struct ext4_extent *ex2 = NULL;
2753         unsigned int ee_len, depth;
2754         int err = 0;
2755
2756         ext_debug("ext4_split_extents_at: inode %lu, logical"
2757                 "block %llu\n", inode->i_ino, (unsigned long long)split);
2758
2759         ext4_ext_show_leaf(inode, path);
2760
2761         depth = ext_depth(inode);
2762         ex = path[depth].p_ext;
2763         ee_block = le32_to_cpu(ex->ee_block);
2764         ee_len = ext4_ext_get_actual_len(ex);
2765         newblock = split - ee_block + ext4_ext_pblock(ex);
2766
2767         BUG_ON(split < ee_block || split >= (ee_block + ee_len));
2768
2769         err = ext4_ext_get_access(handle, inode, path + depth);
2770         if (err)
2771                 goto out;
2772
2773         if (split == ee_block) {
2774                 /*
2775                  * case b: block @split is the block that the extent begins with
2776                  * then we just change the state of the extent, and splitting
2777                  * is not needed.
2778                  */
2779                 if (split_flag & EXT4_EXT_MARK_UNINIT2)
2780                         ext4_ext_mark_uninitialized(ex);
2781                 else
2782                         ext4_ext_mark_initialized(ex);
2783
2784                 if (!(flags & EXT4_GET_BLOCKS_PRE_IO))
2785                         ext4_ext_try_to_merge(inode, path, ex);
2786
2787                 err = ext4_ext_dirty(handle, inode, path + depth);
2788                 goto out;
2789         }
2790
2791         /* case a */
2792         memcpy(&orig_ex, ex, sizeof(orig_ex));
2793         ex->ee_len = cpu_to_le16(split - ee_block);
2794         if (split_flag & EXT4_EXT_MARK_UNINIT1)
2795                 ext4_ext_mark_uninitialized(ex);
2796
2797         /*
2798          * path may lead to new leaf, not to original leaf any more
2799          * after ext4_ext_insert_extent() returns,
2800          */
2801         err = ext4_ext_dirty(handle, inode, path + depth);
2802         if (err)
2803                 goto fix_extent_len;
2804
2805         ex2 = &newex;
2806         ex2->ee_block = cpu_to_le32(split);
2807         ex2->ee_len   = cpu_to_le16(ee_len - (split - ee_block));
2808         ext4_ext_store_pblock(ex2, newblock);
2809         if (split_flag & EXT4_EXT_MARK_UNINIT2)
2810                 ext4_ext_mark_uninitialized(ex2);
2811
2812         err = ext4_ext_insert_extent(handle, inode, path, &newex, flags);
2813         if (err == -ENOSPC && (EXT4_EXT_MAY_ZEROOUT & split_flag)) {
2814                 err = ext4_ext_zeroout(inode, &orig_ex);
2815                 if (err)
2816                         goto fix_extent_len;
2817                 /* update the extent length and mark as initialized */
2818                 ex->ee_len = cpu_to_le32(ee_len);
2819                 ext4_ext_try_to_merge(inode, path, ex);
2820                 err = ext4_ext_dirty(handle, inode, path + depth);
2821                 goto out;
2822         } else if (err)
2823                 goto fix_extent_len;
2824
2825 out:
2826         ext4_ext_show_leaf(inode, path);
2827         return err;
2828
2829 fix_extent_len:
2830         ex->ee_len = orig_ex.ee_len;
2831         ext4_ext_dirty(handle, inode, path + depth);
2832         return err;
2833 }
2834
2835 /*
2836  * ext4_split_extents() splits an extent and mark extent which is covered
2837  * by @map as split_flags indicates
2838  *
2839  * It may result in splitting the extent into multiple extents (upto three)
2840  * There are three possibilities:
2841  *   a> There is no split required
2842  *   b> Splits in two extents: Split is happening at either end of the extent
2843  *   c> Splits in three extents: Somone is splitting in middle of the extent
2844  *
2845  */
2846 static int ext4_split_extent(handle_t *handle,
2847                               struct inode *inode,
2848                               struct ext4_ext_path *path,
2849                               struct ext4_map_blocks *map,
2850                               int split_flag,
2851                               int flags)
2852 {
2853         ext4_lblk_t ee_block;
2854         struct ext4_extent *ex;
2855         unsigned int ee_len, depth;
2856         int err = 0;
2857         int uninitialized;
2858         int split_flag1, flags1;
2859
2860         depth = ext_depth(inode);
2861         ex = path[depth].p_ext;
2862         ee_block = le32_to_cpu(ex->ee_block);
2863         ee_len = ext4_ext_get_actual_len(ex);
2864         uninitialized = ext4_ext_is_uninitialized(ex);
2865
2866         if (map->m_lblk + map->m_len < ee_block + ee_len) {
2867                 split_flag1 = split_flag & EXT4_EXT_MAY_ZEROOUT ?
2868                               EXT4_EXT_MAY_ZEROOUT : 0;
2869                 flags1 = flags | EXT4_GET_BLOCKS_PRE_IO;
2870                 if (uninitialized)
2871                         split_flag1 |= EXT4_EXT_MARK_UNINIT1 |
2872                                        EXT4_EXT_MARK_UNINIT2;
2873                 err = ext4_split_extent_at(handle, inode, path,
2874                                 map->m_lblk + map->m_len, split_flag1, flags1);
2875                 if (err)
2876                         goto out;
2877         }
2878
2879         ext4_ext_drop_refs(path);
2880         path = ext4_ext_find_extent(inode, map->m_lblk, path);
2881         if (IS_ERR(path))
2882                 return PTR_ERR(path);
2883
2884         if (map->m_lblk >= ee_block) {
2885                 split_flag1 = split_flag & EXT4_EXT_MAY_ZEROOUT ?
2886                               EXT4_EXT_MAY_ZEROOUT : 0;
2887                 if (uninitialized)
2888                         split_flag1 |= EXT4_EXT_MARK_UNINIT1;
2889                 if (split_flag & EXT4_EXT_MARK_UNINIT2)
2890                         split_flag1 |= EXT4_EXT_MARK_UNINIT2;
2891                 err = ext4_split_extent_at(handle, inode, path,
2892                                 map->m_lblk, split_flag1, flags);
2893                 if (err)
2894                         goto out;
2895         }
2896
2897         ext4_ext_show_leaf(inode, path);
2898 out:
2899         return err ? err : map->m_len;
2900 }
2901
2902 #define EXT4_EXT_ZERO_LEN 7
2903 /*
2904  * This function is called by ext4_ext_map_blocks() if someone tries to write
2905  * to an uninitialized extent. It may result in splitting the uninitialized
2906  * extent into multiple extents (up to three - one initialized and two
2907  * uninitialized).
2908  * There are three possibilities:
2909  *   a> There is no split required: Entire extent should be initialized
2910  *   b> Splits in two extents: Write is happening at either end of the extent
2911  *   c> Splits in three extents: Somone is writing in middle of the extent
2912  *
2913  * Pre-conditions:
2914  *  - The extent pointed to by 'path' is uninitialized.
2915  *  - The extent pointed to by 'path' contains a superset
2916  *    of the logical span [map->m_lblk, map->m_lblk + map->m_len).
2917  *
2918  * Post-conditions on success:
2919  *  - the returned value is the number of blocks beyond map->l_lblk
2920  *    that are allocated and initialized.
2921  *    It is guaranteed to be >= map->m_len.
2922  */
2923 static int ext4_ext_convert_to_initialized(handle_t *handle,
2924                                            struct inode *inode,
2925                                            struct ext4_map_blocks *map,
2926                                            struct ext4_ext_path *path)
2927 {
2928         struct ext4_extent_header *eh;
2929         struct ext4_map_blocks split_map;
2930         struct ext4_extent zero_ex;
2931         struct ext4_extent *ex;
2932         ext4_lblk_t ee_block, eof_block;
2933         unsigned int ee_len, depth;
2934         int allocated;
2935         int err = 0;
2936         int split_flag = 0;
2937
2938         ext_debug("ext4_ext_convert_to_initialized: inode %lu, logical"
2939                 "block %llu, max_blocks %u\n", inode->i_ino,
2940                 (unsigned long long)map->m_lblk, map->m_len);
2941
2942         eof_block = (inode->i_size + inode->i_sb->s_blocksize - 1) >>
2943                 inode->i_sb->s_blocksize_bits;
2944         if (eof_block < map->m_lblk + map->m_len)
2945                 eof_block = map->m_lblk + map->m_len;
2946
2947         depth = ext_depth(inode);
2948         eh = path[depth].p_hdr;
2949         ex = path[depth].p_ext;
2950         ee_block = le32_to_cpu(ex->ee_block);
2951         ee_len = ext4_ext_get_actual_len(ex);
2952         allocated = ee_len - (map->m_lblk - ee_block);
2953
2954         trace_ext4_ext_convert_to_initialized_enter(inode, map, ex);
2955
2956         /* Pre-conditions */
2957         BUG_ON(!ext4_ext_is_uninitialized(ex));
2958         BUG_ON(!in_range(map->m_lblk, ee_block, ee_len));
2959
2960         /*
2961          * Attempt to transfer newly initialized blocks from the currently
2962          * uninitialized extent to its left neighbor. This is much cheaper
2963          * than an insertion followed by a merge as those involve costly
2964          * memmove() calls. This is the common case in steady state for
2965          * workloads doing fallocate(FALLOC_FL_KEEP_SIZE) followed by append
2966          * writes.
2967          *
2968          * Limitations of the current logic:
2969          *  - L1: we only deal with writes at the start of the extent.
2970          *    The approach could be extended to writes at the end
2971          *    of the extent but this scenario was deemed less common.
2972          *  - L2: we do not deal with writes covering the whole extent.
2973          *    This would require removing the extent if the transfer
2974          *    is possible.
2975          *  - L3: we only attempt to merge with an extent stored in the
2976          *    same extent tree node.
2977          */
2978         if ((map->m_lblk == ee_block) &&        /*L1*/
2979                 (map->m_len < ee_len) &&        /*L2*/
2980                 (ex > EXT_FIRST_EXTENT(eh))) {  /*L3*/
2981                 struct ext4_extent *prev_ex;
2982                 ext4_lblk_t prev_lblk;
2983                 ext4_fsblk_t prev_pblk, ee_pblk;
2984                 unsigned int prev_len, write_len;
2985
2986                 prev_ex = ex - 1;
2987                 prev_lblk = le32_to_cpu(prev_ex->ee_block);
2988                 prev_len = ext4_ext_get_actual_len(prev_ex);
2989                 prev_pblk = ext4_ext_pblock(prev_ex);
2990                 ee_pblk = ext4_ext_pblock(ex);
2991                 write_len = map->m_len;
2992
2993                 /*
2994                  * A transfer of blocks from 'ex' to 'prev_ex' is allowed
2995                  * upon those conditions:
2996                  * - C1: prev_ex is initialized,
2997                  * - C2: prev_ex is logically abutting ex,
2998                  * - C3: prev_ex is physically abutting ex,
2999                  * - C4: prev_ex can receive the additional blocks without
3000                  *   overflowing the (initialized) length limit.
3001                  */
3002                 if ((!ext4_ext_is_uninitialized(prev_ex)) &&            /*C1*/
3003                         ((prev_lblk + prev_len) == ee_block) &&         /*C2*/
3004                         ((prev_pblk + prev_len) == ee_pblk) &&          /*C3*/
3005                         (prev_len < (EXT_INIT_MAX_LEN - write_len))) {  /*C4*/
3006                         err = ext4_ext_get_access(handle, inode, path + depth);
3007                         if (err)
3008                                 goto out;
3009
3010                         trace_ext4_ext_convert_to_initialized_fastpath(inode,
3011                                 map, ex, prev_ex);
3012
3013                         /* Shift the start of ex by 'write_len' blocks */
3014                         ex->ee_block = cpu_to_le32(ee_block + write_len);
3015                         ext4_ext_store_pblock(ex, ee_pblk + write_len);
3016                         ex->ee_len = cpu_to_le16(ee_len - write_len);
3017                         ext4_ext_mark_uninitialized(ex); /* Restore the flag */
3018
3019                         /* Extend prev_ex by 'write_len' blocks */
3020                         prev_ex->ee_len = cpu_to_le16(prev_len + write_len);
3021
3022                         /* Mark the block containing both extents as dirty */
3023                         ext4_ext_dirty(handle, inode, path + depth);
3024
3025                         /* Update path to point to the right extent */
3026                         path[depth].p_ext = prev_ex;
3027
3028                         /* Result: number of initialized blocks past m_lblk */
3029                         allocated = write_len;
3030                         goto out;
3031                 }
3032         }
3033
3034         WARN_ON(map->m_lblk < ee_block);
3035         /*
3036          * It is safe to convert extent to initialized via explicit
3037          * zeroout only if extent is fully insde i_size or new_size.
3038          */
3039         split_flag |= ee_block + ee_len <= eof_block ? EXT4_EXT_MAY_ZEROOUT : 0;
3040
3041         /* If extent has less than 2*EXT4_EXT_ZERO_LEN zerout directly */
3042         if (ee_len <= 2*EXT4_EXT_ZERO_LEN &&
3043             (EXT4_EXT_MAY_ZEROOUT & split_flag)) {
3044                 err = ext4_ext_zeroout(inode, ex);
3045                 if (err)
3046                         goto out;
3047
3048                 err = ext4_ext_get_access(handle, inode, path + depth);
3049                 if (err)
3050                         goto out;
3051                 ext4_ext_mark_initialized(ex);
3052                 ext4_ext_try_to_merge(inode, path, ex);
3053                 err = ext4_ext_dirty(handle, inode, path + depth);
3054                 goto out;
3055         }
3056
3057         /*
3058          * four cases:
3059          * 1. split the extent into three extents.
3060          * 2. split the extent into two extents, zeroout the first half.
3061          * 3. split the extent into two extents, zeroout the second half.
3062          * 4. split the extent into two extents with out zeroout.
3063          */
3064         split_map.m_lblk = map->m_lblk;
3065         split_map.m_len = map->m_len;
3066
3067         if (allocated > map->m_len) {
3068                 if (allocated <= EXT4_EXT_ZERO_LEN &&
3069                     (EXT4_EXT_MAY_ZEROOUT & split_flag)) {
3070                         /* case 3 */
3071                         zero_ex.ee_block =
3072                                          cpu_to_le32(map->m_lblk);
3073                         zero_ex.ee_len = cpu_to_le16(allocated);
3074                         ext4_ext_store_pblock(&zero_ex,
3075                                 ext4_ext_pblock(ex) + map->m_lblk - ee_block);
3076                         err = ext4_ext_zeroout(inode, &zero_ex);
3077                         if (err)
3078                                 goto out;
3079                         split_map.m_lblk = map->m_lblk;
3080                         split_map.m_len = allocated;
3081                 } else if ((map->m_lblk - ee_block + map->m_len <
3082                            EXT4_EXT_ZERO_LEN) &&
3083                            (EXT4_EXT_MAY_ZEROOUT & split_flag)) {
3084                         /* case 2 */
3085                         if (map->m_lblk != ee_block) {
3086                                 zero_ex.ee_block = ex->ee_block;
3087                                 zero_ex.ee_len = cpu_to_le16(map->m_lblk -
3088                                                         ee_block);
3089                                 ext4_ext_store_pblock(&zero_ex,
3090                                                       ext4_ext_pblock(ex));
3091                                 err = ext4_ext_zeroout(inode, &zero_ex);
3092                                 if (err)
3093                                         goto out;
3094                         }
3095
3096                         split_map.m_lblk = ee_block;
3097                         split_map.m_len = map->m_lblk - ee_block + map->m_len;
3098                         allocated = map->m_len;
3099                 }
3100         }
3101
3102         allocated = ext4_split_extent(handle, inode, path,
3103                                        &split_map, split_flag, 0);
3104         if (allocated < 0)
3105                 err = allocated;
3106
3107 out:
3108         return err ? err : allocated;
3109 }
3110
3111 /*
3112  * This function is called by ext4_ext_map_blocks() from
3113  * ext4_get_blocks_dio_write() when DIO to write
3114  * to an uninitialized extent.
3115  *
3116  * Writing to an uninitialized extent may result in splitting the uninitialized
3117  * extent into multiple /initialized uninitialized extents (up to three)
3118  * There are three possibilities:
3119  *   a> There is no split required: Entire extent should be uninitialized
3120  *   b> Splits in two extents: Write is happening at either end of the extent
3121  *   c> Splits in three extents: Somone is writing in middle of the extent
3122  *
3123  * One of more index blocks maybe needed if the extent tree grow after
3124  * the uninitialized extent split. To prevent ENOSPC occur at the IO
3125  * complete, we need to split the uninitialized extent before DIO submit
3126  * the IO. The uninitialized extent called at this time will be split
3127  * into three uninitialized extent(at most). After IO complete, the part
3128  * being filled will be convert to initialized by the end_io callback function
3129  * via ext4_convert_unwritten_extents().
3130  *
3131  * Returns the size of uninitialized extent to be written on success.
3132  */
3133 static int ext4_split_unwritten_extents(handle_t *handle,
3134                                         struct inode *inode,
3135                                         struct ext4_map_blocks *map,
3136                                         struct ext4_ext_path *path,
3137                                         int flags)
3138 {
3139         ext4_lblk_t eof_block;
3140         ext4_lblk_t ee_block;
3141         struct ext4_extent *ex;
3142         unsigned int ee_len;
3143         int split_flag = 0, depth;
3144
3145         ext_debug("ext4_split_unwritten_extents: inode %lu, logical"
3146                 "block %llu, max_blocks %u\n", inode->i_ino,
3147                 (unsigned long long)map->m_lblk, map->m_len);
3148
3149         eof_block = (inode->i_size + inode->i_sb->s_blocksize - 1) >>
3150                 inode->i_sb->s_blocksize_bits;
3151         if (eof_block < map->m_lblk + map->m_len)
3152                 eof_block = map->m_lblk + map->m_len;
3153         /*
3154          * It is safe to convert extent to initialized via explicit
3155          * zeroout only if extent is fully insde i_size or new_size.
3156          */
3157         depth = ext_depth(inode);
3158         ex = path[depth].p_ext;
3159         ee_block = le32_to_cpu(ex->ee_block);
3160         ee_len = ext4_ext_get_actual_len(ex);
3161
3162         split_flag |= ee_block + ee_len <= eof_block ? EXT4_EXT_MAY_ZEROOUT : 0;
3163         split_flag |= EXT4_EXT_MARK_UNINIT2;
3164
3165         flags |= EXT4_GET_BLOCKS_PRE_IO;
3166         return ext4_split_extent(handle, inode, path, map, split_flag, flags);
3167 }
3168
3169 static int ext4_convert_unwritten_extents_endio(handle_t *handle,
3170                                               struct inode *inode,
3171                                               struct ext4_ext_path *path)
3172 {
3173         struct ext4_extent *ex;
3174         int depth;
3175         int err = 0;
3176
3177         depth = ext_depth(inode);
3178         ex = path[depth].p_ext;
3179
3180         ext_debug("ext4_convert_unwritten_extents_endio: inode %lu, logical"
3181                 "block %llu, max_blocks %u\n", inode->i_ino,
3182                 (unsigned long long)le32_to_cpu(ex->ee_block),
3183                 ext4_ext_get_actual_len(ex));
3184
3185         err = ext4_ext_get_access(handle, inode, path + depth);
3186         if (err)
3187                 goto out;
3188         /* first mark the extent as initialized */
3189         ext4_ext_mark_initialized(ex);
3190
3191         /* note: ext4_ext_correct_indexes() isn't needed here because
3192          * borders are not changed
3193          */
3194         ext4_ext_try_to_merge(inode, path, ex);
3195
3196         /* Mark modified extent as dirty */
3197         err = ext4_ext_dirty(handle, inode, path + depth);
3198 out:
3199         ext4_ext_show_leaf(inode, path);
3200         return err;
3201 }
3202
3203 static void unmap_underlying_metadata_blocks(struct block_device *bdev,
3204                         sector_t block, int count)
3205 {
3206         int i;
3207         for (i = 0; i < count; i++)
3208                 unmap_underlying_metadata(bdev, block + i);
3209 }
3210
3211 /*
3212  * Handle EOFBLOCKS_FL flag, clearing it if necessary
3213  */
3214 static int check_eofblocks_fl(handle_t *handle, struct inode *inode,
3215                               ext4_lblk_t lblk,
3216                               struct ext4_ext_path *path,
3217                               unsigned int len)
3218 {
3219         int i, depth;
3220         struct ext4_extent_header *eh;
3221         struct ext4_extent *last_ex;
3222
3223         if (!ext4_test_inode_flag(inode, EXT4_INODE_EOFBLOCKS))
3224                 return 0;
3225
3226         depth = ext_depth(inode);
3227         eh = path[depth].p_hdr;
3228
3229         if (unlikely(!eh->eh_entries)) {
3230                 EXT4_ERROR_INODE(inode, "eh->eh_entries == 0 and "
3231                                  "EOFBLOCKS_FL set");
3232                 return -EIO;
3233         }
3234         last_ex = EXT_LAST_EXTENT(eh);
3235         /*
3236          * We should clear the EOFBLOCKS_FL flag if we are writing the
3237          * last block in the last extent in the file.  We test this by
3238          * first checking to see if the caller to
3239          * ext4_ext_get_blocks() was interested in the last block (or
3240          * a block beyond the last block) in the current extent.  If
3241          * this turns out to be false, we can bail out from this
3242          * function immediately.
3243          */
3244         if (lblk + len < le32_to_cpu(last_ex->ee_block) +
3245             ext4_ext_get_actual_len(last_ex))
3246                 return 0;
3247         /*
3248          * If the caller does appear to be planning to write at or
3249          * beyond the end of the current extent, we then test to see
3250          * if the current extent is the last extent in the file, by
3251          * checking to make sure it was reached via the rightmost node
3252          * at each level of the tree.
3253          */
3254         for (i = depth-1; i >= 0; i--)
3255                 if (path[i].p_idx != EXT_LAST_INDEX(path[i].p_hdr))
3256                         return 0;
3257         ext4_clear_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
3258         return ext4_mark_inode_dirty(handle, inode);
3259 }
3260
3261 /**
3262  * ext4_find_delalloc_range: find delayed allocated block in the given range.
3263  *
3264  * Goes through the buffer heads in the range [lblk_start, lblk_end] and returns
3265  * whether there are any buffers marked for delayed allocation. It returns '1'
3266  * on the first delalloc'ed buffer head found. If no buffer head in the given
3267  * range is marked for delalloc, it returns 0.
3268  * lblk_start should always be <= lblk_end.
3269  * search_hint_reverse is to indicate that searching in reverse from lblk_end to
3270  * lblk_start might be more efficient (i.e., we will likely hit the delalloc'ed
3271  * block sooner). This is useful when blocks are truncated sequentially from
3272  * lblk_start towards lblk_end.
3273  */
3274 static int ext4_find_delalloc_range(struct inode *inode,
3275                                     ext4_lblk_t lblk_start,
3276                                     ext4_lblk_t lblk_end,
3277                                     int search_hint_reverse)
3278 {
3279         struct address_space *mapping = inode->i_mapping;
3280         struct buffer_head *head, *bh = NULL;
3281         struct page *page;
3282         ext4_lblk_t i, pg_lblk;
3283         pgoff_t index;
3284
3285         if (!test_opt(inode->i_sb, DELALLOC))
3286                 return 0;
3287
3288         /* reverse search wont work if fs block size is less than page size */
3289         if (inode->i_blkbits < PAGE_CACHE_SHIFT)
3290                 search_hint_reverse = 0;
3291
3292         if (search_hint_reverse)
3293                 i = lblk_end;
3294         else
3295                 i = lblk_start;
3296
3297         index = i >> (PAGE_CACHE_SHIFT - inode->i_blkbits);
3298
3299         while ((i >= lblk_start) && (i <= lblk_end)) {
3300                 page = find_get_page(mapping, index);
3301                 if (!page)
3302                         goto nextpage;
3303
3304                 if (!page_has_buffers(page))
3305                         goto nextpage;
3306
3307                 head = page_buffers(page);
3308                 if (!head)
3309                         goto nextpage;
3310
3311                 bh = head;
3312                 pg_lblk = index << (PAGE_CACHE_SHIFT -
3313                                                 inode->i_blkbits);
3314                 do {
3315                         if (unlikely(pg_lblk < lblk_start)) {
3316                                 /*
3317                                  * This is possible when fs block size is less
3318                                  * than page size and our cluster starts/ends in
3319                                  * middle of the page. So we need to skip the
3320                                  * initial few blocks till we reach the 'lblk'
3321                                  */
3322                                 pg_lblk++;
3323                                 continue;
3324                         }
3325
3326                         /* Check if the buffer is delayed allocated and that it
3327                          * is not yet mapped. (when da-buffers are mapped during
3328                          * their writeout, their da_mapped bit is set.)
3329                          */
3330                         if (buffer_delay(bh) && !buffer_da_mapped(bh)) {
3331                                 page_cache_release(page);
3332                                 trace_ext4_find_delalloc_range(inode,
3333                                                 lblk_start, lblk_end,
3334                                                 search_hint_reverse,
3335                                                 1, i);
3336                                 return 1;
3337                         }
3338                         if (search_hint_reverse)
3339                                 i--;
3340                         else
3341                                 i++;
3342                 } while ((i >= lblk_start) && (i <= lblk_end) &&
3343                                 ((bh = bh->b_this_page) != head));
3344 nextpage:
3345                 if (page)
3346                         page_cache_release(page);
3347                 /*
3348                  * Move to next page. 'i' will be the first lblk in the next
3349                  * page.
3350                  */
3351                 if (search_hint_reverse)
3352                         index--;
3353                 else
3354                         index++;
3355                 i = index << (PAGE_CACHE_SHIFT - inode->i_blkbits);
3356         }
3357
3358         trace_ext4_find_delalloc_range(inode, lblk_start, lblk_end,
3359                                         search_hint_reverse, 0, 0);
3360         return 0;
3361 }
3362
3363 int ext4_find_delalloc_cluster(struct inode *inode, ext4_lblk_t lblk,
3364                                int search_hint_reverse)
3365 {
3366         struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3367         ext4_lblk_t lblk_start, lblk_end;
3368         lblk_start = lblk & (~(sbi->s_cluster_ratio - 1));
3369         lblk_end = lblk_start + sbi->s_cluster_ratio - 1;
3370
3371         return ext4_find_delalloc_range(inode, lblk_start, lblk_end,
3372                                         search_hint_reverse);
3373 }
3374
3375 /**
3376  * Determines how many complete clusters (out of those specified by the 'map')
3377  * are under delalloc and were reserved quota for.
3378  * This function is called when we are writing out the blocks that were
3379  * originally written with their allocation delayed, but then the space was
3380  * allocated using fallocate() before the delayed allocation could be resolved.
3381  * The cases to look for are:
3382  * ('=' indicated delayed allocated blocks
3383  *  '-' indicates non-delayed allocated blocks)
3384  * (a) partial clusters towards beginning and/or end outside of allocated range
3385  *     are not delalloc'ed.
3386  *      Ex:
3387  *      |----c---=|====c====|====c====|===-c----|
3388  *               |++++++ allocated ++++++|
3389  *      ==> 4 complete clusters in above example
3390  *
3391  * (b) partial cluster (outside of allocated range) towards either end is
3392  *     marked for delayed allocation. In this case, we will exclude that
3393  *     cluster.
3394  *      Ex:
3395  *      |----====c========|========c========|
3396  *           |++++++ allocated ++++++|
3397  *      ==> 1 complete clusters in above example
3398  *
3399  *      Ex:
3400  *      |================c================|
3401  *            |++++++ allocated ++++++|
3402  *      ==> 0 complete clusters in above example
3403  *
3404  * The ext4_da_update_reserve_space will be called only if we
3405  * determine here that there were some "entire" clusters that span
3406  * this 'allocated' range.
3407  * In the non-bigalloc case, this function will just end up returning num_blks
3408  * without ever calling ext4_find_delalloc_range.
3409  */
3410 static unsigned int
3411 get_reserved_cluster_alloc(struct inode *inode, ext4_lblk_t lblk_start,
3412                            unsigned int num_blks)
3413 {
3414         struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3415         ext4_lblk_t alloc_cluster_start, alloc_cluster_end;
3416         ext4_lblk_t lblk_from, lblk_to, c_offset;
3417         unsigned int allocated_clusters = 0;
3418
3419         alloc_cluster_start = EXT4_B2C(sbi, lblk_start);
3420         alloc_cluster_end = EXT4_B2C(sbi, lblk_start + num_blks - 1);
3421
3422         /* max possible clusters for this allocation */
3423         allocated_clusters = alloc_cluster_end - alloc_cluster_start + 1;
3424
3425         trace_ext4_get_reserved_cluster_alloc(inode, lblk_start, num_blks);
3426
3427         /* Check towards left side */
3428         c_offset = lblk_start & (sbi->s_cluster_ratio - 1);
3429         if (c_offset) {
3430                 lblk_from = lblk_start & (~(sbi->s_cluster_ratio - 1));
3431                 lblk_to = lblk_from + c_offset - 1;
3432
3433                 if (ext4_find_delalloc_range(inode, lblk_from, lblk_to, 0))
3434                         allocated_clusters--;
3435         }
3436
3437         /* Now check towards right. */
3438         c_offset = (lblk_start + num_blks) & (sbi->s_cluster_ratio - 1);
3439         if (allocated_clusters && c_offset) {
3440                 lblk_from = lblk_start + num_blks;
3441                 lblk_to = lblk_from + (sbi->s_cluster_ratio - c_offset) - 1;
3442
3443                 if (ext4_find_delalloc_range(inode, lblk_from, lblk_to, 0))
3444                         allocated_clusters--;
3445         }
3446
3447         return allocated_clusters;
3448 }
3449
3450 static int
3451 ext4_ext_handle_uninitialized_extents(handle_t *handle, struct inode *inode,
3452                         struct ext4_map_blocks *map,
3453                         struct ext4_ext_path *path, int flags,
3454                         unsigned int allocated, ext4_fsblk_t newblock)
3455 {
3456         int ret = 0;
3457         int err = 0;
3458         ext4_io_end_t *io = EXT4_I(inode)->cur_aio_dio;
3459
3460         ext_debug("ext4_ext_handle_uninitialized_extents: inode %lu, logical "
3461                   "block %llu, max_blocks %u, flags %x, allocated %u\n",
3462                   inode->i_ino, (unsigned long long)map->m_lblk, map->m_len,
3463                   flags, allocated);
3464         ext4_ext_show_leaf(inode, path);
3465
3466         trace_ext4_ext_handle_uninitialized_extents(inode, map, allocated,
3467                                                     newblock);
3468
3469         /* get_block() before submit the IO, split the extent */
3470         if ((flags & EXT4_GET_BLOCKS_PRE_IO)) {
3471                 ret = ext4_split_unwritten_extents(handle, inode, map,
3472                                                    path, flags);
3473                 /*
3474                  * Flag the inode(non aio case) or end_io struct (aio case)
3475                  * that this IO needs to conversion to written when IO is
3476                  * completed
3477                  */
3478                 if (io)
3479                         ext4_set_io_unwritten_flag(inode, io);
3480                 else
3481                         ext4_set_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
3482                 if (ext4_should_dioread_nolock(inode))
3483                         map->m_flags |= EXT4_MAP_UNINIT;
3484                 goto out;
3485         }
3486         /* IO end_io complete, convert the filled extent to written */
3487         if ((flags & EXT4_GET_BLOCKS_CONVERT)) {
3488                 ret = ext4_convert_unwritten_extents_endio(handle, inode,
3489                                                         path);
3490                 if (ret >= 0) {
3491                         ext4_update_inode_fsync_trans(handle, inode, 1);
3492                         err = check_eofblocks_fl(handle, inode, map->m_lblk,
3493                                                  path, map->m_len);
3494                 } else
3495                         err = ret;
3496                 goto out2;
3497         }
3498         /* buffered IO case */
3499         /*
3500          * repeat fallocate creation request
3501          * we already have an unwritten extent
3502          */
3503         if (flags & EXT4_GET_BLOCKS_UNINIT_EXT)
3504                 goto map_out;
3505
3506         /* buffered READ or buffered write_begin() lookup */
3507         if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
3508                 /*
3509                  * We have blocks reserved already.  We
3510                  * return allocated blocks so that delalloc
3511                  * won't do block reservation for us.  But
3512                  * the buffer head will be unmapped so that
3513                  * a read from the block returns 0s.
3514                  */
3515                 map->m_flags |= EXT4_MAP_UNWRITTEN;
3516                 goto out1;
3517         }
3518
3519         /* buffered write, writepage time, convert*/
3520         ret = ext4_ext_convert_to_initialized(handle, inode, map, path);
3521         if (ret >= 0)
3522                 ext4_update_inode_fsync_trans(handle, inode, 1);
3523 out:
3524         if (ret <= 0) {
3525                 err = ret;
3526                 goto out2;
3527         } else
3528                 allocated = ret;
3529         map->m_flags |= EXT4_MAP_NEW;
3530         /*
3531          * if we allocated more blocks than requested
3532          * we need to make sure we unmap the extra block
3533          * allocated. The actual needed block will get
3534          * unmapped later when we find the buffer_head marked
3535          * new.
3536          */
3537         if (allocated > map->m_len) {
3538                 unmap_underlying_metadata_blocks(inode->i_sb->s_bdev,
3539                                         newblock + map->m_len,
3540                                         allocated - map->m_len);
3541                 allocated = map->m_len;
3542         }
3543
3544         /*
3545          * If we have done fallocate with the offset that is already
3546          * delayed allocated, we would have block reservation
3547          * and quota reservation done in the delayed write path.
3548          * But fallocate would have already updated quota and block
3549          * count for this offset. So cancel these reservation
3550          */
3551         if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) {
3552                 unsigned int reserved_clusters;
3553                 reserved_clusters = get_reserved_cluster_alloc(inode,
3554                                 map->m_lblk, map->m_len);
3555                 if (reserved_clusters)
3556                         ext4_da_update_reserve_space(inode,
3557                                                      reserved_clusters,
3558                                                      0);
3559         }
3560
3561 map_out:
3562         map->m_flags |= EXT4_MAP_MAPPED;
3563         if ((flags & EXT4_GET_BLOCKS_KEEP_SIZE) == 0) {
3564                 err = check_eofblocks_fl(handle, inode, map->m_lblk, path,
3565                                          map->m_len);
3566                 if (err < 0)
3567                         goto out2;
3568         }
3569 out1:
3570         if (allocated > map->m_len)
3571                 allocated = map->m_len;
3572         ext4_ext_show_leaf(inode, path);
3573         map->m_pblk = newblock;
3574         map->m_len = allocated;
3575 out2:
3576         if (path) {
3577                 ext4_ext_drop_refs(path);
3578                 kfree(path);
3579         }
3580         return err ? err : allocated;
3581 }
3582
3583 /*
3584  * get_implied_cluster_alloc - check to see if the requested
3585  * allocation (in the map structure) overlaps with a cluster already
3586  * allocated in an extent.
3587  *      @sb     The filesystem superblock structure
3588  *      @map    The requested lblk->pblk mapping
3589  *      @ex     The extent structure which might contain an implied
3590  *                      cluster allocation
3591  *
3592  * This function is called by ext4_ext_map_blocks() after we failed to
3593  * find blocks that were already in the inode's extent tree.  Hence,
3594  * we know that the beginning of the requested region cannot overlap
3595  * the extent from the inode's extent tree.  There are three cases we
3596  * want to catch.  The first is this case:
3597  *
3598  *               |--- cluster # N--|
3599  *    |--- extent ---|  |---- requested region ---|
3600  *                      |==========|
3601  *
3602  * The second case that we need to test for is this one:
3603  *
3604  *   |--------- cluster # N ----------------|
3605  *         |--- requested region --|   |------- extent ----|
3606  *         |=======================|
3607  *
3608  * The third case is when the requested region lies between two extents
3609  * within the same cluster:
3610  *          |------------- cluster # N-------------|
3611  * |----- ex -----|                  |---- ex_right ----|
3612  *                  |------ requested region ------|
3613  *                  |================|
3614  *
3615  * In each of the above cases, we need to set the map->m_pblk and
3616  * map->m_len so it corresponds to the return the extent labelled as
3617  * "|====|" from cluster #N, since it is already in use for data in
3618  * cluster EXT4_B2C(sbi, map->m_lblk).  We will then return 1 to
3619  * signal to ext4_ext_map_blocks() that map->m_pblk should be treated
3620  * as a new "allocated" block region.  Otherwise, we will return 0 and
3621  * ext4_ext_map_blocks() will then allocate one or more new clusters
3622  * by calling ext4_mb_new_blocks().
3623  */
3624 static int get_implied_cluster_alloc(struct super_block *sb,
3625                                      struct ext4_map_blocks *map,
3626                                      struct ext4_extent *ex,
3627                                      struct ext4_ext_path *path)
3628 {
3629         struct ext4_sb_info *sbi = EXT4_SB(sb);
3630         ext4_lblk_t c_offset = map->m_lblk & (sbi->s_cluster_ratio-1);
3631         ext4_lblk_t ex_cluster_start, ex_cluster_end;
3632         ext4_lblk_t rr_cluster_start;
3633         ext4_lblk_t ee_block = le32_to_cpu(ex->ee_block);
3634         ext4_fsblk_t ee_start = ext4_ext_pblock(ex);
3635         unsigned short ee_len = ext4_ext_get_actual_len(ex);
3636
3637         /* The extent passed in that we are trying to match */
3638         ex_cluster_start = EXT4_B2C(sbi, ee_block);
3639         ex_cluster_end = EXT4_B2C(sbi, ee_block + ee_len - 1);
3640
3641         /* The requested region passed into ext4_map_blocks() */
3642         rr_cluster_start = EXT4_B2C(sbi, map->m_lblk);
3643
3644         if ((rr_cluster_start == ex_cluster_end) ||
3645             (rr_cluster_start == ex_cluster_start)) {
3646                 if (rr_cluster_start == ex_cluster_end)
3647                         ee_start += ee_len - 1;
3648                 map->m_pblk = (ee_start & ~(sbi->s_cluster_ratio - 1)) +
3649                         c_offset;
3650                 map->m_len = min(map->m_len,
3651                                  (unsigned) sbi->s_cluster_ratio - c_offset);
3652                 /*
3653                  * Check for and handle this case:
3654                  *
3655                  *   |--------- cluster # N-------------|
3656                  *                     |------- extent ----|
3657                  *         |--- requested region ---|
3658                  *         |===========|
3659                  */
3660
3661                 if (map->m_lblk < ee_block)
3662                         map->m_len = min(map->m_len, ee_block - map->m_lblk);
3663
3664                 /*
3665                  * Check for the case where there is already another allocated
3666                  * block to the right of 'ex' but before the end of the cluster.
3667                  *
3668                  *          |------------- cluster # N-------------|
3669                  * |----- ex -----|                  |---- ex_right ----|
3670                  *                  |------ requested region ------|
3671                  *                  |================|
3672                  */
3673                 if (map->m_lblk > ee_block) {
3674                         ext4_lblk_t next = ext4_ext_next_allocated_block(path);
3675                         map->m_len = min(map->m_len, next - map->m_lblk);
3676                 }
3677
3678                 trace_ext4_get_implied_cluster_alloc_exit(sb, map, 1);
3679                 return 1;
3680         }
3681
3682         trace_ext4_get_implied_cluster_alloc_exit(sb, map, 0);
3683         return 0;
3684 }
3685
3686
3687 /*
3688  * Block allocation/map/preallocation routine for extents based files
3689  *
3690  *
3691  * Need to be called with
3692  * down_read(&EXT4_I(inode)->i_data_sem) if not allocating file system block
3693  * (ie, create is zero). Otherwise down_write(&EXT4_I(inode)->i_data_sem)
3694  *
3695  * return > 0, number of of blocks already mapped/allocated
3696  *          if create == 0 and these are pre-allocated blocks
3697  *              buffer head is unmapped
3698  *          otherwise blocks are mapped
3699  *
3700  * return = 0, if plain look up failed (blocks have not been allocated)
3701  *          buffer head is unmapped
3702  *
3703  * return < 0, error case.
3704  */
3705 int ext4_ext_map_blocks(handle_t *handle, struct inode *inode,
3706                         struct ext4_map_blocks *map, int flags)
3707 {
3708         struct ext4_ext_path *path = NULL;
3709         struct ext4_extent newex, *ex, *ex2;
3710         struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3711         ext4_fsblk_t newblock = 0;
3712         int free_on_err = 0, err = 0, depth, ret;
3713         unsigned int allocated = 0, offset = 0;
3714         unsigned int allocated_clusters = 0;
3715         unsigned int punched_out = 0;
3716         unsigned int result = 0;
3717         struct ext4_allocation_request ar;
3718         ext4_io_end_t *io = EXT4_I(inode)->cur_aio_dio;
3719         ext4_lblk_t cluster_offset;
3720
3721         ext_debug("blocks %u/%u requested for inode %lu\n",
3722                   map->m_lblk, map->m_len, inode->i_ino);
3723         trace_ext4_ext_map_blocks_enter(inode, map->m_lblk, map->m_len, flags);
3724
3725         /* check in cache */
3726         if (!(flags & EXT4_GET_BLOCKS_PUNCH_OUT_EXT) &&
3727                 ext4_ext_in_cache(inode, map->m_lblk, &newex)) {
3728                 if (!newex.ee_start_lo && !newex.ee_start_hi) {
3729                         if ((sbi->s_cluster_ratio > 1) &&
3730                             ext4_find_delalloc_cluster(inode, map->m_lblk, 0))
3731                                 map->m_flags |= EXT4_MAP_FROM_CLUSTER;
3732
3733                         if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
3734                                 /*
3735                                  * block isn't allocated yet and
3736                                  * user doesn't want to allocate it
3737                                  */
3738                                 goto out2;
3739                         }
3740                         /* we should allocate requested block */
3741                 } else {
3742                         /* block is already allocated */
3743                         if (sbi->s_cluster_ratio > 1)
3744                                 map->m_flags |= EXT4_MAP_FROM_CLUSTER;
3745                         newblock = map->m_lblk
3746                                    - le32_to_cpu(newex.ee_block)
3747                                    + ext4_ext_pblock(&newex);
3748                         /* number of remaining blocks in the extent */
3749                         allocated = ext4_ext_get_actual_len(&newex) -
3750                                 (map->m_lblk - le32_to_cpu(newex.ee_block));
3751                         goto out;
3752                 }
3753         }
3754
3755         /* find extent for this block */
3756         path = ext4_ext_find_extent(inode, map->m_lblk, NULL);
3757         if (IS_ERR(path)) {
3758                 err = PTR_ERR(path);
3759                 path = NULL;
3760                 goto out2;
3761         }
3762
3763         depth = ext_depth(inode);
3764
3765         /*
3766          * consistent leaf must not be empty;
3767          * this situation is possible, though, _during_ tree modification;
3768          * this is why assert can't be put in ext4_ext_find_extent()
3769          */
3770         if (unlikely(path[depth].p_ext == NULL && depth != 0)) {
3771                 EXT4_ERROR_INODE(inode, "bad extent address "
3772                                  "lblock: %lu, depth: %d pblock %lld",
3773                                  (unsigned long) map->m_lblk, depth,
3774                                  path[depth].p_block);
3775                 err = -EIO;
3776                 goto out2;
3777         }
3778
3779         ex = path[depth].p_ext;
3780         if (ex) {
3781                 ext4_lblk_t ee_block = le32_to_cpu(ex->ee_block);
3782                 ext4_fsblk_t ee_start = ext4_ext_pblock(ex);
3783                 unsigned short ee_len;
3784
3785                 /*
3786                  * Uninitialized extents are treated as holes, except that
3787                  * we split out initialized portions during a write.
3788                  */
3789                 ee_len = ext4_ext_get_actual_len(ex);
3790
3791                 trace_ext4_ext_show_extent(inode, ee_block, ee_start, ee_len);
3792
3793                 /* if found extent covers block, simply return it */
3794                 if (in_range(map->m_lblk, ee_block, ee_len)) {
3795                         struct ext4_map_blocks punch_map;
3796                         ext4_fsblk_t partial_cluster = 0;
3797
3798                         newblock = map->m_lblk - ee_block + ee_start;
3799                         /* number of remaining blocks in the extent */
3800                         allocated = ee_len - (map->m_lblk - ee_block);
3801                         ext_debug("%u fit into %u:%d -> %llu\n", map->m_lblk,
3802                                   ee_block, ee_len, newblock);
3803
3804                         if ((flags & EXT4_GET_BLOCKS_PUNCH_OUT_EXT) == 0) {
3805                                 /*
3806                                  * Do not put uninitialized extent
3807                                  * in the cache
3808                                  */
3809                                 if (!ext4_ext_is_uninitialized(ex)) {
3810                                         ext4_ext_put_in_cache(inode, ee_block,
3811                                                 ee_len, ee_start);
3812                                         goto out;
3813                                 }
3814                                 ret = ext4_ext_handle_uninitialized_extents(
3815                                         handle, inode, map, path, flags,
3816                                         allocated, newblock);
3817                                 return ret;
3818                         }
3819
3820                         /*
3821                          * Punch out the map length, but only to the
3822                          * end of the extent
3823                          */
3824                         punched_out = allocated < map->m_len ?
3825                                 allocated : map->m_len;
3826
3827                         /*
3828                          * Sense extents need to be converted to
3829                          * uninitialized, they must fit in an
3830                          * uninitialized extent
3831                          */
3832                         if (punched_out > EXT_UNINIT_MAX_LEN)
3833                                 punched_out = EXT_UNINIT_MAX_LEN;
3834
3835                         punch_map.m_lblk = map->m_lblk;
3836                         punch_map.m_pblk = newblock;
3837                         punch_map.m_len = punched_out;
3838                         punch_map.m_flags = 0;
3839
3840                         /* Check to see if the extent needs to be split */
3841                         if (punch_map.m_len != ee_len ||
3842                                 punch_map.m_lblk != ee_block) {
3843
3844                                 ret = ext4_split_extent(handle, inode,
3845                                 path, &punch_map, 0,
3846                                 EXT4_GET_BLOCKS_PUNCH_OUT_EXT |
3847                                 EXT4_GET_BLOCKS_PRE_IO);
3848
3849                                 if (ret < 0) {
3850                                         err = ret;
3851                                         goto out2;
3852                                 }
3853                                 /*
3854                                  * find extent for the block at
3855                                  * the start of the hole
3856                                  */
3857                                 ext4_ext_drop_refs(path);
3858                                 kfree(path);
3859
3860                                 path = ext4_ext_find_extent(inode,
3861                                 map->m_lblk, NULL);
3862                                 if (IS_ERR(path)) {
3863                                         err = PTR_ERR(path);
3864                                         path = NULL;
3865                                         goto out2;
3866                                 }
3867
3868                                 depth = ext_depth(inode);
3869                                 ex = path[depth].p_ext;
3870                                 ee_len = ext4_ext_get_actual_len(ex);
3871                                 ee_block = le32_to_cpu(ex->ee_block);
3872                                 ee_start = ext4_ext_pblock(ex);
3873
3874                         }
3875
3876                         ext4_ext_mark_uninitialized(ex);
3877
3878                         ext4_ext_invalidate_cache(inode);
3879
3880                         err = ext4_ext_rm_leaf(handle, inode, path,
3881                                                &partial_cluster, map->m_lblk,
3882                                                map->m_lblk + punched_out);
3883
3884                         if (!err && path->p_hdr->eh_entries == 0) {
3885                                 /*
3886                                  * Punch hole freed all of this sub tree,
3887                                  * so we need to correct eh_depth
3888                                  */
3889                                 err = ext4_ext_get_access(handle, inode, path);
3890                                 if (err == 0) {
3891                                         ext_inode_hdr(inode)->eh_depth = 0;
3892                                         ext_inode_hdr(inode)->eh_max =
3893                                         cpu_to_le16(ext4_ext_space_root(
3894                                                 inode, 0));
3895
3896                                         err = ext4_ext_dirty(
3897                                                 handle, inode, path);
3898                                 }
3899                         }
3900
3901                         goto out2;
3902                 }
3903         }
3904
3905         if ((sbi->s_cluster_ratio > 1) &&
3906             ext4_find_delalloc_cluster(inode, map->m_lblk, 0))
3907                 map->m_flags |= EXT4_MAP_FROM_CLUSTER;
3908
3909         /*
3910          * requested block isn't allocated yet;
3911          * we couldn't try to create block if create flag is zero
3912          */
3913         if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
3914                 /*
3915                  * put just found gap into cache to speed up
3916                  * subsequent requests
3917                  */
3918                 ext4_ext_put_gap_in_cache(inode, path, map->m_lblk);
3919                 goto out2;
3920         }
3921
3922         /*
3923          * Okay, we need to do block allocation.
3924          */
3925         map->m_flags &= ~EXT4_MAP_FROM_CLUSTER;
3926         newex.ee_block = cpu_to_le32(map->m_lblk);
3927         cluster_offset = map->m_lblk & (sbi->s_cluster_ratio-1);
3928
3929         /*
3930          * If we are doing bigalloc, check to see if the extent returned
3931          * by ext4_ext_find_extent() implies a cluster we can use.
3932          */
3933         if (cluster_offset && ex &&
3934             get_implied_cluster_alloc(inode->i_sb, map, ex, path)) {
3935                 ar.len = allocated = map->m_len;
3936                 newblock = map->m_pblk;
3937                 map->m_flags |= EXT4_MAP_FROM_CLUSTER;
3938                 goto got_allocated_blocks;
3939         }
3940
3941         /* find neighbour allocated blocks */
3942         ar.lleft = map->m_lblk;
3943         err = ext4_ext_search_left(inode, path, &ar.lleft, &ar.pleft);
3944         if (err)
3945                 goto out2;
3946         ar.lright = map->m_lblk;
3947         ex2 = NULL;
3948         err = ext4_ext_search_right(inode, path, &ar.lright, &ar.pright, &ex2);
3949         if (err)
3950                 goto out2;
3951
3952         /* Check if the extent after searching to the right implies a
3953          * cluster we can use. */
3954         if ((sbi->s_cluster_ratio > 1) && ex2 &&
3955             get_implied_cluster_alloc(inode->i_sb, map, ex2, path)) {
3956                 ar.len = allocated = map->m_len;
3957                 newblock = map->m_pblk;
3958                 map->m_flags |= EXT4_MAP_FROM_CLUSTER;
3959                 goto got_allocated_blocks;
3960         }
3961
3962         /*
3963          * See if request is beyond maximum number of blocks we can have in
3964          * a single extent. For an initialized extent this limit is
3965          * EXT_INIT_MAX_LEN and for an uninitialized extent this limit is
3966          * EXT_UNINIT_MAX_LEN.
3967          */
3968         if (map->m_len > EXT_INIT_MAX_LEN &&
3969             !(flags & EXT4_GET_BLOCKS_UNINIT_EXT))
3970                 map->m_len = EXT_INIT_MAX_LEN;
3971         else if (map->m_len > EXT_UNINIT_MAX_LEN &&
3972                  (flags & EXT4_GET_BLOCKS_UNINIT_EXT))
3973                 map->m_len = EXT_UNINIT_MAX_LEN;
3974
3975         /* Check if we can really insert (m_lblk)::(m_lblk + m_len) extent */
3976         newex.ee_len = cpu_to_le16(map->m_len);
3977         err = ext4_ext_check_overlap(sbi, inode, &newex, path);
3978         if (err)
3979                 allocated = ext4_ext_get_actual_len(&newex);
3980         else
3981                 allocated = map->m_len;
3982
3983         /* allocate new block */
3984         ar.inode = inode;
3985         ar.goal = ext4_ext_find_goal(inode, path, map->m_lblk);
3986         ar.logical = map->m_lblk;
3987         /*
3988          * We calculate the offset from the beginning of the cluster
3989          * for the logical block number, since when we allocate a
3990          * physical cluster, the physical block should start at the
3991          * same offset from the beginning of the cluster.  This is
3992          * needed so that future calls to get_implied_cluster_alloc()
3993          * work correctly.
3994          */
3995         offset = map->m_lblk & (sbi->s_cluster_ratio - 1);
3996         ar.len = EXT4_NUM_B2C(sbi, offset+allocated);
3997         ar.goal -= offset;
3998         ar.logical -= offset;
3999         if (S_ISREG(inode->i_mode))
4000                 ar.flags = EXT4_MB_HINT_DATA;
4001         else
4002                 /* disable in-core preallocation for non-regular files */
4003                 ar.flags = 0;
4004         if (flags & EXT4_GET_BLOCKS_NO_NORMALIZE)
4005                 ar.flags |= EXT4_MB_HINT_NOPREALLOC;
4006         newblock = ext4_mb_new_blocks(handle, &ar, &err);
4007         if (!newblock)
4008                 goto out2;
4009         ext_debug("allocate new block: goal %llu, found %llu/%u\n",
4010                   ar.goal, newblock, allocated);
4011         free_on_err = 1;
4012         allocated_clusters = ar.len;
4013         ar.len = EXT4_C2B(sbi, ar.len) - offset;
4014         if (ar.len > allocated)
4015                 ar.len = allocated;
4016
4017 got_allocated_blocks:
4018         /* try to insert new extent into found leaf and return */
4019         ext4_ext_store_pblock(&newex, newblock + offset);
4020         newex.ee_len = cpu_to_le16(ar.len);
4021         /* Mark uninitialized */
4022         if (flags & EXT4_GET_BLOCKS_UNINIT_EXT){
4023                 ext4_ext_mark_uninitialized(&newex);
4024                 /*
4025                  * io_end structure was created for every IO write to an
4026                  * uninitialized extent. To avoid unnecessary conversion,
4027                  * here we flag the IO that really needs the conversion.
4028                  * For non asycn direct IO case, flag the inode state
4029                  * that we need to perform conversion when IO is done.
4030                  */
4031                 if ((flags & EXT4_GET_BLOCKS_PRE_IO)) {
4032                         if (io)
4033                                 ext4_set_io_unwritten_flag(inode, io);
4034                         else
4035                                 ext4_set_inode_state(inode,
4036                                                      EXT4_STATE_DIO_UNWRITTEN);
4037                 }
4038                 if (ext4_should_dioread_nolock(inode))
4039                         map->m_flags |= EXT4_MAP_UNINIT;
4040         }
4041
4042         err = 0;
4043         if ((flags & EXT4_GET_BLOCKS_KEEP_SIZE) == 0)
4044                 err = check_eofblocks_fl(handle, inode, map->m_lblk,
4045                                          path, ar.len);
4046         if (!err)
4047                 err = ext4_ext_insert_extent(handle, inode, path,
4048                                              &newex, flags);
4049         if (err && free_on_err) {
4050                 int fb_flags = flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE ?
4051                         EXT4_FREE_BLOCKS_NO_QUOT_UPDATE : 0;
4052                 /* free data blocks we just allocated */
4053                 /* not a good idea to call discard here directly,
4054                  * but otherwise we'd need to call it every free() */
4055                 ext4_discard_preallocations(inode);
4056                 ext4_free_blocks(handle, inode, NULL, ext4_ext_pblock(&newex),
4057                                  ext4_ext_get_actual_len(&newex), fb_flags);
4058                 goto out2;
4059         }
4060
4061         /* previous routine could use block we allocated */
4062         newblock = ext4_ext_pblock(&newex);
4063         allocated = ext4_ext_get_actual_len(&newex);
4064         if (allocated > map->m_len)
4065                 allocated = map->m_len;
4066         map->m_flags |= EXT4_MAP_NEW;
4067
4068         /*
4069          * Update reserved blocks/metadata blocks after successful
4070          * block allocation which had been deferred till now.
4071          */
4072         if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) {
4073                 unsigned int reserved_clusters;
4074                 /*
4075                  * Check how many clusters we had reserved this allocated range
4076                  */
4077                 reserved_clusters = get_reserved_cluster_alloc(inode,
4078                                                 map->m_lblk, allocated);
4079                 if (map->m_flags & EXT4_MAP_FROM_CLUSTER) {
4080                         if (reserved_clusters) {
4081                                 /*
4082                                  * We have clusters reserved for this range.
4083                                  * But since we are not doing actual allocation
4084                                  * and are simply using blocks from previously
4085                                  * allocated cluster, we should release the
4086                                  * reservation and not claim quota.
4087                                  */
4088                                 ext4_da_update_reserve_space(inode,
4089                                                 reserved_clusters, 0);
4090                         }
4091                 } else {
4092                         BUG_ON(allocated_clusters < reserved_clusters);
4093                         /* We will claim quota for all newly allocated blocks.*/
4094                         ext4_da_update_reserve_space(inode, allocated_clusters,
4095                                                         1);
4096                         if (reserved_clusters < allocated_clusters) {
4097                                 struct ext4_inode_info *ei = EXT4_I(inode);
4098                                 int reservation = allocated_clusters -
4099                                                   reserved_clusters;
4100                                 /*
4101                                  * It seems we claimed few clusters outside of
4102                                  * the range of this allocation. We should give
4103                                  * it back to the reservation pool. This can
4104                                  * happen in the following case:
4105                                  *
4106                                  * * Suppose s_cluster_ratio is 4 (i.e., each
4107                                  *   cluster has 4 blocks. Thus, the clusters
4108                                  *   are [0-3],[4-7],[8-11]...
4109                                  * * First comes delayed allocation write for
4110                                  *   logical blocks 10 & 11. Since there were no
4111                                  *   previous delayed allocated blocks in the
4112                                  *   range [8-11], we would reserve 1 cluster
4113                                  *   for this write.
4114                                  * * Next comes write for logical blocks 3 to 8.
4115                                  *   In this case, we will reserve 2 clusters
4116                                  *   (for [0-3] and [4-7]; and not for [8-11] as
4117                                  *   that range has a delayed allocated blocks.
4118                                  *   Thus total reserved clusters now becomes 3.
4119                                  * * Now, during the delayed allocation writeout
4120                                  *   time, we will first write blocks [3-8] and
4121                                  *   allocate 3 clusters for writing these
4122                                  *   blocks. Also, we would claim all these
4123                                  *   three clusters above.
4124                                  * * Now when we come here to writeout the
4125                                  *   blocks [10-11], we would expect to claim
4126                                  *   the reservation of 1 cluster we had made
4127                                  *   (and we would claim it since there are no
4128                                  *   more delayed allocated blocks in the range
4129                                  *   [8-11]. But our reserved cluster count had
4130                                  *   already gone to 0.
4131                                  *
4132                                  *   Thus, at the step 4 above when we determine
4133                                  *   that there are still some unwritten delayed
4134                                  *   allocated blocks outside of our current
4135                                  *   block range, we should increment the
4136                                  *   reserved clusters count so that when the
4137                                  *   remaining blocks finally gets written, we
4138                                  *   could claim them.
4139                                  */
4140                                 dquot_reserve_block(inode,
4141                                                 EXT4_C2B(sbi, reservation));
4142                                 spin_lock(&ei->i_block_reservation_lock);
4143                                 ei->i_reserved_data_blocks += reservation;
4144                                 spin_unlock(&ei->i_block_reservation_lock);
4145                         }
4146                 }
4147         }
4148
4149         /*
4150          * Cache the extent and update transaction to commit on fdatasync only
4151          * when it is _not_ an uninitialized extent.
4152          */
4153         if ((flags & EXT4_GET_BLOCKS_UNINIT_EXT) == 0) {
4154                 ext4_ext_put_in_cache(inode, map->m_lblk, allocated, newblock);
4155                 ext4_update_inode_fsync_trans(handle, inode, 1);
4156         } else
4157                 ext4_update_inode_fsync_trans(handle, inode, 0);
4158 out:
4159         if (allocated > map->m_len)
4160                 allocated = map->m_len;
4161         ext4_ext_show_leaf(inode, path);
4162         map->m_flags |= EXT4_MAP_MAPPED;
4163         map->m_pblk = newblock;
4164         map->m_len = allocated;
4165 out2:
4166         if (path) {
4167                 ext4_ext_drop_refs(path);
4168                 kfree(path);
4169         }
4170         result = (flags & EXT4_GET_BLOCKS_PUNCH_OUT_EXT) ?
4171                         punched_out : allocated;
4172
4173         trace_ext4_ext_map_blocks_exit(inode, map->m_lblk,
4174                 newblock, map->m_len, err ? err : result);
4175
4176         return err ? err : result;
4177 }
4178
4179 void ext4_ext_truncate(struct inode *inode)
4180 {
4181         struct address_space *mapping = inode->i_mapping;
4182         struct super_block *sb = inode->i_sb;
4183         ext4_lblk_t last_block;
4184         handle_t *handle;
4185         loff_t page_len;
4186         int err = 0;
4187
4188         /*
4189          * finish any pending end_io work so we won't run the risk of
4190          * converting any truncated blocks to initialized later
4191          */
4192         ext4_flush_completed_IO(inode);
4193
4194         /*
4195          * probably first extent we're gonna free will be last in block
4196          */
4197         err = ext4_writepage_trans_blocks(inode);
4198         handle = ext4_journal_start(inode, err);
4199         if (IS_ERR(handle))
4200                 return;
4201
4202         if (inode->i_size % PAGE_CACHE_SIZE != 0) {
4203                 page_len = PAGE_CACHE_SIZE -
4204                         (inode->i_size & (PAGE_CACHE_SIZE - 1));
4205
4206                 err = ext4_discard_partial_page_buffers(handle,
4207                         mapping, inode->i_size, page_len, 0);
4208
4209                 if (err)
4210                         goto out_stop;
4211         }
4212
4213         if (ext4_orphan_add(handle, inode))
4214                 goto out_stop;
4215
4216         down_write(&EXT4_I(inode)->i_data_sem);
4217         ext4_ext_invalidate_cache(inode);
4218
4219         ext4_discard_preallocations(inode);
4220
4221         /*
4222          * TODO: optimization is possible here.
4223          * Probably we need not scan at all,
4224          * because page truncation is enough.
4225          */
4226
4227         /* we have to know where to truncate from in crash case */
4228         EXT4_I(inode)->i_disksize = inode->i_size;
4229         ext4_mark_inode_dirty(handle, inode);
4230
4231         last_block = (inode->i_size + sb->s_blocksize - 1)
4232                         >> EXT4_BLOCK_SIZE_BITS(sb);
4233         err = ext4_ext_remove_space(inode, last_block);
4234
4235         /* In a multi-transaction truncate, we only make the final
4236          * transaction synchronous.
4237          */
4238         if (IS_SYNC(inode))
4239                 ext4_handle_sync(handle);
4240
4241         up_write(&EXT4_I(inode)->i_data_sem);
4242
4243 out_stop:
4244         /*
4245          * If this was a simple ftruncate() and the file will remain alive,
4246          * then we need to clear up the orphan record which we created above.
4247          * However, if this was a real unlink then we were called by
4248          * ext4_delete_inode(), and we allow that function to clean up the
4249          * orphan info for us.
4250          */
4251         if (inode->i_nlink)
4252                 ext4_orphan_del(handle, inode);
4253
4254         inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
4255         ext4_mark_inode_dirty(handle, inode);
4256         ext4_journal_stop(handle);
4257 }
4258
4259 static void ext4_falloc_update_inode(struct inode *inode,
4260                                 int mode, loff_t new_size, int update_ctime)
4261 {
4262         struct timespec now;
4263
4264         if (update_ctime) {
4265                 now = current_fs_time(inode->i_sb);
4266                 if (!timespec_equal(&inode->i_ctime, &now))
4267                         inode->i_ctime = now;
4268         }
4269         /*
4270          * Update only when preallocation was requested beyond
4271          * the file size.
4272          */
4273         if (!(mode & FALLOC_FL_KEEP_SIZE)) {
4274                 if (new_size > i_size_read(inode))
4275                         i_size_write(inode, new_size);
4276                 if (new_size > EXT4_I(inode)->i_disksize)
4277                         ext4_update_i_disksize(inode, new_size);
4278         } else {
4279                 /*
4280                  * Mark that we allocate beyond EOF so the subsequent truncate
4281                  * can proceed even if the new size is the same as i_size.
4282                  */
4283                 if (new_size > i_size_read(inode))
4284                         ext4_set_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
4285         }
4286
4287 }
4288
4289 /*
4290  * preallocate space for a file. This implements ext4's fallocate file
4291  * operation, which gets called from sys_fallocate system call.
4292  * For block-mapped files, posix_fallocate should fall back to the method
4293  * of writing zeroes to the required new blocks (the same behavior which is
4294  * expected for file systems which do not support fallocate() system call).
4295  */
4296 long ext4_fallocate(struct file *file, int mode, loff_t offset, loff_t len)
4297 {
4298         struct inode *inode = file->f_path.dentry->d_inode;
4299         handle_t *handle;
4300         loff_t new_size;
4301         unsigned int max_blocks;
4302         int ret = 0;
4303         int ret2 = 0;
4304         int retries = 0;
4305         int flags;
4306         struct ext4_map_blocks map;
4307         unsigned int credits, blkbits = inode->i_blkbits;
4308
4309         /*
4310          * currently supporting (pre)allocate mode for extent-based
4311          * files _only_
4312          */
4313         if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
4314                 return -EOPNOTSUPP;
4315
4316         /* Return error if mode is not supported */
4317         if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE))
4318                 return -EOPNOTSUPP;
4319
4320         if (mode & FALLOC_FL_PUNCH_HOLE)
4321                 return ext4_punch_hole(file, offset, len);
4322
4323         trace_ext4_fallocate_enter(inode, offset, len, mode);
4324         map.m_lblk = offset >> blkbits;
4325         /*
4326          * We can't just convert len to max_blocks because
4327          * If blocksize = 4096 offset = 3072 and len = 2048
4328          */
4329         max_blocks = (EXT4_BLOCK_ALIGN(len + offset, blkbits) >> blkbits)
4330                 - map.m_lblk;
4331         /*
4332          * credits to insert 1 extent into extent tree
4333          */
4334         credits = ext4_chunk_trans_blocks(inode, max_blocks);
4335         mutex_lock(&inode->i_mutex);
4336         ret = inode_newsize_ok(inode, (len + offset));
4337         if (ret) {
4338                 mutex_unlock(&inode->i_mutex);
4339                 trace_ext4_fallocate_exit(inode, offset, max_blocks, ret);
4340                 return ret;
4341         }
4342         flags = EXT4_GET_BLOCKS_CREATE_UNINIT_EXT;
4343         if (mode & FALLOC_FL_KEEP_SIZE)
4344                 flags |= EXT4_GET_BLOCKS_KEEP_SIZE;
4345         /*
4346          * Don't normalize the request if it can fit in one extent so
4347          * that it doesn't get unnecessarily split into multiple
4348          * extents.
4349          */
4350         if (len <= EXT_UNINIT_MAX_LEN << blkbits)
4351                 flags |= EXT4_GET_BLOCKS_NO_NORMALIZE;
4352 retry:
4353         while (ret >= 0 && ret < max_blocks) {
4354                 map.m_lblk = map.m_lblk + ret;
4355                 map.m_len = max_blocks = max_blocks - ret;
4356                 handle = ext4_journal_start(inode, credits);
4357                 if (IS_ERR(handle)) {
4358                         ret = PTR_ERR(handle);
4359                         break;
4360                 }
4361                 ret = ext4_map_blocks(handle, inode, &map, flags);
4362                 if (ret <= 0) {
4363 #ifdef EXT4FS_DEBUG
4364                         WARN_ON(ret <= 0);
4365                         printk(KERN_ERR "%s: ext4_ext_map_blocks "
4366                                     "returned error inode#%lu, block=%u, "
4367                                     "max_blocks=%u", __func__,
4368                                     inode->i_ino, map.m_lblk, max_blocks);
4369 #endif
4370                         ext4_mark_inode_dirty(handle, inode);
4371                         ret2 = ext4_journal_stop(handle);
4372                         break;
4373                 }
4374                 if ((map.m_lblk + ret) >= (EXT4_BLOCK_ALIGN(offset + len,
4375                                                 blkbits) >> blkbits))
4376                         new_size = offset + len;
4377                 else
4378                         new_size = ((loff_t) map.m_lblk + ret) << blkbits;
4379
4380                 ext4_falloc_update_inode(inode, mode, new_size,
4381                                          (map.m_flags & EXT4_MAP_NEW));
4382                 ext4_mark_inode_dirty(handle, inode);
4383                 ret2 = ext4_journal_stop(handle);
4384                 if (ret2)
4385                         break;
4386         }
4387         if (ret == -ENOSPC &&
4388                         ext4_should_retry_alloc(inode->i_sb, &retries)) {
4389                 ret = 0;
4390                 goto retry;
4391         }
4392         mutex_unlock(&inode->i_mutex);
4393         trace_ext4_fallocate_exit(inode, offset, max_blocks,
4394                                 ret > 0 ? ret2 : ret);
4395         return ret > 0 ? ret2 : ret;
4396 }
4397
4398 /*
4399  * This function convert a range of blocks to written extents
4400  * The caller of this function will pass the start offset and the size.
4401  * all unwritten extents within this range will be converted to
4402  * written extents.
4403  *
4404  * This function is called from the direct IO end io call back
4405  * function, to convert the fallocated extents after IO is completed.
4406  * Returns 0 on success.
4407  */
4408 int ext4_convert_unwritten_extents(struct inode *inode, loff_t offset,
4409                                     ssize_t len)
4410 {
4411         handle_t *handle;
4412         unsigned int max_blocks;
4413         int ret = 0;
4414         int ret2 = 0;
4415         struct ext4_map_blocks map;
4416         unsigned int credits, blkbits = inode->i_blkbits;
4417
4418         map.m_lblk = offset >> blkbits;
4419         /*
4420          * We can't just convert len to max_blocks because
4421          * If blocksize = 4096 offset = 3072 and len = 2048
4422          */
4423         max_blocks = ((EXT4_BLOCK_ALIGN(len + offset, blkbits) >> blkbits) -
4424                       map.m_lblk);
4425         /*
4426          * credits to insert 1 extent into extent tree
4427          */
4428         credits = ext4_chunk_trans_blocks(inode, max_blocks);
4429         while (ret >= 0 && ret < max_blocks) {
4430                 map.m_lblk += ret;
4431                 map.m_len = (max_blocks -= ret);
4432                 handle = ext4_journal_start(inode, credits);
4433                 if (IS_ERR(handle)) {
4434                         ret = PTR_ERR(handle);
4435                         break;
4436                 }
4437                 ret = ext4_map_blocks(handle, inode, &map,
4438                                       EXT4_GET_BLOCKS_IO_CONVERT_EXT);
4439                 if (ret <= 0) {
4440                         WARN_ON(ret <= 0);
4441                         printk(KERN_ERR "%s: ext4_ext_map_blocks "
4442                                     "returned error inode#%lu, block=%u, "
4443                                     "max_blocks=%u", __func__,
4444                                     inode->i_ino, map.m_lblk, map.m_len);
4445                 }
4446                 ext4_mark_inode_dirty(handle, inode);
4447                 ret2 = ext4_journal_stop(handle);
4448                 if (ret <= 0 || ret2 )
4449                         break;
4450         }
4451         return ret > 0 ? ret2 : ret;
4452 }
4453
4454 /*
4455  * Callback function called for each extent to gather FIEMAP information.
4456  */
4457 static int ext4_ext_fiemap_cb(struct inode *inode, ext4_lblk_t next,
4458                        struct ext4_ext_cache *newex, struct ext4_extent *ex,
4459                        void *data)
4460 {
4461         __u64   logical;
4462         __u64   physical;
4463         __u64   length;
4464         __u32   flags = 0;
4465         int             ret = 0;
4466         struct fiemap_extent_info *fieinfo = data;
4467         unsigned char blksize_bits;
4468
4469         blksize_bits = inode->i_sb->s_blocksize_bits;
4470         logical = (__u64)newex->ec_block << blksize_bits;
4471
4472         if (newex->ec_start == 0) {
4473                 /*
4474                  * No extent in extent-tree contains block @newex->ec_start,
4475                  * then the block may stay in 1)a hole or 2)delayed-extent.
4476                  *
4477                  * Holes or delayed-extents are processed as follows.
4478                  * 1. lookup dirty pages with specified range in pagecache.
4479                  *    If no page is got, then there is no delayed-extent and
4480                  *    return with EXT_CONTINUE.
4481                  * 2. find the 1st mapped buffer,
4482                  * 3. check if the mapped buffer is both in the request range
4483                  *    and a delayed buffer. If not, there is no delayed-extent,
4484                  *    then return.
4485                  * 4. a delayed-extent is found, the extent will be collected.
4486                  */
4487                 ext4_lblk_t     end = 0;
4488                 pgoff_t         last_offset;
4489                 pgoff_t         offset;
4490                 pgoff_t         index;
4491                 pgoff_t         start_index = 0;
4492                 struct page     **pages = NULL;
4493                 struct buffer_head *bh = NULL;
4494                 struct buffer_head *head = NULL;
4495                 unsigned int nr_pages = PAGE_SIZE / sizeof(struct page *);
4496
4497                 pages = kmalloc(PAGE_SIZE, GFP_KERNEL);
4498                 if (pages == NULL)
4499                         return -ENOMEM;
4500
4501                 offset = logical >> PAGE_SHIFT;
4502 repeat:
4503                 last_offset = offset;
4504                 head = NULL;
4505                 ret = find_get_pages_tag(inode->i_mapping, &offset,
4506                                         PAGECACHE_TAG_DIRTY, nr_pages, pages);
4507
4508                 if (!(flags & FIEMAP_EXTENT_DELALLOC)) {
4509                         /* First time, try to find a mapped buffer. */
4510                         if (ret == 0) {
4511 out:
4512                                 for (index = 0; index < ret; index++)
4513                                         page_cache_release(pages[index]);
4514                                 /* just a hole. */
4515                                 kfree(pages);
4516                                 return EXT_CONTINUE;
4517                         }
4518                         index = 0;
4519
4520 next_page:
4521                         /* Try to find the 1st mapped buffer. */
4522                         end = ((__u64)pages[index]->index << PAGE_SHIFT) >>
4523                                   blksize_bits;
4524                         if (!page_has_buffers(pages[index]))
4525                                 goto out;
4526                         head = page_buffers(pages[index]);
4527                         if (!head)
4528                                 goto out;
4529
4530                         index++;
4531                         bh = head;
4532                         do {
4533                                 if (end >= newex->ec_block +
4534                                         newex->ec_len)
4535                                         /* The buffer is out of
4536                                          * the request range.
4537                                          */
4538                                         goto out;
4539
4540                                 if (buffer_mapped(bh) &&
4541                                     end >= newex->ec_block) {
4542                                         start_index = index - 1;
4543                                         /* get the 1st mapped buffer. */
4544                                         goto found_mapped_buffer;
4545                                 }
4546
4547                                 bh = bh->b_this_page;
4548                                 end++;
4549                         } while (bh != head);
4550
4551                         /* No mapped buffer in the range found in this page,
4552                          * We need to look up next page.
4553                          */
4554                         if (index >= ret) {
4555                                 /* There is no page left, but we need to limit
4556                                  * newex->ec_len.
4557                                  */
4558                                 newex->ec_len = end - newex->ec_block;
4559                                 goto out;
4560                         }
4561                         goto next_page;
4562                 } else {
4563                         /*Find contiguous delayed buffers. */
4564                         if (ret > 0 && pages[0]->index == last_offset)
4565                                 head = page_buffers(pages[0]);
4566                         bh = head;
4567                         index = 1;
4568                         start_index = 0;
4569                 }
4570
4571 found_mapped_buffer:
4572                 if (bh != NULL && buffer_delay(bh)) {
4573                         /* 1st or contiguous delayed buffer found. */
4574                         if (!(flags & FIEMAP_EXTENT_DELALLOC)) {
4575                                 /*
4576                                  * 1st delayed buffer found, record
4577                                  * the start of extent.
4578                                  */
4579                                 flags |= FIEMAP_EXTENT_DELALLOC;
4580                                 newex->ec_block = end;
4581                                 logical = (__u64)end << blksize_bits;
4582                         }
4583                         /* Find contiguous delayed buffers. */
4584                         do {
4585                                 if (!buffer_delay(bh))
4586                                         goto found_delayed_extent;
4587                                 bh = bh->b_this_page;
4588                                 end++;
4589                         } while (bh != head);
4590
4591                         for (; index < ret; index++) {
4592                                 if (!page_has_buffers(pages[index])) {
4593                                         bh = NULL;
4594                                         break;
4595                                 }
4596                                 head = page_buffers(pages[index]);
4597                                 if (!head) {
4598                                         bh = NULL;
4599                                         break;
4600                                 }
4601
4602                                 if (pages[index]->index !=
4603                                     pages[start_index]->index + index
4604                                     - start_index) {
4605                                         /* Blocks are not contiguous. */
4606                                         bh = NULL;
4607                                         break;
4608                                 }
4609                                 bh = head;
4610                                 do {
4611                                         if (!buffer_delay(bh))
4612                                                 /* Delayed-extent ends. */
4613                                                 goto found_delayed_extent;
4614                                         bh = bh->b_this_page;
4615                                         end++;
4616                                 } while (bh != head);
4617                         }
4618                 } else if (!(flags & FIEMAP_EXTENT_DELALLOC))
4619                         /* a hole found. */
4620                         goto out;
4621
4622 found_delayed_extent:
4623                 newex->ec_len = min(end - newex->ec_block,
4624                                                 (ext4_lblk_t)EXT_INIT_MAX_LEN);
4625                 if (ret == nr_pages && bh != NULL &&
4626                         newex->ec_len < EXT_INIT_MAX_LEN &&
4627                         buffer_delay(bh)) {
4628                         /* Have not collected an extent and continue. */
4629                         for (index = 0; index < ret; index++)
4630                                 page_cache_release(pages[index]);
4631                         goto repeat;
4632                 }
4633
4634                 for (index = 0; index < ret; index++)
4635                         page_cache_release(pages[index]);
4636                 kfree(pages);
4637         }
4638
4639         physical = (__u64)newex->ec_start << blksize_bits;
4640         length =   (__u64)newex->ec_len << blksize_bits;
4641
4642         if (ex && ext4_ext_is_uninitialized(ex))
4643                 flags |= FIEMAP_EXTENT_UNWRITTEN;
4644
4645         if (next == EXT_MAX_BLOCKS)
4646                 flags |= FIEMAP_EXTENT_LAST;
4647
4648         ret = fiemap_fill_next_extent(fieinfo, logical, physical,
4649                                         length, flags);
4650         if (ret < 0)
4651                 return ret;
4652         if (ret == 1)
4653                 return EXT_BREAK;
4654         return EXT_CONTINUE;
4655 }
4656 /* fiemap flags we can handle specified here */
4657 #define EXT4_FIEMAP_FLAGS       (FIEMAP_FLAG_SYNC|FIEMAP_FLAG_XATTR)
4658
4659 static int ext4_xattr_fiemap(struct inode *inode,
4660                                 struct fiemap_extent_info *fieinfo)
4661 {
4662         __u64 physical = 0;
4663         __u64 length;
4664         __u32 flags = FIEMAP_EXTENT_LAST;
4665         int blockbits = inode->i_sb->s_blocksize_bits;
4666         int error = 0;
4667
4668         /* in-inode? */
4669         if (ext4_test_inode_state(inode, EXT4_STATE_XATTR)) {
4670                 struct ext4_iloc iloc;
4671                 int offset;     /* offset of xattr in inode */
4672
4673                 error = ext4_get_inode_loc(inode, &iloc);
4674                 if (error)
4675                         return error;
4676                 physical = iloc.bh->b_blocknr << blockbits;
4677                 offset = EXT4_GOOD_OLD_INODE_SIZE +
4678                                 EXT4_I(inode)->i_extra_isize;
4679                 physical += offset;
4680                 length = EXT4_SB(inode->i_sb)->s_inode_size - offset;
4681                 flags |= FIEMAP_EXTENT_DATA_INLINE;
4682                 brelse(iloc.bh);
4683         } else { /* external block */
4684                 physical = EXT4_I(inode)->i_file_acl << blockbits;
4685                 length = inode->i_sb->s_blocksize;
4686         }
4687
4688         if (physical)
4689                 error = fiemap_fill_next_extent(fieinfo, 0, physical,
4690                                                 length, flags);
4691         return (error < 0 ? error : 0);
4692 }
4693
4694 /*
4695  * ext4_ext_punch_hole
4696  *
4697  * Punches a hole of "length" bytes in a file starting
4698  * at byte "offset"
4699  *
4700  * @inode:  The inode of the file to punch a hole in
4701  * @offset: The starting byte offset of the hole
4702  * @length: The length of the hole
4703  *
4704  * Returns the number of blocks removed or negative on err
4705  */
4706 int ext4_ext_punch_hole(struct file *file, loff_t offset, loff_t length)
4707 {
4708         struct inode *inode = file->f_path.dentry->d_inode;
4709         struct super_block *sb = inode->i_sb;
4710         struct ext4_ext_cache cache_ex;
4711         ext4_lblk_t first_block, last_block, num_blocks, iblock, max_blocks;
4712         struct address_space *mapping = inode->i_mapping;
4713         struct ext4_map_blocks map;
4714         handle_t *handle;
4715         loff_t first_page, last_page, page_len;
4716         loff_t first_page_offset, last_page_offset;
4717         int ret, credits, blocks_released, err = 0;
4718
4719         /* No need to punch hole beyond i_size */
4720         if (offset >= inode->i_size)
4721                 return 0;
4722
4723         /*
4724          * If the hole extends beyond i_size, set the hole
4725          * to end after the page that contains i_size
4726          */
4727         if (offset + length > inode->i_size) {
4728                 length = inode->i_size +
4729                    PAGE_CACHE_SIZE - (inode->i_size & (PAGE_CACHE_SIZE - 1)) -
4730                    offset;
4731         }
4732
4733         first_block = (offset + sb->s_blocksize - 1) >>
4734                 EXT4_BLOCK_SIZE_BITS(sb);
4735         last_block = (offset + length) >> EXT4_BLOCK_SIZE_BITS(sb);
4736
4737         first_page = (offset + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
4738         last_page = (offset + length) >> PAGE_CACHE_SHIFT;
4739
4740         first_page_offset = first_page << PAGE_CACHE_SHIFT;
4741         last_page_offset = last_page << PAGE_CACHE_SHIFT;
4742
4743         /*
4744          * Write out all dirty pages to avoid race conditions
4745          * Then release them.
4746          */
4747         if (mapping->nrpages && mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) {
4748                 err = filemap_write_and_wait_range(mapping,
4749                         offset, offset + length - 1);
4750
4751                 if (err)
4752                         return err;
4753         }
4754
4755         /* Now release the pages */
4756         if (last_page_offset > first_page_offset) {
4757                 truncate_inode_pages_range(mapping, first_page_offset,
4758                                            last_page_offset-1);
4759         }
4760
4761         /* finish any pending end_io work */
4762         ext4_flush_completed_IO(inode);
4763
4764         credits = ext4_writepage_trans_blocks(inode);
4765         handle = ext4_journal_start(inode, credits);
4766         if (IS_ERR(handle))
4767                 return PTR_ERR(handle);
4768
4769         err = ext4_orphan_add(handle, inode);
4770         if (err)
4771                 goto out;
4772
4773         /*
4774          * Now we need to zero out the non-page-aligned data in the
4775          * pages at the start and tail of the hole, and unmap the buffer
4776          * heads for the block aligned regions of the page that were
4777          * completely zeroed.
4778          */
4779         if (first_page > last_page) {
4780                 /*
4781                  * If the file space being truncated is contained within a page
4782                  * just zero out and unmap the middle of that page
4783                  */
4784                 err = ext4_discard_partial_page_buffers(handle,
4785                         mapping, offset, length, 0);
4786
4787                 if (err)
4788                         goto out;
4789         } else {
4790                 /*
4791                  * zero out and unmap the partial page that contains
4792                  * the start of the hole
4793                  */
4794                 page_len  = first_page_offset - offset;
4795                 if (page_len > 0) {
4796                         err = ext4_discard_partial_page_buffers(handle, mapping,
4797                                                    offset, page_len, 0);
4798                         if (err)
4799                                 goto out;
4800                 }
4801
4802                 /*
4803                  * zero out and unmap the partial page that contains
4804                  * the end of the hole
4805                  */
4806                 page_len = offset + length - last_page_offset;
4807                 if (page_len > 0) {
4808                         err = ext4_discard_partial_page_buffers(handle, mapping,
4809                                         last_page_offset, page_len, 0);
4810                         if (err)
4811                                 goto out;
4812                 }
4813         }
4814
4815
4816         /*
4817          * If i_size is contained in the last page, we need to
4818          * unmap and zero the partial page after i_size
4819          */
4820         if (inode->i_size >> PAGE_CACHE_SHIFT == last_page &&
4821            inode->i_size % PAGE_CACHE_SIZE != 0) {
4822
4823                 page_len = PAGE_CACHE_SIZE -
4824                         (inode->i_size & (PAGE_CACHE_SIZE - 1));
4825
4826                 if (page_len > 0) {
4827                         err = ext4_discard_partial_page_buffers(handle,
4828                           mapping, inode->i_size, page_len, 0);
4829
4830                         if (err)
4831                                 goto out;
4832                 }
4833         }
4834
4835         /* If there are no blocks to remove, return now */
4836         if (first_block >= last_block)
4837                 goto out;
4838
4839         down_write(&EXT4_I(inode)->i_data_sem);
4840         ext4_ext_invalidate_cache(inode);
4841         ext4_discard_preallocations(inode);
4842
4843         /*
4844          * Loop over all the blocks and identify blocks
4845          * that need to be punched out
4846          */
4847         iblock = first_block;
4848         blocks_released = 0;
4849         while (iblock < last_block) {
4850                 max_blocks = last_block - iblock;
4851                 num_blocks = 1;
4852                 memset(&map, 0, sizeof(map));
4853                 map.m_lblk = iblock;
4854                 map.m_len = max_blocks;
4855                 ret = ext4_ext_map_blocks(handle, inode, &map,
4856                         EXT4_GET_BLOCKS_PUNCH_OUT_EXT);
4857
4858                 if (ret > 0) {
4859                         blocks_released += ret;
4860                         num_blocks = ret;
4861                 } else if (ret == 0) {
4862                         /*
4863                          * If map blocks could not find the block,
4864                          * then it is in a hole.  If the hole was
4865                          * not already cached, then map blocks should
4866                          * put it in the cache.  So we can get the hole
4867                          * out of the cache
4868                          */
4869                         memset(&cache_ex, 0, sizeof(cache_ex));
4870                         if ((ext4_ext_check_cache(inode, iblock, &cache_ex)) &&
4871                                 !cache_ex.ec_start) {
4872
4873                                 /* The hole is cached */
4874                                 num_blocks = cache_ex.ec_block +
4875                                 cache_ex.ec_len - iblock;
4876
4877                         } else {
4878                                 /* The block could not be identified */
4879                                 err = -EIO;
4880                                 break;
4881                         }
4882                 } else {
4883                         /* Map blocks error */
4884                         err = ret;
4885                         break;
4886                 }
4887
4888                 if (num_blocks == 0) {
4889                         /* This condition should never happen */
4890                         ext_debug("Block lookup failed");
4891                         err = -EIO;
4892                         break;
4893                 }
4894
4895                 iblock += num_blocks;
4896         }
4897
4898         if (blocks_released > 0) {
4899                 ext4_ext_invalidate_cache(inode);
4900                 ext4_discard_preallocations(inode);
4901         }
4902
4903         if (IS_SYNC(inode))
4904                 ext4_handle_sync(handle);
4905
4906         up_write(&EXT4_I(inode)->i_data_sem);
4907
4908 out:
4909         ext4_orphan_del(handle, inode);
4910         inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
4911         ext4_mark_inode_dirty(handle, inode);
4912         ext4_journal_stop(handle);
4913         return err;
4914 }
4915 int ext4_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
4916                 __u64 start, __u64 len)
4917 {
4918         ext4_lblk_t start_blk;
4919         int error = 0;
4920
4921         /* fallback to generic here if not in extents fmt */
4922         if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
4923                 return generic_block_fiemap(inode, fieinfo, start, len,
4924                         ext4_get_block);
4925
4926         if (fiemap_check_flags(fieinfo, EXT4_FIEMAP_FLAGS))
4927                 return -EBADR;
4928
4929         if (fieinfo->fi_flags & FIEMAP_FLAG_XATTR) {
4930                 error = ext4_xattr_fiemap(inode, fieinfo);
4931         } else {
4932                 ext4_lblk_t len_blks;
4933                 __u64 last_blk;
4934
4935                 start_blk = start >> inode->i_sb->s_blocksize_bits;
4936                 last_blk = (start + len - 1) >> inode->i_sb->s_blocksize_bits;
4937                 if (last_blk >= EXT_MAX_BLOCKS)
4938                         last_blk = EXT_MAX_BLOCKS-1;
4939                 len_blks = ((ext4_lblk_t) last_blk) - start_blk + 1;
4940
4941                 /*
4942                  * Walk the extent tree gathering extent information.
4943                  * ext4_ext_fiemap_cb will push extents back to user.
4944                  */
4945                 error = ext4_ext_walk_space(inode, start_blk, len_blks,
4946                                           ext4_ext_fiemap_cb, fieinfo);
4947         }
4948
4949         return error;
4950 }