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