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