NFSv4.1: Ensure state manager thread dies on last umount
[firefly-linux-kernel-4.4.55.git] / fs / ext4 / extents.c
1 /*
2  * Copyright (c) 2003-2006, Cluster File Systems, Inc, info@clusterfs.com
3  * Written by Alex Tomas <alex@clusterfs.com>
4  *
5  * Architecture independence:
6  *   Copyright (c) 2005, Bull S.A.
7  *   Written by Pierre Peiffer <pierre.peiffer@bull.net>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License version 2 as
11  * published by the Free Software Foundation.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public Licens
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-
21  */
22
23 /*
24  * Extents support for EXT4
25  *
26  * TODO:
27  *   - ext4*_error() should be used in some situations
28  *   - analyze all BUG()/BUG_ON(), use -EIO where appropriate
29  *   - smart tree reduction
30  */
31
32 #include <linux/module.h>
33 #include <linux/fs.h>
34 #include <linux/time.h>
35 #include <linux/jbd2.h>
36 #include <linux/highuid.h>
37 #include <linux/pagemap.h>
38 #include <linux/quotaops.h>
39 #include <linux/string.h>
40 #include <linux/slab.h>
41 #include <linux/falloc.h>
42 #include <asm/uaccess.h>
43 #include <linux/fiemap.h>
44 #include "ext4_jbd2.h"
45 #include "ext4_extents.h"
46
47
48 /*
49  * ext_pblock:
50  * combine low and high parts of physical block number into ext4_fsblk_t
51  */
52 ext4_fsblk_t ext_pblock(struct ext4_extent *ex)
53 {
54         ext4_fsblk_t block;
55
56         block = le32_to_cpu(ex->ee_start_lo);
57         block |= ((ext4_fsblk_t) le16_to_cpu(ex->ee_start_hi) << 31) << 1;
58         return block;
59 }
60
61 /*
62  * idx_pblock:
63  * combine low and high parts of a leaf physical block number into ext4_fsblk_t
64  */
65 ext4_fsblk_t idx_pblock(struct ext4_extent_idx *ix)
66 {
67         ext4_fsblk_t block;
68
69         block = le32_to_cpu(ix->ei_leaf_lo);
70         block |= ((ext4_fsblk_t) le16_to_cpu(ix->ei_leaf_hi) << 31) << 1;
71         return block;
72 }
73
74 /*
75  * ext4_ext_store_pblock:
76  * stores a large physical block number into an extent struct,
77  * breaking it into parts
78  */
79 void ext4_ext_store_pblock(struct ext4_extent *ex, ext4_fsblk_t pb)
80 {
81         ex->ee_start_lo = cpu_to_le32((unsigned long) (pb & 0xffffffff));
82         ex->ee_start_hi = cpu_to_le16((unsigned long) ((pb >> 31) >> 1) & 0xffff);
83 }
84
85 /*
86  * ext4_idx_store_pblock:
87  * stores a large physical block number into an index struct,
88  * breaking it into parts
89  */
90 static void ext4_idx_store_pblock(struct ext4_extent_idx *ix, ext4_fsblk_t pb)
91 {
92         ix->ei_leaf_lo = cpu_to_le32((unsigned long) (pb & 0xffffffff));
93         ix->ei_leaf_hi = cpu_to_le16((unsigned long) ((pb >> 31) >> 1) & 0xffff);
94 }
95
96 static int ext4_ext_truncate_extend_restart(handle_t *handle,
97                                             struct inode *inode,
98                                             int needed)
99 {
100         int err;
101
102         if (!ext4_handle_valid(handle))
103                 return 0;
104         if (handle->h_buffer_credits > needed)
105                 return 0;
106         err = ext4_journal_extend(handle, needed);
107         if (err <= 0)
108                 return err;
109         err = ext4_truncate_restart_trans(handle, inode, needed);
110         if (err == 0)
111                 err = -EAGAIN;
112
113         return err;
114 }
115
116 /*
117  * could return:
118  *  - EROFS
119  *  - ENOMEM
120  */
121 static int ext4_ext_get_access(handle_t *handle, struct inode *inode,
122                                 struct ext4_ext_path *path)
123 {
124         if (path->p_bh) {
125                 /* path points to block */
126                 return ext4_journal_get_write_access(handle, path->p_bh);
127         }
128         /* path points to leaf/index in inode body */
129         /* we use in-core data, no need to protect them */
130         return 0;
131 }
132
133 /*
134  * could return:
135  *  - EROFS
136  *  - ENOMEM
137  *  - EIO
138  */
139 static int ext4_ext_dirty(handle_t *handle, struct inode *inode,
140                                 struct ext4_ext_path *path)
141 {
142         int err;
143         if (path->p_bh) {
144                 /* path points to block */
145                 err = ext4_handle_dirty_metadata(handle, inode, path->p_bh);
146         } else {
147                 /* path points to leaf/index in inode body */
148                 err = ext4_mark_inode_dirty(handle, inode);
149         }
150         return err;
151 }
152
153 static ext4_fsblk_t ext4_ext_find_goal(struct inode *inode,
154                               struct ext4_ext_path *path,
155                               ext4_lblk_t block)
156 {
157         struct ext4_inode_info *ei = EXT4_I(inode);
158         ext4_fsblk_t bg_start;
159         ext4_fsblk_t last_block;
160         ext4_grpblk_t colour;
161         ext4_group_t block_group;
162         int flex_size = ext4_flex_bg_size(EXT4_SB(inode->i_sb));
163         int depth;
164
165         if (path) {
166                 struct ext4_extent *ex;
167                 depth = path->p_depth;
168
169                 /* try to predict block placement */
170                 ex = path[depth].p_ext;
171                 if (ex)
172                         return ext_pblock(ex)+(block-le32_to_cpu(ex->ee_block));
173
174                 /* it looks like index is empty;
175                  * try to find starting block from index itself */
176                 if (path[depth].p_bh)
177                         return path[depth].p_bh->b_blocknr;
178         }
179
180         /* OK. use inode's group */
181         block_group = ei->i_block_group;
182         if (flex_size >= EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME) {
183                 /*
184                  * If there are at least EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME
185                  * block groups per flexgroup, reserve the first block 
186                  * group for directories and special files.  Regular 
187                  * files will start at the second block group.  This
188                  * tends to speed up directory access and improves 
189                  * fsck times.
190                  */
191                 block_group &= ~(flex_size-1);
192                 if (S_ISREG(inode->i_mode))
193                         block_group++;
194         }
195         bg_start = (block_group * EXT4_BLOCKS_PER_GROUP(inode->i_sb)) +
196                 le32_to_cpu(EXT4_SB(inode->i_sb)->s_es->s_first_data_block);
197         last_block = ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es) - 1;
198
199         /*
200          * If we are doing delayed allocation, we don't need take
201          * colour into account.
202          */
203         if (test_opt(inode->i_sb, DELALLOC))
204                 return bg_start;
205
206         if (bg_start + EXT4_BLOCKS_PER_GROUP(inode->i_sb) <= last_block)
207                 colour = (current->pid % 16) *
208                         (EXT4_BLOCKS_PER_GROUP(inode->i_sb) / 16);
209         else
210                 colour = (current->pid % 16) * ((last_block - bg_start) / 16);
211         return bg_start + colour + block;
212 }
213
214 /*
215  * Allocation for a meta data block
216  */
217 static ext4_fsblk_t
218 ext4_ext_new_meta_block(handle_t *handle, struct inode *inode,
219                         struct ext4_ext_path *path,
220                         struct ext4_extent *ex, int *err)
221 {
222         ext4_fsblk_t goal, newblock;
223
224         goal = ext4_ext_find_goal(inode, path, le32_to_cpu(ex->ee_block));
225         newblock = ext4_new_meta_blocks(handle, inode, goal, NULL, err);
226         return newblock;
227 }
228
229 static inline int ext4_ext_space_block(struct inode *inode, int check)
230 {
231         int size;
232
233         size = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
234                         / sizeof(struct ext4_extent);
235         if (!check) {
236 #ifdef AGGRESSIVE_TEST
237                 if (size > 6)
238                         size = 6;
239 #endif
240         }
241         return size;
242 }
243
244 static inline int ext4_ext_space_block_idx(struct inode *inode, int check)
245 {
246         int size;
247
248         size = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
249                         / sizeof(struct ext4_extent_idx);
250         if (!check) {
251 #ifdef AGGRESSIVE_TEST
252                 if (size > 5)
253                         size = 5;
254 #endif
255         }
256         return size;
257 }
258
259 static inline int ext4_ext_space_root(struct inode *inode, int check)
260 {
261         int size;
262
263         size = sizeof(EXT4_I(inode)->i_data);
264         size -= sizeof(struct ext4_extent_header);
265         size /= sizeof(struct ext4_extent);
266         if (!check) {
267 #ifdef AGGRESSIVE_TEST
268                 if (size > 3)
269                         size = 3;
270 #endif
271         }
272         return size;
273 }
274
275 static inline int ext4_ext_space_root_idx(struct inode *inode, int check)
276 {
277         int size;
278
279         size = sizeof(EXT4_I(inode)->i_data);
280         size -= sizeof(struct ext4_extent_header);
281         size /= sizeof(struct ext4_extent_idx);
282         if (!check) {
283 #ifdef AGGRESSIVE_TEST
284                 if (size > 4)
285                         size = 4;
286 #endif
287         }
288         return size;
289 }
290
291 /*
292  * Calculate the number of metadata blocks needed
293  * to allocate @blocks
294  * Worse case is one block per extent
295  */
296 int ext4_ext_calc_metadata_amount(struct inode *inode, sector_t lblock)
297 {
298         struct ext4_inode_info *ei = EXT4_I(inode);
299         int idxs, num = 0;
300
301         idxs = ((inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
302                 / sizeof(struct ext4_extent_idx));
303
304         /*
305          * If the new delayed allocation block is contiguous with the
306          * previous da block, it can share index blocks with the
307          * previous block, so we only need to allocate a new index
308          * block every idxs leaf blocks.  At ldxs**2 blocks, we need
309          * an additional index block, and at ldxs**3 blocks, yet
310          * another index blocks.
311          */
312         if (ei->i_da_metadata_calc_len &&
313             ei->i_da_metadata_calc_last_lblock+1 == lblock) {
314                 if ((ei->i_da_metadata_calc_len % idxs) == 0)
315                         num++;
316                 if ((ei->i_da_metadata_calc_len % (idxs*idxs)) == 0)
317                         num++;
318                 if ((ei->i_da_metadata_calc_len % (idxs*idxs*idxs)) == 0) {
319                         num++;
320                         ei->i_da_metadata_calc_len = 0;
321                 } else
322                         ei->i_da_metadata_calc_len++;
323                 ei->i_da_metadata_calc_last_lblock++;
324                 return num;
325         }
326
327         /*
328          * In the worst case we need a new set of index blocks at
329          * every level of the inode's extent tree.
330          */
331         ei->i_da_metadata_calc_len = 1;
332         ei->i_da_metadata_calc_last_lblock = lblock;
333         return ext_depth(inode) + 1;
334 }
335
336 static int
337 ext4_ext_max_entries(struct inode *inode, int depth)
338 {
339         int max;
340
341         if (depth == ext_depth(inode)) {
342                 if (depth == 0)
343                         max = ext4_ext_space_root(inode, 1);
344                 else
345                         max = ext4_ext_space_root_idx(inode, 1);
346         } else {
347                 if (depth == 0)
348                         max = ext4_ext_space_block(inode, 1);
349                 else
350                         max = ext4_ext_space_block_idx(inode, 1);
351         }
352
353         return max;
354 }
355
356 static int ext4_valid_extent(struct inode *inode, struct ext4_extent *ext)
357 {
358         ext4_fsblk_t block = ext_pblock(ext);
359         int len = ext4_ext_get_actual_len(ext);
360
361         return ext4_data_block_valid(EXT4_SB(inode->i_sb), block, len);
362 }
363
364 static int ext4_valid_extent_idx(struct inode *inode,
365                                 struct ext4_extent_idx *ext_idx)
366 {
367         ext4_fsblk_t block = idx_pblock(ext_idx);
368
369         return ext4_data_block_valid(EXT4_SB(inode->i_sb), block, 1);
370 }
371
372 static int ext4_valid_extent_entries(struct inode *inode,
373                                 struct ext4_extent_header *eh,
374                                 int depth)
375 {
376         struct ext4_extent *ext;
377         struct ext4_extent_idx *ext_idx;
378         unsigned short entries;
379         if (eh->eh_entries == 0)
380                 return 1;
381
382         entries = le16_to_cpu(eh->eh_entries);
383
384         if (depth == 0) {
385                 /* leaf entries */
386                 ext = EXT_FIRST_EXTENT(eh);
387                 while (entries) {
388                         if (!ext4_valid_extent(inode, ext))
389                                 return 0;
390                         ext++;
391                         entries--;
392                 }
393         } else {
394                 ext_idx = EXT_FIRST_INDEX(eh);
395                 while (entries) {
396                         if (!ext4_valid_extent_idx(inode, ext_idx))
397                                 return 0;
398                         ext_idx++;
399                         entries--;
400                 }
401         }
402         return 1;
403 }
404
405 static int __ext4_ext_check(const char *function, struct inode *inode,
406                                         struct ext4_extent_header *eh,
407                                         int depth)
408 {
409         const char *error_msg;
410         int max = 0;
411
412         if (unlikely(eh->eh_magic != EXT4_EXT_MAGIC)) {
413                 error_msg = "invalid magic";
414                 goto corrupted;
415         }
416         if (unlikely(le16_to_cpu(eh->eh_depth) != depth)) {
417                 error_msg = "unexpected eh_depth";
418                 goto corrupted;
419         }
420         if (unlikely(eh->eh_max == 0)) {
421                 error_msg = "invalid eh_max";
422                 goto corrupted;
423         }
424         max = ext4_ext_max_entries(inode, depth);
425         if (unlikely(le16_to_cpu(eh->eh_max) > max)) {
426                 error_msg = "too large eh_max";
427                 goto corrupted;
428         }
429         if (unlikely(le16_to_cpu(eh->eh_entries) > le16_to_cpu(eh->eh_max))) {
430                 error_msg = "invalid eh_entries";
431                 goto corrupted;
432         }
433         if (!ext4_valid_extent_entries(inode, eh, depth)) {
434                 error_msg = "invalid extent entries";
435                 goto corrupted;
436         }
437         return 0;
438
439 corrupted:
440         ext4_error(inode->i_sb, function,
441                         "bad header/extent in inode #%lu: %s - magic %x, "
442                         "entries %u, max %u(%u), depth %u(%u)",
443                         inode->i_ino, error_msg, le16_to_cpu(eh->eh_magic),
444                         le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max),
445                         max, le16_to_cpu(eh->eh_depth), depth);
446
447         return -EIO;
448 }
449
450 #define ext4_ext_check(inode, eh, depth)        \
451         __ext4_ext_check(__func__, inode, eh, depth)
452
453 int ext4_ext_check_inode(struct inode *inode)
454 {
455         return ext4_ext_check(inode, ext_inode_hdr(inode), ext_depth(inode));
456 }
457
458 #ifdef EXT_DEBUG
459 static void ext4_ext_show_path(struct inode *inode, struct ext4_ext_path *path)
460 {
461         int k, l = path->p_depth;
462
463         ext_debug("path:");
464         for (k = 0; k <= l; k++, path++) {
465                 if (path->p_idx) {
466                   ext_debug("  %d->%llu", le32_to_cpu(path->p_idx->ei_block),
467                             idx_pblock(path->p_idx));
468                 } else if (path->p_ext) {
469                         ext_debug("  %d:[%d]%d:%llu ",
470                                   le32_to_cpu(path->p_ext->ee_block),
471                                   ext4_ext_is_uninitialized(path->p_ext),
472                                   ext4_ext_get_actual_len(path->p_ext),
473                                   ext_pblock(path->p_ext));
474                 } else
475                         ext_debug("  []");
476         }
477         ext_debug("\n");
478 }
479
480 static void ext4_ext_show_leaf(struct inode *inode, struct ext4_ext_path *path)
481 {
482         int depth = ext_depth(inode);
483         struct ext4_extent_header *eh;
484         struct ext4_extent *ex;
485         int i;
486
487         if (!path)
488                 return;
489
490         eh = path[depth].p_hdr;
491         ex = EXT_FIRST_EXTENT(eh);
492
493         ext_debug("Displaying leaf extents for inode %lu\n", inode->i_ino);
494
495         for (i = 0; i < le16_to_cpu(eh->eh_entries); i++, ex++) {
496                 ext_debug("%d:[%d]%d:%llu ", le32_to_cpu(ex->ee_block),
497                           ext4_ext_is_uninitialized(ex),
498                           ext4_ext_get_actual_len(ex), ext_pblock(ex));
499         }
500         ext_debug("\n");
501 }
502 #else
503 #define ext4_ext_show_path(inode, path)
504 #define ext4_ext_show_leaf(inode, path)
505 #endif
506
507 void ext4_ext_drop_refs(struct ext4_ext_path *path)
508 {
509         int depth = path->p_depth;
510         int i;
511
512         for (i = 0; i <= depth; i++, path++)
513                 if (path->p_bh) {
514                         brelse(path->p_bh);
515                         path->p_bh = NULL;
516                 }
517 }
518
519 /*
520  * ext4_ext_binsearch_idx:
521  * binary search for the closest index of the given block
522  * the header must be checked before calling this
523  */
524 static void
525 ext4_ext_binsearch_idx(struct inode *inode,
526                         struct ext4_ext_path *path, ext4_lblk_t block)
527 {
528         struct ext4_extent_header *eh = path->p_hdr;
529         struct ext4_extent_idx *r, *l, *m;
530
531
532         ext_debug("binsearch for %u(idx):  ", block);
533
534         l = EXT_FIRST_INDEX(eh) + 1;
535         r = EXT_LAST_INDEX(eh);
536         while (l <= r) {
537                 m = l + (r - l) / 2;
538                 if (block < le32_to_cpu(m->ei_block))
539                         r = m - 1;
540                 else
541                         l = m + 1;
542                 ext_debug("%p(%u):%p(%u):%p(%u) ", l, le32_to_cpu(l->ei_block),
543                                 m, le32_to_cpu(m->ei_block),
544                                 r, le32_to_cpu(r->ei_block));
545         }
546
547         path->p_idx = l - 1;
548         ext_debug("  -> %d->%lld ", le32_to_cpu(path->p_idx->ei_block),
549                   idx_pblock(path->p_idx));
550
551 #ifdef CHECK_BINSEARCH
552         {
553                 struct ext4_extent_idx *chix, *ix;
554                 int k;
555
556                 chix = ix = EXT_FIRST_INDEX(eh);
557                 for (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ix++) {
558                   if (k != 0 &&
559                       le32_to_cpu(ix->ei_block) <= le32_to_cpu(ix[-1].ei_block)) {
560                                 printk(KERN_DEBUG "k=%d, ix=0x%p, "
561                                        "first=0x%p\n", k,
562                                        ix, EXT_FIRST_INDEX(eh));
563                                 printk(KERN_DEBUG "%u <= %u\n",
564                                        le32_to_cpu(ix->ei_block),
565                                        le32_to_cpu(ix[-1].ei_block));
566                         }
567                         BUG_ON(k && le32_to_cpu(ix->ei_block)
568                                            <= le32_to_cpu(ix[-1].ei_block));
569                         if (block < le32_to_cpu(ix->ei_block))
570                                 break;
571                         chix = ix;
572                 }
573                 BUG_ON(chix != path->p_idx);
574         }
575 #endif
576
577 }
578
579 /*
580  * ext4_ext_binsearch:
581  * binary search for closest extent of the given block
582  * the header must be checked before calling this
583  */
584 static void
585 ext4_ext_binsearch(struct inode *inode,
586                 struct ext4_ext_path *path, ext4_lblk_t block)
587 {
588         struct ext4_extent_header *eh = path->p_hdr;
589         struct ext4_extent *r, *l, *m;
590
591         if (eh->eh_entries == 0) {
592                 /*
593                  * this leaf is empty:
594                  * we get such a leaf in split/add case
595                  */
596                 return;
597         }
598
599         ext_debug("binsearch for %u:  ", block);
600
601         l = EXT_FIRST_EXTENT(eh) + 1;
602         r = EXT_LAST_EXTENT(eh);
603
604         while (l <= r) {
605                 m = l + (r - l) / 2;
606                 if (block < le32_to_cpu(m->ee_block))
607                         r = m - 1;
608                 else
609                         l = m + 1;
610                 ext_debug("%p(%u):%p(%u):%p(%u) ", l, le32_to_cpu(l->ee_block),
611                                 m, le32_to_cpu(m->ee_block),
612                                 r, le32_to_cpu(r->ee_block));
613         }
614
615         path->p_ext = l - 1;
616         ext_debug("  -> %d:%llu:[%d]%d ",
617                         le32_to_cpu(path->p_ext->ee_block),
618                         ext_pblock(path->p_ext),
619                         ext4_ext_is_uninitialized(path->p_ext),
620                         ext4_ext_get_actual_len(path->p_ext));
621
622 #ifdef CHECK_BINSEARCH
623         {
624                 struct ext4_extent *chex, *ex;
625                 int k;
626
627                 chex = ex = EXT_FIRST_EXTENT(eh);
628                 for (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ex++) {
629                         BUG_ON(k && le32_to_cpu(ex->ee_block)
630                                           <= le32_to_cpu(ex[-1].ee_block));
631                         if (block < le32_to_cpu(ex->ee_block))
632                                 break;
633                         chex = ex;
634                 }
635                 BUG_ON(chex != path->p_ext);
636         }
637 #endif
638
639 }
640
641 int ext4_ext_tree_init(handle_t *handle, struct inode *inode)
642 {
643         struct ext4_extent_header *eh;
644
645         eh = ext_inode_hdr(inode);
646         eh->eh_depth = 0;
647         eh->eh_entries = 0;
648         eh->eh_magic = EXT4_EXT_MAGIC;
649         eh->eh_max = cpu_to_le16(ext4_ext_space_root(inode, 0));
650         ext4_mark_inode_dirty(handle, inode);
651         ext4_ext_invalidate_cache(inode);
652         return 0;
653 }
654
655 struct ext4_ext_path *
656 ext4_ext_find_extent(struct inode *inode, ext4_lblk_t block,
657                                         struct ext4_ext_path *path)
658 {
659         struct ext4_extent_header *eh;
660         struct buffer_head *bh;
661         short int depth, i, ppos = 0, alloc = 0;
662
663         eh = ext_inode_hdr(inode);
664         depth = ext_depth(inode);
665
666         /* account possible depth increase */
667         if (!path) {
668                 path = kzalloc(sizeof(struct ext4_ext_path) * (depth + 2),
669                                 GFP_NOFS);
670                 if (!path)
671                         return ERR_PTR(-ENOMEM);
672                 alloc = 1;
673         }
674         path[0].p_hdr = eh;
675         path[0].p_bh = NULL;
676
677         i = depth;
678         /* walk through the tree */
679         while (i) {
680                 int need_to_validate = 0;
681
682                 ext_debug("depth %d: num %d, max %d\n",
683                           ppos, le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
684
685                 ext4_ext_binsearch_idx(inode, path + ppos, block);
686                 path[ppos].p_block = idx_pblock(path[ppos].p_idx);
687                 path[ppos].p_depth = i;
688                 path[ppos].p_ext = NULL;
689
690                 bh = sb_getblk(inode->i_sb, path[ppos].p_block);
691                 if (unlikely(!bh))
692                         goto err;
693                 if (!bh_uptodate_or_lock(bh)) {
694                         if (bh_submit_read(bh) < 0) {
695                                 put_bh(bh);
696                                 goto err;
697                         }
698                         /* validate the extent entries */
699                         need_to_validate = 1;
700                 }
701                 eh = ext_block_hdr(bh);
702                 ppos++;
703                 BUG_ON(ppos > depth);
704                 path[ppos].p_bh = bh;
705                 path[ppos].p_hdr = eh;
706                 i--;
707
708                 if (need_to_validate && ext4_ext_check(inode, eh, i))
709                         goto err;
710         }
711
712         path[ppos].p_depth = i;
713         path[ppos].p_ext = NULL;
714         path[ppos].p_idx = NULL;
715
716         /* find extent */
717         ext4_ext_binsearch(inode, path + ppos, block);
718         /* if not an empty leaf */
719         if (path[ppos].p_ext)
720                 path[ppos].p_block = ext_pblock(path[ppos].p_ext);
721
722         ext4_ext_show_path(inode, path);
723
724         return path;
725
726 err:
727         ext4_ext_drop_refs(path);
728         if (alloc)
729                 kfree(path);
730         return ERR_PTR(-EIO);
731 }
732
733 /*
734  * ext4_ext_insert_index:
735  * insert new index [@logical;@ptr] into the block at @curp;
736  * check where to insert: before @curp or after @curp
737  */
738 int ext4_ext_insert_index(handle_t *handle, struct inode *inode,
739                                 struct ext4_ext_path *curp,
740                                 int logical, ext4_fsblk_t ptr)
741 {
742         struct ext4_extent_idx *ix;
743         int len, err;
744
745         err = ext4_ext_get_access(handle, inode, curp);
746         if (err)
747                 return err;
748
749         BUG_ON(logical == le32_to_cpu(curp->p_idx->ei_block));
750         len = EXT_MAX_INDEX(curp->p_hdr) - curp->p_idx;
751         if (logical > le32_to_cpu(curp->p_idx->ei_block)) {
752                 /* insert after */
753                 if (curp->p_idx != EXT_LAST_INDEX(curp->p_hdr)) {
754                         len = (len - 1) * sizeof(struct ext4_extent_idx);
755                         len = len < 0 ? 0 : len;
756                         ext_debug("insert new index %d after: %llu. "
757                                         "move %d from 0x%p to 0x%p\n",
758                                         logical, ptr, len,
759                                         (curp->p_idx + 1), (curp->p_idx + 2));
760                         memmove(curp->p_idx + 2, curp->p_idx + 1, len);
761                 }
762                 ix = curp->p_idx + 1;
763         } else {
764                 /* insert before */
765                 len = len * sizeof(struct ext4_extent_idx);
766                 len = len < 0 ? 0 : len;
767                 ext_debug("insert new index %d before: %llu. "
768                                 "move %d from 0x%p to 0x%p\n",
769                                 logical, ptr, len,
770                                 curp->p_idx, (curp->p_idx + 1));
771                 memmove(curp->p_idx + 1, curp->p_idx, len);
772                 ix = curp->p_idx;
773         }
774
775         ix->ei_block = cpu_to_le32(logical);
776         ext4_idx_store_pblock(ix, ptr);
777         le16_add_cpu(&curp->p_hdr->eh_entries, 1);
778
779         BUG_ON(le16_to_cpu(curp->p_hdr->eh_entries)
780                              > le16_to_cpu(curp->p_hdr->eh_max));
781         BUG_ON(ix > EXT_LAST_INDEX(curp->p_hdr));
782
783         err = ext4_ext_dirty(handle, inode, curp);
784         ext4_std_error(inode->i_sb, err);
785
786         return err;
787 }
788
789 /*
790  * ext4_ext_split:
791  * inserts new subtree into the path, using free index entry
792  * at depth @at:
793  * - allocates all needed blocks (new leaf and all intermediate index blocks)
794  * - makes decision where to split
795  * - moves remaining extents and index entries (right to the split point)
796  *   into the newly allocated blocks
797  * - initializes subtree
798  */
799 static int ext4_ext_split(handle_t *handle, struct inode *inode,
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         struct ext4_extent *ex;
808         int i = at, k, m, a;
809         ext4_fsblk_t newblock, oldblock;
810         __le32 border;
811         ext4_fsblk_t *ablocks = NULL; /* array of allocated blocks */
812         int err = 0;
813
814         /* make decision: where to split? */
815         /* FIXME: now decision is simplest: at current extent */
816
817         /* if current leaf will be split, then we should use
818          * border from split point */
819         BUG_ON(path[depth].p_ext > EXT_MAX_EXTENT(path[depth].p_hdr));
820         if (path[depth].p_ext != EXT_MAX_EXTENT(path[depth].p_hdr)) {
821                 border = path[depth].p_ext[1].ee_block;
822                 ext_debug("leaf will be split."
823                                 " next leaf starts at %d\n",
824                                   le32_to_cpu(border));
825         } else {
826                 border = newext->ee_block;
827                 ext_debug("leaf will be added."
828                                 " next leaf starts at %d\n",
829                                 le32_to_cpu(border));
830         }
831
832         /*
833          * If error occurs, then we break processing
834          * and mark filesystem read-only. index won't
835          * be inserted and tree will be in consistent
836          * state. Next mount will repair buffers too.
837          */
838
839         /*
840          * Get array to track all allocated blocks.
841          * We need this to handle errors and free blocks
842          * upon them.
843          */
844         ablocks = kzalloc(sizeof(ext4_fsblk_t) * depth, GFP_NOFS);
845         if (!ablocks)
846                 return -ENOMEM;
847
848         /* allocate all needed blocks */
849         ext_debug("allocate %d blocks for indexes/leaf\n", depth - at);
850         for (a = 0; a < depth - at; a++) {
851                 newblock = ext4_ext_new_meta_block(handle, inode, path,
852                                                    newext, &err);
853                 if (newblock == 0)
854                         goto cleanup;
855                 ablocks[a] = newblock;
856         }
857
858         /* initialize new leaf */
859         newblock = ablocks[--a];
860         BUG_ON(newblock == 0);
861         bh = sb_getblk(inode->i_sb, newblock);
862         if (!bh) {
863                 err = -EIO;
864                 goto cleanup;
865         }
866         lock_buffer(bh);
867
868         err = ext4_journal_get_create_access(handle, bh);
869         if (err)
870                 goto cleanup;
871
872         neh = ext_block_hdr(bh);
873         neh->eh_entries = 0;
874         neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0));
875         neh->eh_magic = EXT4_EXT_MAGIC;
876         neh->eh_depth = 0;
877         ex = EXT_FIRST_EXTENT(neh);
878
879         /* move remainder of path[depth] to the new leaf */
880         BUG_ON(path[depth].p_hdr->eh_entries != path[depth].p_hdr->eh_max);
881         /* start copy from next extent */
882         /* TODO: we could do it by single memmove */
883         m = 0;
884         path[depth].p_ext++;
885         while (path[depth].p_ext <=
886                         EXT_MAX_EXTENT(path[depth].p_hdr)) {
887                 ext_debug("move %d:%llu:[%d]%d in new leaf %llu\n",
888                                 le32_to_cpu(path[depth].p_ext->ee_block),
889                                 ext_pblock(path[depth].p_ext),
890                                 ext4_ext_is_uninitialized(path[depth].p_ext),
891                                 ext4_ext_get_actual_len(path[depth].p_ext),
892                                 newblock);
893                 /*memmove(ex++, path[depth].p_ext++,
894                                 sizeof(struct ext4_extent));
895                 neh->eh_entries++;*/
896                 path[depth].p_ext++;
897                 m++;
898         }
899         if (m) {
900                 memmove(ex, path[depth].p_ext-m, sizeof(struct ext4_extent)*m);
901                 le16_add_cpu(&neh->eh_entries, m);
902         }
903
904         set_buffer_uptodate(bh);
905         unlock_buffer(bh);
906
907         err = ext4_handle_dirty_metadata(handle, inode, bh);
908         if (err)
909                 goto cleanup;
910         brelse(bh);
911         bh = NULL;
912
913         /* correct old leaf */
914         if (m) {
915                 err = ext4_ext_get_access(handle, inode, path + depth);
916                 if (err)
917                         goto cleanup;
918                 le16_add_cpu(&path[depth].p_hdr->eh_entries, -m);
919                 err = ext4_ext_dirty(handle, inode, path + depth);
920                 if (err)
921                         goto cleanup;
922
923         }
924
925         /* create intermediate indexes */
926         k = depth - at - 1;
927         BUG_ON(k < 0);
928         if (k)
929                 ext_debug("create %d intermediate indices\n", k);
930         /* insert new index into current index block */
931         /* current depth stored in i var */
932         i = depth - 1;
933         while (k--) {
934                 oldblock = newblock;
935                 newblock = ablocks[--a];
936                 bh = sb_getblk(inode->i_sb, newblock);
937                 if (!bh) {
938                         err = -EIO;
939                         goto cleanup;
940                 }
941                 lock_buffer(bh);
942
943                 err = ext4_journal_get_create_access(handle, bh);
944                 if (err)
945                         goto cleanup;
946
947                 neh = ext_block_hdr(bh);
948                 neh->eh_entries = cpu_to_le16(1);
949                 neh->eh_magic = EXT4_EXT_MAGIC;
950                 neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0));
951                 neh->eh_depth = cpu_to_le16(depth - i);
952                 fidx = EXT_FIRST_INDEX(neh);
953                 fidx->ei_block = border;
954                 ext4_idx_store_pblock(fidx, oldblock);
955
956                 ext_debug("int.index at %d (block %llu): %u -> %llu\n",
957                                 i, newblock, le32_to_cpu(border), oldblock);
958                 /* copy indexes */
959                 m = 0;
960                 path[i].p_idx++;
961
962                 ext_debug("cur 0x%p, last 0x%p\n", path[i].p_idx,
963                                 EXT_MAX_INDEX(path[i].p_hdr));
964                 BUG_ON(EXT_MAX_INDEX(path[i].p_hdr) !=
965                                 EXT_LAST_INDEX(path[i].p_hdr));
966                 while (path[i].p_idx <= EXT_MAX_INDEX(path[i].p_hdr)) {
967                         ext_debug("%d: move %d:%llu in new index %llu\n", i,
968                                         le32_to_cpu(path[i].p_idx->ei_block),
969                                         idx_pblock(path[i].p_idx),
970                                         newblock);
971                         /*memmove(++fidx, path[i].p_idx++,
972                                         sizeof(struct ext4_extent_idx));
973                         neh->eh_entries++;
974                         BUG_ON(neh->eh_entries > neh->eh_max);*/
975                         path[i].p_idx++;
976                         m++;
977                 }
978                 if (m) {
979                         memmove(++fidx, path[i].p_idx - m,
980                                 sizeof(struct ext4_extent_idx) * m);
981                         le16_add_cpu(&neh->eh_entries, m);
982                 }
983                 set_buffer_uptodate(bh);
984                 unlock_buffer(bh);
985
986                 err = ext4_handle_dirty_metadata(handle, inode, bh);
987                 if (err)
988                         goto cleanup;
989                 brelse(bh);
990                 bh = NULL;
991
992                 /* correct old index */
993                 if (m) {
994                         err = ext4_ext_get_access(handle, inode, path + i);
995                         if (err)
996                                 goto cleanup;
997                         le16_add_cpu(&path[i].p_hdr->eh_entries, -m);
998                         err = ext4_ext_dirty(handle, inode, path + i);
999                         if (err)
1000                                 goto cleanup;
1001                 }
1002
1003                 i--;
1004         }
1005
1006         /* insert new index */
1007         err = ext4_ext_insert_index(handle, inode, path + at,
1008                                     le32_to_cpu(border), newblock);
1009
1010 cleanup:
1011         if (bh) {
1012                 if (buffer_locked(bh))
1013                         unlock_buffer(bh);
1014                 brelse(bh);
1015         }
1016
1017         if (err) {
1018                 /* free all allocated blocks in error case */
1019                 for (i = 0; i < depth; i++) {
1020                         if (!ablocks[i])
1021                                 continue;
1022                         ext4_free_blocks(handle, inode, ablocks[i], 1, 1);
1023                 }
1024         }
1025         kfree(ablocks);
1026
1027         return err;
1028 }
1029
1030 /*
1031  * ext4_ext_grow_indepth:
1032  * implements tree growing procedure:
1033  * - allocates new block
1034  * - moves top-level data (index block or leaf) into the new block
1035  * - initializes new top-level, creating index that points to the
1036  *   just created block
1037  */
1038 static int ext4_ext_grow_indepth(handle_t *handle, struct inode *inode,
1039                                         struct ext4_ext_path *path,
1040                                         struct ext4_extent *newext)
1041 {
1042         struct ext4_ext_path *curp = path;
1043         struct ext4_extent_header *neh;
1044         struct ext4_extent_idx *fidx;
1045         struct buffer_head *bh;
1046         ext4_fsblk_t newblock;
1047         int err = 0;
1048
1049         newblock = ext4_ext_new_meta_block(handle, inode, path, newext, &err);
1050         if (newblock == 0)
1051                 return err;
1052
1053         bh = sb_getblk(inode->i_sb, newblock);
1054         if (!bh) {
1055                 err = -EIO;
1056                 ext4_std_error(inode->i_sb, err);
1057                 return err;
1058         }
1059         lock_buffer(bh);
1060
1061         err = ext4_journal_get_create_access(handle, bh);
1062         if (err) {
1063                 unlock_buffer(bh);
1064                 goto out;
1065         }
1066
1067         /* move top-level index/leaf into new block */
1068         memmove(bh->b_data, curp->p_hdr, sizeof(EXT4_I(inode)->i_data));
1069
1070         /* set size of new block */
1071         neh = ext_block_hdr(bh);
1072         /* old root could have indexes or leaves
1073          * so calculate e_max right way */
1074         if (ext_depth(inode))
1075                 neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0));
1076         else
1077                 neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0));
1078         neh->eh_magic = EXT4_EXT_MAGIC;
1079         set_buffer_uptodate(bh);
1080         unlock_buffer(bh);
1081
1082         err = ext4_handle_dirty_metadata(handle, inode, bh);
1083         if (err)
1084                 goto out;
1085
1086         /* create index in new top-level index: num,max,pointer */
1087         err = ext4_ext_get_access(handle, inode, curp);
1088         if (err)
1089                 goto out;
1090
1091         curp->p_hdr->eh_magic = EXT4_EXT_MAGIC;
1092         curp->p_hdr->eh_max = cpu_to_le16(ext4_ext_space_root_idx(inode, 0));
1093         curp->p_hdr->eh_entries = cpu_to_le16(1);
1094         curp->p_idx = EXT_FIRST_INDEX(curp->p_hdr);
1095
1096         if (path[0].p_hdr->eh_depth)
1097                 curp->p_idx->ei_block =
1098                         EXT_FIRST_INDEX(path[0].p_hdr)->ei_block;
1099         else
1100                 curp->p_idx->ei_block =
1101                         EXT_FIRST_EXTENT(path[0].p_hdr)->ee_block;
1102         ext4_idx_store_pblock(curp->p_idx, newblock);
1103
1104         neh = ext_inode_hdr(inode);
1105         fidx = EXT_FIRST_INDEX(neh);
1106         ext_debug("new root: num %d(%d), lblock %d, ptr %llu\n",
1107                   le16_to_cpu(neh->eh_entries), le16_to_cpu(neh->eh_max),
1108                   le32_to_cpu(fidx->ei_block), idx_pblock(fidx));
1109
1110         neh->eh_depth = cpu_to_le16(path->p_depth + 1);
1111         err = ext4_ext_dirty(handle, inode, curp);
1112 out:
1113         brelse(bh);
1114
1115         return err;
1116 }
1117
1118 /*
1119  * ext4_ext_create_new_leaf:
1120  * finds empty index and adds new leaf.
1121  * if no free index is found, then it requests in-depth growing.
1122  */
1123 static int ext4_ext_create_new_leaf(handle_t *handle, struct inode *inode,
1124                                         struct ext4_ext_path *path,
1125                                         struct ext4_extent *newext)
1126 {
1127         struct ext4_ext_path *curp;
1128         int depth, i, err = 0;
1129
1130 repeat:
1131         i = depth = ext_depth(inode);
1132
1133         /* walk up to the tree and look for free index entry */
1134         curp = path + depth;
1135         while (i > 0 && !EXT_HAS_FREE_INDEX(curp)) {
1136                 i--;
1137                 curp--;
1138         }
1139
1140         /* we use already allocated block for index block,
1141          * so subsequent data blocks should be contiguous */
1142         if (EXT_HAS_FREE_INDEX(curp)) {
1143                 /* if we found index with free entry, then use that
1144                  * entry: create all needed subtree and add new leaf */
1145                 err = ext4_ext_split(handle, inode, path, newext, i);
1146                 if (err)
1147                         goto out;
1148
1149                 /* refill path */
1150                 ext4_ext_drop_refs(path);
1151                 path = ext4_ext_find_extent(inode,
1152                                     (ext4_lblk_t)le32_to_cpu(newext->ee_block),
1153                                     path);
1154                 if (IS_ERR(path))
1155                         err = PTR_ERR(path);
1156         } else {
1157                 /* tree is full, time to grow in depth */
1158                 err = ext4_ext_grow_indepth(handle, inode, path, newext);
1159                 if (err)
1160                         goto out;
1161
1162                 /* refill path */
1163                 ext4_ext_drop_refs(path);
1164                 path = ext4_ext_find_extent(inode,
1165                                    (ext4_lblk_t)le32_to_cpu(newext->ee_block),
1166                                     path);
1167                 if (IS_ERR(path)) {
1168                         err = PTR_ERR(path);
1169                         goto out;
1170                 }
1171
1172                 /*
1173                  * only first (depth 0 -> 1) produces free space;
1174                  * in all other cases we have to split the grown tree
1175                  */
1176                 depth = ext_depth(inode);
1177                 if (path[depth].p_hdr->eh_entries == path[depth].p_hdr->eh_max) {
1178                         /* now we need to split */
1179                         goto repeat;
1180                 }
1181         }
1182
1183 out:
1184         return err;
1185 }
1186
1187 /*
1188  * search the closest allocated block to the left for *logical
1189  * and returns it at @logical + it's physical address at @phys
1190  * if *logical is the smallest allocated block, the function
1191  * returns 0 at @phys
1192  * return value contains 0 (success) or error code
1193  */
1194 int
1195 ext4_ext_search_left(struct inode *inode, struct ext4_ext_path *path,
1196                         ext4_lblk_t *logical, ext4_fsblk_t *phys)
1197 {
1198         struct ext4_extent_idx *ix;
1199         struct ext4_extent *ex;
1200         int depth, ee_len;
1201
1202         BUG_ON(path == NULL);
1203         depth = path->p_depth;
1204         *phys = 0;
1205
1206         if (depth == 0 && path->p_ext == NULL)
1207                 return 0;
1208
1209         /* usually extent in the path covers blocks smaller
1210          * then *logical, but it can be that extent is the
1211          * first one in the file */
1212
1213         ex = path[depth].p_ext;
1214         ee_len = ext4_ext_get_actual_len(ex);
1215         if (*logical < le32_to_cpu(ex->ee_block)) {
1216                 BUG_ON(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex);
1217                 while (--depth >= 0) {
1218                         ix = path[depth].p_idx;
1219                         BUG_ON(ix != EXT_FIRST_INDEX(path[depth].p_hdr));
1220                 }
1221                 return 0;
1222         }
1223
1224         BUG_ON(*logical < (le32_to_cpu(ex->ee_block) + ee_len));
1225
1226         *logical = le32_to_cpu(ex->ee_block) + ee_len - 1;
1227         *phys = ext_pblock(ex) + ee_len - 1;
1228         return 0;
1229 }
1230
1231 /*
1232  * search the closest allocated block to the right for *logical
1233  * and returns it at @logical + it's physical address at @phys
1234  * if *logical is the smallest allocated block, the function
1235  * returns 0 at @phys
1236  * return value contains 0 (success) or error code
1237  */
1238 int
1239 ext4_ext_search_right(struct inode *inode, struct ext4_ext_path *path,
1240                         ext4_lblk_t *logical, ext4_fsblk_t *phys)
1241 {
1242         struct buffer_head *bh = NULL;
1243         struct ext4_extent_header *eh;
1244         struct ext4_extent_idx *ix;
1245         struct ext4_extent *ex;
1246         ext4_fsblk_t block;
1247         int depth;      /* Note, NOT eh_depth; depth from top of tree */
1248         int ee_len;
1249
1250         BUG_ON(path == NULL);
1251         depth = path->p_depth;
1252         *phys = 0;
1253
1254         if (depth == 0 && path->p_ext == NULL)
1255                 return 0;
1256
1257         /* usually extent in the path covers blocks smaller
1258          * then *logical, but it can be that extent is the
1259          * first one in the file */
1260
1261         ex = path[depth].p_ext;
1262         ee_len = ext4_ext_get_actual_len(ex);
1263         if (*logical < le32_to_cpu(ex->ee_block)) {
1264                 BUG_ON(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex);
1265                 while (--depth >= 0) {
1266                         ix = path[depth].p_idx;
1267                         BUG_ON(ix != EXT_FIRST_INDEX(path[depth].p_hdr));
1268                 }
1269                 *logical = le32_to_cpu(ex->ee_block);
1270                 *phys = ext_pblock(ex);
1271                 return 0;
1272         }
1273
1274         BUG_ON(*logical < (le32_to_cpu(ex->ee_block) + ee_len));
1275
1276         if (ex != EXT_LAST_EXTENT(path[depth].p_hdr)) {
1277                 /* next allocated block in this leaf */
1278                 ex++;
1279                 *logical = le32_to_cpu(ex->ee_block);
1280                 *phys = ext_pblock(ex);
1281                 return 0;
1282         }
1283
1284         /* go up and search for index to the right */
1285         while (--depth >= 0) {
1286                 ix = path[depth].p_idx;
1287                 if (ix != EXT_LAST_INDEX(path[depth].p_hdr))
1288                         goto got_index;
1289         }
1290
1291         /* we've gone up to the root and found no index to the right */
1292         return 0;
1293
1294 got_index:
1295         /* we've found index to the right, let's
1296          * follow it and find the closest allocated
1297          * block to the right */
1298         ix++;
1299         block = idx_pblock(ix);
1300         while (++depth < path->p_depth) {
1301                 bh = sb_bread(inode->i_sb, block);
1302                 if (bh == NULL)
1303                         return -EIO;
1304                 eh = ext_block_hdr(bh);
1305                 /* subtract from p_depth to get proper eh_depth */
1306                 if (ext4_ext_check(inode, eh, path->p_depth - depth)) {
1307                         put_bh(bh);
1308                         return -EIO;
1309                 }
1310                 ix = EXT_FIRST_INDEX(eh);
1311                 block = idx_pblock(ix);
1312                 put_bh(bh);
1313         }
1314
1315         bh = sb_bread(inode->i_sb, block);
1316         if (bh == NULL)
1317                 return -EIO;
1318         eh = ext_block_hdr(bh);
1319         if (ext4_ext_check(inode, eh, path->p_depth - depth)) {
1320                 put_bh(bh);
1321                 return -EIO;
1322         }
1323         ex = EXT_FIRST_EXTENT(eh);
1324         *logical = le32_to_cpu(ex->ee_block);
1325         *phys = ext_pblock(ex);
1326         put_bh(bh);
1327         return 0;
1328 }
1329
1330 /*
1331  * ext4_ext_next_allocated_block:
1332  * returns allocated block in subsequent extent or EXT_MAX_BLOCK.
1333  * NOTE: it considers block number from index entry as
1334  * allocated block. Thus, index entries have to be consistent
1335  * with leaves.
1336  */
1337 static ext4_lblk_t
1338 ext4_ext_next_allocated_block(struct ext4_ext_path *path)
1339 {
1340         int depth;
1341
1342         BUG_ON(path == NULL);
1343         depth = path->p_depth;
1344
1345         if (depth == 0 && path->p_ext == NULL)
1346                 return EXT_MAX_BLOCK;
1347
1348         while (depth >= 0) {
1349                 if (depth == path->p_depth) {
1350                         /* leaf */
1351                         if (path[depth].p_ext !=
1352                                         EXT_LAST_EXTENT(path[depth].p_hdr))
1353                           return le32_to_cpu(path[depth].p_ext[1].ee_block);
1354                 } else {
1355                         /* index */
1356                         if (path[depth].p_idx !=
1357                                         EXT_LAST_INDEX(path[depth].p_hdr))
1358                           return le32_to_cpu(path[depth].p_idx[1].ei_block);
1359                 }
1360                 depth--;
1361         }
1362
1363         return EXT_MAX_BLOCK;
1364 }
1365
1366 /*
1367  * ext4_ext_next_leaf_block:
1368  * returns first allocated block from next leaf or EXT_MAX_BLOCK
1369  */
1370 static ext4_lblk_t ext4_ext_next_leaf_block(struct inode *inode,
1371                                         struct ext4_ext_path *path)
1372 {
1373         int depth;
1374
1375         BUG_ON(path == NULL);
1376         depth = path->p_depth;
1377
1378         /* zero-tree has no leaf blocks at all */
1379         if (depth == 0)
1380                 return EXT_MAX_BLOCK;
1381
1382         /* go to index block */
1383         depth--;
1384
1385         while (depth >= 0) {
1386                 if (path[depth].p_idx !=
1387                                 EXT_LAST_INDEX(path[depth].p_hdr))
1388                         return (ext4_lblk_t)
1389                                 le32_to_cpu(path[depth].p_idx[1].ei_block);
1390                 depth--;
1391         }
1392
1393         return EXT_MAX_BLOCK;
1394 }
1395
1396 /*
1397  * ext4_ext_correct_indexes:
1398  * if leaf gets modified and modified extent is first in the leaf,
1399  * then we have to correct all indexes above.
1400  * TODO: do we need to correct tree in all cases?
1401  */
1402 static int ext4_ext_correct_indexes(handle_t *handle, struct inode *inode,
1403                                 struct ext4_ext_path *path)
1404 {
1405         struct ext4_extent_header *eh;
1406         int depth = ext_depth(inode);
1407         struct ext4_extent *ex;
1408         __le32 border;
1409         int k, err = 0;
1410
1411         eh = path[depth].p_hdr;
1412         ex = path[depth].p_ext;
1413         BUG_ON(ex == NULL);
1414         BUG_ON(eh == NULL);
1415
1416         if (depth == 0) {
1417                 /* there is no tree at all */
1418                 return 0;
1419         }
1420
1421         if (ex != EXT_FIRST_EXTENT(eh)) {
1422                 /* we correct tree if first leaf got modified only */
1423                 return 0;
1424         }
1425
1426         /*
1427          * TODO: we need correction if border is smaller than current one
1428          */
1429         k = depth - 1;
1430         border = path[depth].p_ext->ee_block;
1431         err = ext4_ext_get_access(handle, inode, path + k);
1432         if (err)
1433                 return err;
1434         path[k].p_idx->ei_block = border;
1435         err = ext4_ext_dirty(handle, inode, path + k);
1436         if (err)
1437                 return err;
1438
1439         while (k--) {
1440                 /* change all left-side indexes */
1441                 if (path[k+1].p_idx != EXT_FIRST_INDEX(path[k+1].p_hdr))
1442                         break;
1443                 err = ext4_ext_get_access(handle, inode, path + k);
1444                 if (err)
1445                         break;
1446                 path[k].p_idx->ei_block = border;
1447                 err = ext4_ext_dirty(handle, inode, path + k);
1448                 if (err)
1449                         break;
1450         }
1451
1452         return err;
1453 }
1454
1455 int
1456 ext4_can_extents_be_merged(struct inode *inode, struct ext4_extent *ex1,
1457                                 struct ext4_extent *ex2)
1458 {
1459         unsigned short ext1_ee_len, ext2_ee_len, max_len;
1460
1461         /*
1462          * Make sure that either both extents are uninitialized, or
1463          * both are _not_.
1464          */
1465         if (ext4_ext_is_uninitialized(ex1) ^ ext4_ext_is_uninitialized(ex2))
1466                 return 0;
1467
1468         if (ext4_ext_is_uninitialized(ex1))
1469                 max_len = EXT_UNINIT_MAX_LEN;
1470         else
1471                 max_len = EXT_INIT_MAX_LEN;
1472
1473         ext1_ee_len = ext4_ext_get_actual_len(ex1);
1474         ext2_ee_len = ext4_ext_get_actual_len(ex2);
1475
1476         if (le32_to_cpu(ex1->ee_block) + ext1_ee_len !=
1477                         le32_to_cpu(ex2->ee_block))
1478                 return 0;
1479
1480         /*
1481          * To allow future support for preallocated extents to be added
1482          * as an RO_COMPAT feature, refuse to merge to extents if
1483          * this can result in the top bit of ee_len being set.
1484          */
1485         if (ext1_ee_len + ext2_ee_len > max_len)
1486                 return 0;
1487 #ifdef AGGRESSIVE_TEST
1488         if (ext1_ee_len >= 4)
1489                 return 0;
1490 #endif
1491
1492         if (ext_pblock(ex1) + ext1_ee_len == ext_pblock(ex2))
1493                 return 1;
1494         return 0;
1495 }
1496
1497 /*
1498  * This function tries to merge the "ex" extent to the next extent in the tree.
1499  * It always tries to merge towards right. If you want to merge towards
1500  * left, pass "ex - 1" as argument instead of "ex".
1501  * Returns 0 if the extents (ex and ex+1) were _not_ merged and returns
1502  * 1 if they got merged.
1503  */
1504 int ext4_ext_try_to_merge(struct inode *inode,
1505                           struct ext4_ext_path *path,
1506                           struct ext4_extent *ex)
1507 {
1508         struct ext4_extent_header *eh;
1509         unsigned int depth, len;
1510         int merge_done = 0;
1511         int uninitialized = 0;
1512
1513         depth = ext_depth(inode);
1514         BUG_ON(path[depth].p_hdr == NULL);
1515         eh = path[depth].p_hdr;
1516
1517         while (ex < EXT_LAST_EXTENT(eh)) {
1518                 if (!ext4_can_extents_be_merged(inode, ex, ex + 1))
1519                         break;
1520                 /* merge with next extent! */
1521                 if (ext4_ext_is_uninitialized(ex))
1522                         uninitialized = 1;
1523                 ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
1524                                 + ext4_ext_get_actual_len(ex + 1));
1525                 if (uninitialized)
1526                         ext4_ext_mark_uninitialized(ex);
1527
1528                 if (ex + 1 < EXT_LAST_EXTENT(eh)) {
1529                         len = (EXT_LAST_EXTENT(eh) - ex - 1)
1530                                 * sizeof(struct ext4_extent);
1531                         memmove(ex + 1, ex + 2, len);
1532                 }
1533                 le16_add_cpu(&eh->eh_entries, -1);
1534                 merge_done = 1;
1535                 WARN_ON(eh->eh_entries == 0);
1536                 if (!eh->eh_entries)
1537                         ext4_error(inode->i_sb, "ext4_ext_try_to_merge",
1538                            "inode#%lu, eh->eh_entries = 0!", inode->i_ino);
1539         }
1540
1541         return merge_done;
1542 }
1543
1544 /*
1545  * check if a portion of the "newext" extent overlaps with an
1546  * existing extent.
1547  *
1548  * If there is an overlap discovered, it updates the length of the newext
1549  * such that there will be no overlap, and then returns 1.
1550  * If there is no overlap found, it returns 0.
1551  */
1552 unsigned int ext4_ext_check_overlap(struct inode *inode,
1553                                     struct ext4_extent *newext,
1554                                     struct ext4_ext_path *path)
1555 {
1556         ext4_lblk_t b1, b2;
1557         unsigned int depth, len1;
1558         unsigned int ret = 0;
1559
1560         b1 = le32_to_cpu(newext->ee_block);
1561         len1 = ext4_ext_get_actual_len(newext);
1562         depth = ext_depth(inode);
1563         if (!path[depth].p_ext)
1564                 goto out;
1565         b2 = le32_to_cpu(path[depth].p_ext->ee_block);
1566
1567         /*
1568          * get the next allocated block if the extent in the path
1569          * is before the requested block(s)
1570          */
1571         if (b2 < b1) {
1572                 b2 = ext4_ext_next_allocated_block(path);
1573                 if (b2 == EXT_MAX_BLOCK)
1574                         goto out;
1575         }
1576
1577         /* check for wrap through zero on extent logical start block*/
1578         if (b1 + len1 < b1) {
1579                 len1 = EXT_MAX_BLOCK - b1;
1580                 newext->ee_len = cpu_to_le16(len1);
1581                 ret = 1;
1582         }
1583
1584         /* check for overlap */
1585         if (b1 + len1 > b2) {
1586                 newext->ee_len = cpu_to_le16(b2 - b1);
1587                 ret = 1;
1588         }
1589 out:
1590         return ret;
1591 }
1592
1593 /*
1594  * ext4_ext_insert_extent:
1595  * tries to merge requsted extent into the existing extent or
1596  * inserts requested extent as new one into the tree,
1597  * creating new leaf in the no-space case.
1598  */
1599 int ext4_ext_insert_extent(handle_t *handle, struct inode *inode,
1600                                 struct ext4_ext_path *path,
1601                                 struct ext4_extent *newext, int flag)
1602 {
1603         struct ext4_extent_header *eh;
1604         struct ext4_extent *ex, *fex;
1605         struct ext4_extent *nearex; /* nearest extent */
1606         struct ext4_ext_path *npath = NULL;
1607         int depth, len, err;
1608         ext4_lblk_t next;
1609         unsigned uninitialized = 0;
1610
1611         BUG_ON(ext4_ext_get_actual_len(newext) == 0);
1612         depth = ext_depth(inode);
1613         ex = path[depth].p_ext;
1614         BUG_ON(path[depth].p_hdr == NULL);
1615
1616         /* try to insert block into found extent and return */
1617         if (ex && (flag != EXT4_GET_BLOCKS_DIO_CREATE_EXT)
1618                 && ext4_can_extents_be_merged(inode, ex, newext)) {
1619                 ext_debug("append [%d]%d block to %d:[%d]%d (from %llu)\n",
1620                                 ext4_ext_is_uninitialized(newext),
1621                                 ext4_ext_get_actual_len(newext),
1622                                 le32_to_cpu(ex->ee_block),
1623                                 ext4_ext_is_uninitialized(ex),
1624                                 ext4_ext_get_actual_len(ex), ext_pblock(ex));
1625                 err = ext4_ext_get_access(handle, inode, path + depth);
1626                 if (err)
1627                         return err;
1628
1629                 /*
1630                  * ext4_can_extents_be_merged should have checked that either
1631                  * both extents are uninitialized, or both aren't. Thus we
1632                  * need to check only one of them here.
1633                  */
1634                 if (ext4_ext_is_uninitialized(ex))
1635                         uninitialized = 1;
1636                 ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
1637                                         + ext4_ext_get_actual_len(newext));
1638                 if (uninitialized)
1639                         ext4_ext_mark_uninitialized(ex);
1640                 eh = path[depth].p_hdr;
1641                 nearex = ex;
1642                 goto merge;
1643         }
1644
1645 repeat:
1646         depth = ext_depth(inode);
1647         eh = path[depth].p_hdr;
1648         if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max))
1649                 goto has_space;
1650
1651         /* probably next leaf has space for us? */
1652         fex = EXT_LAST_EXTENT(eh);
1653         next = ext4_ext_next_leaf_block(inode, path);
1654         if (le32_to_cpu(newext->ee_block) > le32_to_cpu(fex->ee_block)
1655             && next != EXT_MAX_BLOCK) {
1656                 ext_debug("next leaf block - %d\n", next);
1657                 BUG_ON(npath != NULL);
1658                 npath = ext4_ext_find_extent(inode, next, NULL);
1659                 if (IS_ERR(npath))
1660                         return PTR_ERR(npath);
1661                 BUG_ON(npath->p_depth != path->p_depth);
1662                 eh = npath[depth].p_hdr;
1663                 if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max)) {
1664                         ext_debug("next leaf isnt full(%d)\n",
1665                                   le16_to_cpu(eh->eh_entries));
1666                         path = npath;
1667                         goto repeat;
1668                 }
1669                 ext_debug("next leaf has no free space(%d,%d)\n",
1670                           le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
1671         }
1672
1673         /*
1674          * There is no free space in the found leaf.
1675          * We're gonna add a new leaf in the tree.
1676          */
1677         err = ext4_ext_create_new_leaf(handle, inode, path, newext);
1678         if (err)
1679                 goto cleanup;
1680         depth = ext_depth(inode);
1681         eh = path[depth].p_hdr;
1682
1683 has_space:
1684         nearex = path[depth].p_ext;
1685
1686         err = ext4_ext_get_access(handle, inode, path + depth);
1687         if (err)
1688                 goto cleanup;
1689
1690         if (!nearex) {
1691                 /* there is no extent in this leaf, create first one */
1692                 ext_debug("first extent in the leaf: %d:%llu:[%d]%d\n",
1693                                 le32_to_cpu(newext->ee_block),
1694                                 ext_pblock(newext),
1695                                 ext4_ext_is_uninitialized(newext),
1696                                 ext4_ext_get_actual_len(newext));
1697                 path[depth].p_ext = EXT_FIRST_EXTENT(eh);
1698         } else if (le32_to_cpu(newext->ee_block)
1699                            > le32_to_cpu(nearex->ee_block)) {
1700 /*              BUG_ON(newext->ee_block == nearex->ee_block); */
1701                 if (nearex != EXT_LAST_EXTENT(eh)) {
1702                         len = EXT_MAX_EXTENT(eh) - nearex;
1703                         len = (len - 1) * sizeof(struct ext4_extent);
1704                         len = len < 0 ? 0 : len;
1705                         ext_debug("insert %d:%llu:[%d]%d after: nearest 0x%p, "
1706                                         "move %d from 0x%p to 0x%p\n",
1707                                         le32_to_cpu(newext->ee_block),
1708                                         ext_pblock(newext),
1709                                         ext4_ext_is_uninitialized(newext),
1710                                         ext4_ext_get_actual_len(newext),
1711                                         nearex, len, nearex + 1, nearex + 2);
1712                         memmove(nearex + 2, nearex + 1, len);
1713                 }
1714                 path[depth].p_ext = nearex + 1;
1715         } else {
1716                 BUG_ON(newext->ee_block == nearex->ee_block);
1717                 len = (EXT_MAX_EXTENT(eh) - nearex) * sizeof(struct ext4_extent);
1718                 len = len < 0 ? 0 : len;
1719                 ext_debug("insert %d:%llu:[%d]%d before: nearest 0x%p, "
1720                                 "move %d from 0x%p to 0x%p\n",
1721                                 le32_to_cpu(newext->ee_block),
1722                                 ext_pblock(newext),
1723                                 ext4_ext_is_uninitialized(newext),
1724                                 ext4_ext_get_actual_len(newext),
1725                                 nearex, len, nearex + 1, nearex + 2);
1726                 memmove(nearex + 1, nearex, len);
1727                 path[depth].p_ext = nearex;
1728         }
1729
1730         le16_add_cpu(&eh->eh_entries, 1);
1731         nearex = path[depth].p_ext;
1732         nearex->ee_block = newext->ee_block;
1733         ext4_ext_store_pblock(nearex, ext_pblock(newext));
1734         nearex->ee_len = newext->ee_len;
1735
1736 merge:
1737         /* try to merge extents to the right */
1738         if (flag != EXT4_GET_BLOCKS_DIO_CREATE_EXT)
1739                 ext4_ext_try_to_merge(inode, path, nearex);
1740
1741         /* try to merge extents to the left */
1742
1743         /* time to correct all indexes above */
1744         err = ext4_ext_correct_indexes(handle, inode, path);
1745         if (err)
1746                 goto cleanup;
1747
1748         err = ext4_ext_dirty(handle, inode, path + depth);
1749
1750 cleanup:
1751         if (npath) {
1752                 ext4_ext_drop_refs(npath);
1753                 kfree(npath);
1754         }
1755         ext4_ext_invalidate_cache(inode);
1756         return err;
1757 }
1758
1759 int ext4_ext_walk_space(struct inode *inode, ext4_lblk_t block,
1760                         ext4_lblk_t num, ext_prepare_callback func,
1761                         void *cbdata)
1762 {
1763         struct ext4_ext_path *path = NULL;
1764         struct ext4_ext_cache cbex;
1765         struct ext4_extent *ex;
1766         ext4_lblk_t next, start = 0, end = 0;
1767         ext4_lblk_t last = block + num;
1768         int depth, exists, err = 0;
1769
1770         BUG_ON(func == NULL);
1771         BUG_ON(inode == NULL);
1772
1773         while (block < last && block != EXT_MAX_BLOCK) {
1774                 num = last - block;
1775                 /* find extent for this block */
1776                 down_read(&EXT4_I(inode)->i_data_sem);
1777                 path = ext4_ext_find_extent(inode, block, path);
1778                 up_read(&EXT4_I(inode)->i_data_sem);
1779                 if (IS_ERR(path)) {
1780                         err = PTR_ERR(path);
1781                         path = NULL;
1782                         break;
1783                 }
1784
1785                 depth = ext_depth(inode);
1786                 BUG_ON(path[depth].p_hdr == NULL);
1787                 ex = path[depth].p_ext;
1788                 next = ext4_ext_next_allocated_block(path);
1789
1790                 exists = 0;
1791                 if (!ex) {
1792                         /* there is no extent yet, so try to allocate
1793                          * all requested space */
1794                         start = block;
1795                         end = block + num;
1796                 } else if (le32_to_cpu(ex->ee_block) > block) {
1797                         /* need to allocate space before found extent */
1798                         start = block;
1799                         end = le32_to_cpu(ex->ee_block);
1800                         if (block + num < end)
1801                                 end = block + num;
1802                 } else if (block >= le32_to_cpu(ex->ee_block)
1803                                         + ext4_ext_get_actual_len(ex)) {
1804                         /* need to allocate space after found extent */
1805                         start = block;
1806                         end = block + num;
1807                         if (end >= next)
1808                                 end = next;
1809                 } else if (block >= le32_to_cpu(ex->ee_block)) {
1810                         /*
1811                          * some part of requested space is covered
1812                          * by found extent
1813                          */
1814                         start = block;
1815                         end = le32_to_cpu(ex->ee_block)
1816                                 + ext4_ext_get_actual_len(ex);
1817                         if (block + num < end)
1818                                 end = block + num;
1819                         exists = 1;
1820                 } else {
1821                         BUG();
1822                 }
1823                 BUG_ON(end <= start);
1824
1825                 if (!exists) {
1826                         cbex.ec_block = start;
1827                         cbex.ec_len = end - start;
1828                         cbex.ec_start = 0;
1829                         cbex.ec_type = EXT4_EXT_CACHE_GAP;
1830                 } else {
1831                         cbex.ec_block = le32_to_cpu(ex->ee_block);
1832                         cbex.ec_len = ext4_ext_get_actual_len(ex);
1833                         cbex.ec_start = ext_pblock(ex);
1834                         cbex.ec_type = EXT4_EXT_CACHE_EXTENT;
1835                 }
1836
1837                 BUG_ON(cbex.ec_len == 0);
1838                 err = func(inode, path, &cbex, ex, cbdata);
1839                 ext4_ext_drop_refs(path);
1840
1841                 if (err < 0)
1842                         break;
1843
1844                 if (err == EXT_REPEAT)
1845                         continue;
1846                 else if (err == EXT_BREAK) {
1847                         err = 0;
1848                         break;
1849                 }
1850
1851                 if (ext_depth(inode) != depth) {
1852                         /* depth was changed. we have to realloc path */
1853                         kfree(path);
1854                         path = NULL;
1855                 }
1856
1857                 block = cbex.ec_block + cbex.ec_len;
1858         }
1859
1860         if (path) {
1861                 ext4_ext_drop_refs(path);
1862                 kfree(path);
1863         }
1864
1865         return err;
1866 }
1867
1868 static void
1869 ext4_ext_put_in_cache(struct inode *inode, ext4_lblk_t block,
1870                         __u32 len, ext4_fsblk_t start, int type)
1871 {
1872         struct ext4_ext_cache *cex;
1873         BUG_ON(len == 0);
1874         spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1875         cex = &EXT4_I(inode)->i_cached_extent;
1876         cex->ec_type = type;
1877         cex->ec_block = block;
1878         cex->ec_len = len;
1879         cex->ec_start = start;
1880         spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1881 }
1882
1883 /*
1884  * ext4_ext_put_gap_in_cache:
1885  * calculate boundaries of the gap that the requested block fits into
1886  * and cache this gap
1887  */
1888 static void
1889 ext4_ext_put_gap_in_cache(struct inode *inode, struct ext4_ext_path *path,
1890                                 ext4_lblk_t block)
1891 {
1892         int depth = ext_depth(inode);
1893         unsigned long len;
1894         ext4_lblk_t lblock;
1895         struct ext4_extent *ex;
1896
1897         ex = path[depth].p_ext;
1898         if (ex == NULL) {
1899                 /* there is no extent yet, so gap is [0;-] */
1900                 lblock = 0;
1901                 len = EXT_MAX_BLOCK;
1902                 ext_debug("cache gap(whole file):");
1903         } else if (block < le32_to_cpu(ex->ee_block)) {
1904                 lblock = block;
1905                 len = le32_to_cpu(ex->ee_block) - block;
1906                 ext_debug("cache gap(before): %u [%u:%u]",
1907                                 block,
1908                                 le32_to_cpu(ex->ee_block),
1909                                  ext4_ext_get_actual_len(ex));
1910         } else if (block >= le32_to_cpu(ex->ee_block)
1911                         + ext4_ext_get_actual_len(ex)) {
1912                 ext4_lblk_t next;
1913                 lblock = le32_to_cpu(ex->ee_block)
1914                         + ext4_ext_get_actual_len(ex);
1915
1916                 next = ext4_ext_next_allocated_block(path);
1917                 ext_debug("cache gap(after): [%u:%u] %u",
1918                                 le32_to_cpu(ex->ee_block),
1919                                 ext4_ext_get_actual_len(ex),
1920                                 block);
1921                 BUG_ON(next == lblock);
1922                 len = next - lblock;
1923         } else {
1924                 lblock = len = 0;
1925                 BUG();
1926         }
1927
1928         ext_debug(" -> %u:%lu\n", lblock, len);
1929         ext4_ext_put_in_cache(inode, lblock, len, 0, EXT4_EXT_CACHE_GAP);
1930 }
1931
1932 static int
1933 ext4_ext_in_cache(struct inode *inode, ext4_lblk_t block,
1934                         struct ext4_extent *ex)
1935 {
1936         struct ext4_ext_cache *cex;
1937         int ret = EXT4_EXT_CACHE_NO;
1938
1939         /* 
1940          * We borrow i_block_reservation_lock to protect i_cached_extent
1941          */
1942         spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1943         cex = &EXT4_I(inode)->i_cached_extent;
1944
1945         /* has cache valid data? */
1946         if (cex->ec_type == EXT4_EXT_CACHE_NO)
1947                 goto errout;
1948
1949         BUG_ON(cex->ec_type != EXT4_EXT_CACHE_GAP &&
1950                         cex->ec_type != EXT4_EXT_CACHE_EXTENT);
1951         if (in_range(block, cex->ec_block, cex->ec_len)) {
1952                 ex->ee_block = cpu_to_le32(cex->ec_block);
1953                 ext4_ext_store_pblock(ex, cex->ec_start);
1954                 ex->ee_len = cpu_to_le16(cex->ec_len);
1955                 ext_debug("%u cached by %u:%u:%llu\n",
1956                                 block,
1957                                 cex->ec_block, cex->ec_len, cex->ec_start);
1958                 ret = cex->ec_type;
1959         }
1960 errout:
1961         spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1962         return ret;
1963 }
1964
1965 /*
1966  * ext4_ext_rm_idx:
1967  * removes index from the index block.
1968  * It's used in truncate case only, thus all requests are for
1969  * last index in the block only.
1970  */
1971 static int ext4_ext_rm_idx(handle_t *handle, struct inode *inode,
1972                         struct ext4_ext_path *path)
1973 {
1974         struct buffer_head *bh;
1975         int err;
1976         ext4_fsblk_t leaf;
1977
1978         /* free index block */
1979         path--;
1980         leaf = idx_pblock(path->p_idx);
1981         BUG_ON(path->p_hdr->eh_entries == 0);
1982         err = ext4_ext_get_access(handle, inode, path);
1983         if (err)
1984                 return err;
1985         le16_add_cpu(&path->p_hdr->eh_entries, -1);
1986         err = ext4_ext_dirty(handle, inode, path);
1987         if (err)
1988                 return err;
1989         ext_debug("index is empty, remove it, free block %llu\n", leaf);
1990         bh = sb_find_get_block(inode->i_sb, leaf);
1991         ext4_forget(handle, 1, inode, bh, leaf);
1992         ext4_free_blocks(handle, inode, leaf, 1, 1);
1993         return err;
1994 }
1995
1996 /*
1997  * ext4_ext_calc_credits_for_single_extent:
1998  * This routine returns max. credits that needed to insert an extent
1999  * to the extent tree.
2000  * When pass the actual path, the caller should calculate credits
2001  * under i_data_sem.
2002  */
2003 int ext4_ext_calc_credits_for_single_extent(struct inode *inode, int nrblocks,
2004                                                 struct ext4_ext_path *path)
2005 {
2006         if (path) {
2007                 int depth = ext_depth(inode);
2008                 int ret = 0;
2009
2010                 /* probably there is space in leaf? */
2011                 if (le16_to_cpu(path[depth].p_hdr->eh_entries)
2012                                 < le16_to_cpu(path[depth].p_hdr->eh_max)) {
2013
2014                         /*
2015                          *  There are some space in the leaf tree, no
2016                          *  need to account for leaf block credit
2017                          *
2018                          *  bitmaps and block group descriptor blocks
2019                          *  and other metadat blocks still need to be
2020                          *  accounted.
2021                          */
2022                         /* 1 bitmap, 1 block group descriptor */
2023                         ret = 2 + EXT4_META_TRANS_BLOCKS(inode->i_sb);
2024                         return ret;
2025                 }
2026         }
2027
2028         return ext4_chunk_trans_blocks(inode, nrblocks);
2029 }
2030
2031 /*
2032  * How many index/leaf blocks need to change/allocate to modify nrblocks?
2033  *
2034  * if nrblocks are fit in a single extent (chunk flag is 1), then
2035  * in the worse case, each tree level index/leaf need to be changed
2036  * if the tree split due to insert a new extent, then the old tree
2037  * index/leaf need to be updated too
2038  *
2039  * If the nrblocks are discontiguous, they could cause
2040  * the whole tree split more than once, but this is really rare.
2041  */
2042 int ext4_ext_index_trans_blocks(struct inode *inode, int nrblocks, int chunk)
2043 {
2044         int index;
2045         int depth = ext_depth(inode);
2046
2047         if (chunk)
2048                 index = depth * 2;
2049         else
2050                 index = depth * 3;
2051
2052         return index;
2053 }
2054
2055 static int ext4_remove_blocks(handle_t *handle, struct inode *inode,
2056                                 struct ext4_extent *ex,
2057                                 ext4_lblk_t from, ext4_lblk_t to)
2058 {
2059         struct buffer_head *bh;
2060         unsigned short ee_len =  ext4_ext_get_actual_len(ex);
2061         int i, metadata = 0;
2062
2063         if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode))
2064                 metadata = 1;
2065 #ifdef EXTENTS_STATS
2066         {
2067                 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2068                 spin_lock(&sbi->s_ext_stats_lock);
2069                 sbi->s_ext_blocks += ee_len;
2070                 sbi->s_ext_extents++;
2071                 if (ee_len < sbi->s_ext_min)
2072                         sbi->s_ext_min = ee_len;
2073                 if (ee_len > sbi->s_ext_max)
2074                         sbi->s_ext_max = ee_len;
2075                 if (ext_depth(inode) > sbi->s_depth_max)
2076                         sbi->s_depth_max = ext_depth(inode);
2077                 spin_unlock(&sbi->s_ext_stats_lock);
2078         }
2079 #endif
2080         if (from >= le32_to_cpu(ex->ee_block)
2081             && to == le32_to_cpu(ex->ee_block) + ee_len - 1) {
2082                 /* tail removal */
2083                 ext4_lblk_t num;
2084                 ext4_fsblk_t start;
2085
2086                 num = le32_to_cpu(ex->ee_block) + ee_len - from;
2087                 start = ext_pblock(ex) + ee_len - num;
2088                 ext_debug("free last %u blocks starting %llu\n", num, start);
2089                 for (i = 0; i < num; i++) {
2090                         bh = sb_find_get_block(inode->i_sb, start + i);
2091                         ext4_forget(handle, metadata, inode, bh, start + i);
2092                 }
2093                 ext4_free_blocks(handle, inode, start, num, metadata);
2094         } else if (from == le32_to_cpu(ex->ee_block)
2095                    && to <= le32_to_cpu(ex->ee_block) + ee_len - 1) {
2096                 printk(KERN_INFO "strange request: removal %u-%u from %u:%u\n",
2097                         from, to, le32_to_cpu(ex->ee_block), ee_len);
2098         } else {
2099                 printk(KERN_INFO "strange request: removal(2) "
2100                                 "%u-%u from %u:%u\n",
2101                                 from, to, le32_to_cpu(ex->ee_block), ee_len);
2102         }
2103         return 0;
2104 }
2105
2106 static int
2107 ext4_ext_rm_leaf(handle_t *handle, struct inode *inode,
2108                 struct ext4_ext_path *path, ext4_lblk_t start)
2109 {
2110         int err = 0, correct_index = 0;
2111         int depth = ext_depth(inode), credits;
2112         struct ext4_extent_header *eh;
2113         ext4_lblk_t a, b, block;
2114         unsigned num;
2115         ext4_lblk_t ex_ee_block;
2116         unsigned short ex_ee_len;
2117         unsigned uninitialized = 0;
2118         struct ext4_extent *ex;
2119
2120         /* the header must be checked already in ext4_ext_remove_space() */
2121         ext_debug("truncate since %u in leaf\n", start);
2122         if (!path[depth].p_hdr)
2123                 path[depth].p_hdr = ext_block_hdr(path[depth].p_bh);
2124         eh = path[depth].p_hdr;
2125         BUG_ON(eh == NULL);
2126
2127         /* find where to start removing */
2128         ex = EXT_LAST_EXTENT(eh);
2129
2130         ex_ee_block = le32_to_cpu(ex->ee_block);
2131         ex_ee_len = ext4_ext_get_actual_len(ex);
2132
2133         while (ex >= EXT_FIRST_EXTENT(eh) &&
2134                         ex_ee_block + ex_ee_len > start) {
2135
2136                 if (ext4_ext_is_uninitialized(ex))
2137                         uninitialized = 1;
2138                 else
2139                         uninitialized = 0;
2140
2141                 ext_debug("remove ext %u:[%d]%d\n", ex_ee_block,
2142                          uninitialized, ex_ee_len);
2143                 path[depth].p_ext = ex;
2144
2145                 a = ex_ee_block > start ? ex_ee_block : start;
2146                 b = ex_ee_block + ex_ee_len - 1 < EXT_MAX_BLOCK ?
2147                         ex_ee_block + ex_ee_len - 1 : EXT_MAX_BLOCK;
2148
2149                 ext_debug("  border %u:%u\n", a, b);
2150
2151                 if (a != ex_ee_block && b != ex_ee_block + ex_ee_len - 1) {
2152                         block = 0;
2153                         num = 0;
2154                         BUG();
2155                 } else if (a != ex_ee_block) {
2156                         /* remove tail of the extent */
2157                         block = ex_ee_block;
2158                         num = a - block;
2159                 } else if (b != ex_ee_block + ex_ee_len - 1) {
2160                         /* remove head of the extent */
2161                         block = a;
2162                         num = b - a;
2163                         /* there is no "make a hole" API yet */
2164                         BUG();
2165                 } else {
2166                         /* remove whole extent: excellent! */
2167                         block = ex_ee_block;
2168                         num = 0;
2169                         BUG_ON(a != ex_ee_block);
2170                         BUG_ON(b != ex_ee_block + ex_ee_len - 1);
2171                 }
2172
2173                 /*
2174                  * 3 for leaf, sb, and inode plus 2 (bmap and group
2175                  * descriptor) for each block group; assume two block
2176                  * groups plus ex_ee_len/blocks_per_block_group for
2177                  * the worst case
2178                  */
2179                 credits = 7 + 2*(ex_ee_len/EXT4_BLOCKS_PER_GROUP(inode->i_sb));
2180                 if (ex == EXT_FIRST_EXTENT(eh)) {
2181                         correct_index = 1;
2182                         credits += (ext_depth(inode)) + 1;
2183                 }
2184                 credits += EXT4_MAXQUOTAS_TRANS_BLOCKS(inode->i_sb);
2185
2186                 err = ext4_ext_truncate_extend_restart(handle, inode, credits);
2187                 if (err)
2188                         goto out;
2189
2190                 err = ext4_ext_get_access(handle, inode, path + depth);
2191                 if (err)
2192                         goto out;
2193
2194                 err = ext4_remove_blocks(handle, inode, ex, a, b);
2195                 if (err)
2196                         goto out;
2197
2198                 if (num == 0) {
2199                         /* this extent is removed; mark slot entirely unused */
2200                         ext4_ext_store_pblock(ex, 0);
2201                         le16_add_cpu(&eh->eh_entries, -1);
2202                 }
2203
2204                 ex->ee_block = cpu_to_le32(block);
2205                 ex->ee_len = cpu_to_le16(num);
2206                 /*
2207                  * Do not mark uninitialized if all the blocks in the
2208                  * extent have been removed.
2209                  */
2210                 if (uninitialized && num)
2211                         ext4_ext_mark_uninitialized(ex);
2212
2213                 err = ext4_ext_dirty(handle, inode, path + depth);
2214                 if (err)
2215                         goto out;
2216
2217                 ext_debug("new extent: %u:%u:%llu\n", block, num,
2218                                 ext_pblock(ex));
2219                 ex--;
2220                 ex_ee_block = le32_to_cpu(ex->ee_block);
2221                 ex_ee_len = ext4_ext_get_actual_len(ex);
2222         }
2223
2224         if (correct_index && eh->eh_entries)
2225                 err = ext4_ext_correct_indexes(handle, inode, path);
2226
2227         /* if this leaf is free, then we should
2228          * remove it from index block above */
2229         if (err == 0 && eh->eh_entries == 0 && path[depth].p_bh != NULL)
2230                 err = ext4_ext_rm_idx(handle, inode, path + depth);
2231
2232 out:
2233         return err;
2234 }
2235
2236 /*
2237  * ext4_ext_more_to_rm:
2238  * returns 1 if current index has to be freed (even partial)
2239  */
2240 static int
2241 ext4_ext_more_to_rm(struct ext4_ext_path *path)
2242 {
2243         BUG_ON(path->p_idx == NULL);
2244
2245         if (path->p_idx < EXT_FIRST_INDEX(path->p_hdr))
2246                 return 0;
2247
2248         /*
2249          * if truncate on deeper level happened, it wasn't partial,
2250          * so we have to consider current index for truncation
2251          */
2252         if (le16_to_cpu(path->p_hdr->eh_entries) == path->p_block)
2253                 return 0;
2254         return 1;
2255 }
2256
2257 static int ext4_ext_remove_space(struct inode *inode, ext4_lblk_t start)
2258 {
2259         struct super_block *sb = inode->i_sb;
2260         int depth = ext_depth(inode);
2261         struct ext4_ext_path *path;
2262         handle_t *handle;
2263         int i, err;
2264
2265         ext_debug("truncate since %u\n", start);
2266
2267         /* probably first extent we're gonna free will be last in block */
2268         handle = ext4_journal_start(inode, depth + 1);
2269         if (IS_ERR(handle))
2270                 return PTR_ERR(handle);
2271
2272 again:
2273         ext4_ext_invalidate_cache(inode);
2274
2275         /*
2276          * We start scanning from right side, freeing all the blocks
2277          * after i_size and walking into the tree depth-wise.
2278          */
2279         depth = ext_depth(inode);
2280         path = kzalloc(sizeof(struct ext4_ext_path) * (depth + 1), GFP_NOFS);
2281         if (path == NULL) {
2282                 ext4_journal_stop(handle);
2283                 return -ENOMEM;
2284         }
2285         path[0].p_depth = depth;
2286         path[0].p_hdr = ext_inode_hdr(inode);
2287         if (ext4_ext_check(inode, path[0].p_hdr, depth)) {
2288                 err = -EIO;
2289                 goto out;
2290         }
2291         i = err = 0;
2292
2293         while (i >= 0 && err == 0) {
2294                 if (i == depth) {
2295                         /* this is leaf block */
2296                         err = ext4_ext_rm_leaf(handle, inode, path, start);
2297                         /* root level has p_bh == NULL, brelse() eats this */
2298                         brelse(path[i].p_bh);
2299                         path[i].p_bh = NULL;
2300                         i--;
2301                         continue;
2302                 }
2303
2304                 /* this is index block */
2305                 if (!path[i].p_hdr) {
2306                         ext_debug("initialize header\n");
2307                         path[i].p_hdr = ext_block_hdr(path[i].p_bh);
2308                 }
2309
2310                 if (!path[i].p_idx) {
2311                         /* this level hasn't been touched yet */
2312                         path[i].p_idx = EXT_LAST_INDEX(path[i].p_hdr);
2313                         path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries)+1;
2314                         ext_debug("init index ptr: hdr 0x%p, num %d\n",
2315                                   path[i].p_hdr,
2316                                   le16_to_cpu(path[i].p_hdr->eh_entries));
2317                 } else {
2318                         /* we were already here, see at next index */
2319                         path[i].p_idx--;
2320                 }
2321
2322                 ext_debug("level %d - index, first 0x%p, cur 0x%p\n",
2323                                 i, EXT_FIRST_INDEX(path[i].p_hdr),
2324                                 path[i].p_idx);
2325                 if (ext4_ext_more_to_rm(path + i)) {
2326                         struct buffer_head *bh;
2327                         /* go to the next level */
2328                         ext_debug("move to level %d (block %llu)\n",
2329                                   i + 1, idx_pblock(path[i].p_idx));
2330                         memset(path + i + 1, 0, sizeof(*path));
2331                         bh = sb_bread(sb, idx_pblock(path[i].p_idx));
2332                         if (!bh) {
2333                                 /* should we reset i_size? */
2334                                 err = -EIO;
2335                                 break;
2336                         }
2337                         if (WARN_ON(i + 1 > depth)) {
2338                                 err = -EIO;
2339                                 break;
2340                         }
2341                         if (ext4_ext_check(inode, ext_block_hdr(bh),
2342                                                         depth - i - 1)) {
2343                                 err = -EIO;
2344                                 break;
2345                         }
2346                         path[i + 1].p_bh = bh;
2347
2348                         /* save actual number of indexes since this
2349                          * number is changed at the next iteration */
2350                         path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries);
2351                         i++;
2352                 } else {
2353                         /* we finished processing this index, go up */
2354                         if (path[i].p_hdr->eh_entries == 0 && i > 0) {
2355                                 /* index is empty, remove it;
2356                                  * handle must be already prepared by the
2357                                  * truncatei_leaf() */
2358                                 err = ext4_ext_rm_idx(handle, inode, path + i);
2359                         }
2360                         /* root level has p_bh == NULL, brelse() eats this */
2361                         brelse(path[i].p_bh);
2362                         path[i].p_bh = NULL;
2363                         i--;
2364                         ext_debug("return to level %d\n", i);
2365                 }
2366         }
2367
2368         /* TODO: flexible tree reduction should be here */
2369         if (path->p_hdr->eh_entries == 0) {
2370                 /*
2371                  * truncate to zero freed all the tree,
2372                  * so we need to correct eh_depth
2373                  */
2374                 err = ext4_ext_get_access(handle, inode, path);
2375                 if (err == 0) {
2376                         ext_inode_hdr(inode)->eh_depth = 0;
2377                         ext_inode_hdr(inode)->eh_max =
2378                                 cpu_to_le16(ext4_ext_space_root(inode, 0));
2379                         err = ext4_ext_dirty(handle, inode, path);
2380                 }
2381         }
2382 out:
2383         ext4_ext_drop_refs(path);
2384         kfree(path);
2385         if (err == -EAGAIN)
2386                 goto again;
2387         ext4_journal_stop(handle);
2388
2389         return err;
2390 }
2391
2392 /*
2393  * called at mount time
2394  */
2395 void ext4_ext_init(struct super_block *sb)
2396 {
2397         /*
2398          * possible initialization would be here
2399          */
2400
2401         if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_EXTENTS)) {
2402 #if defined(AGGRESSIVE_TEST) || defined(CHECK_BINSEARCH) || defined(EXTENTS_STATS)
2403                 printk(KERN_INFO "EXT4-fs: file extents enabled");
2404 #ifdef AGGRESSIVE_TEST
2405                 printk(", aggressive tests");
2406 #endif
2407 #ifdef CHECK_BINSEARCH
2408                 printk(", check binsearch");
2409 #endif
2410 #ifdef EXTENTS_STATS
2411                 printk(", stats");
2412 #endif
2413                 printk("\n");
2414 #endif
2415 #ifdef EXTENTS_STATS
2416                 spin_lock_init(&EXT4_SB(sb)->s_ext_stats_lock);
2417                 EXT4_SB(sb)->s_ext_min = 1 << 30;
2418                 EXT4_SB(sb)->s_ext_max = 0;
2419 #endif
2420         }
2421 }
2422
2423 /*
2424  * called at umount time
2425  */
2426 void ext4_ext_release(struct super_block *sb)
2427 {
2428         if (!EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_EXTENTS))
2429                 return;
2430
2431 #ifdef EXTENTS_STATS
2432         if (EXT4_SB(sb)->s_ext_blocks && EXT4_SB(sb)->s_ext_extents) {
2433                 struct ext4_sb_info *sbi = EXT4_SB(sb);
2434                 printk(KERN_ERR "EXT4-fs: %lu blocks in %lu extents (%lu ave)\n",
2435                         sbi->s_ext_blocks, sbi->s_ext_extents,
2436                         sbi->s_ext_blocks / sbi->s_ext_extents);
2437                 printk(KERN_ERR "EXT4-fs: extents: %lu min, %lu max, max depth %lu\n",
2438                         sbi->s_ext_min, sbi->s_ext_max, sbi->s_depth_max);
2439         }
2440 #endif
2441 }
2442
2443 static void bi_complete(struct bio *bio, int error)
2444 {
2445         complete((struct completion *)bio->bi_private);
2446 }
2447
2448 /* FIXME!! we need to try to merge to left or right after zero-out  */
2449 static int ext4_ext_zeroout(struct inode *inode, struct ext4_extent *ex)
2450 {
2451         int ret;
2452         struct bio *bio;
2453         int blkbits, blocksize;
2454         sector_t ee_pblock;
2455         struct completion event;
2456         unsigned int ee_len, len, done, offset;
2457
2458
2459         blkbits   = inode->i_blkbits;
2460         blocksize = inode->i_sb->s_blocksize;
2461         ee_len    = ext4_ext_get_actual_len(ex);
2462         ee_pblock = ext_pblock(ex);
2463
2464         /* convert ee_pblock to 512 byte sectors */
2465         ee_pblock = ee_pblock << (blkbits - 9);
2466
2467         while (ee_len > 0) {
2468
2469                 if (ee_len > BIO_MAX_PAGES)
2470                         len = BIO_MAX_PAGES;
2471                 else
2472                         len = ee_len;
2473
2474                 bio = bio_alloc(GFP_NOIO, len);
2475                 if (!bio)
2476                         return -ENOMEM;
2477
2478                 bio->bi_sector = ee_pblock;
2479                 bio->bi_bdev   = inode->i_sb->s_bdev;
2480
2481                 done = 0;
2482                 offset = 0;
2483                 while (done < len) {
2484                         ret = bio_add_page(bio, ZERO_PAGE(0),
2485                                                         blocksize, offset);
2486                         if (ret != blocksize) {
2487                                 /*
2488                                  * We can't add any more pages because of
2489                                  * hardware limitations.  Start a new bio.
2490                                  */
2491                                 break;
2492                         }
2493                         done++;
2494                         offset += blocksize;
2495                         if (offset >= PAGE_CACHE_SIZE)
2496                                 offset = 0;
2497                 }
2498
2499                 init_completion(&event);
2500                 bio->bi_private = &event;
2501                 bio->bi_end_io = bi_complete;
2502                 submit_bio(WRITE, bio);
2503                 wait_for_completion(&event);
2504
2505                 if (!test_bit(BIO_UPTODATE, &bio->bi_flags)) {
2506                         bio_put(bio);
2507                         return -EIO;
2508                 }
2509                 bio_put(bio);
2510                 ee_len    -= done;
2511                 ee_pblock += done  << (blkbits - 9);
2512         }
2513         return 0;
2514 }
2515
2516 #define EXT4_EXT_ZERO_LEN 7
2517 /*
2518  * This function is called by ext4_ext_get_blocks() if someone tries to write
2519  * to an uninitialized extent. It may result in splitting the uninitialized
2520  * extent into multiple extents (upto three - one initialized and two
2521  * uninitialized).
2522  * There are three possibilities:
2523  *   a> There is no split required: Entire extent should be initialized
2524  *   b> Splits in two extents: Write is happening at either end of the extent
2525  *   c> Splits in three extents: Somone is writing in middle of the extent
2526  */
2527 static int ext4_ext_convert_to_initialized(handle_t *handle,
2528                                                 struct inode *inode,
2529                                                 struct ext4_ext_path *path,
2530                                                 ext4_lblk_t iblock,
2531                                                 unsigned int max_blocks)
2532 {
2533         struct ext4_extent *ex, newex, orig_ex;
2534         struct ext4_extent *ex1 = NULL;
2535         struct ext4_extent *ex2 = NULL;
2536         struct ext4_extent *ex3 = NULL;
2537         struct ext4_extent_header *eh;
2538         ext4_lblk_t ee_block, eof_block;
2539         unsigned int allocated, ee_len, depth;
2540         ext4_fsblk_t newblock;
2541         int err = 0;
2542         int ret = 0;
2543         int may_zeroout;
2544
2545         ext_debug("ext4_ext_convert_to_initialized: inode %lu, logical"
2546                 "block %llu, max_blocks %u\n", inode->i_ino,
2547                 (unsigned long long)iblock, max_blocks);
2548
2549         eof_block = (inode->i_size + inode->i_sb->s_blocksize - 1) >>
2550                 inode->i_sb->s_blocksize_bits;
2551         if (eof_block < iblock + max_blocks)
2552                 eof_block = iblock + max_blocks;
2553
2554         depth = ext_depth(inode);
2555         eh = path[depth].p_hdr;
2556         ex = path[depth].p_ext;
2557         ee_block = le32_to_cpu(ex->ee_block);
2558         ee_len = ext4_ext_get_actual_len(ex);
2559         allocated = ee_len - (iblock - ee_block);
2560         newblock = iblock - ee_block + ext_pblock(ex);
2561
2562         ex2 = ex;
2563         orig_ex.ee_block = ex->ee_block;
2564         orig_ex.ee_len   = cpu_to_le16(ee_len);
2565         ext4_ext_store_pblock(&orig_ex, ext_pblock(ex));
2566
2567         /*
2568          * It is safe to convert extent to initialized via explicit
2569          * zeroout only if extent is fully insde i_size or new_size.
2570          */
2571         may_zeroout = ee_block + ee_len <= eof_block;
2572
2573         err = ext4_ext_get_access(handle, inode, path + depth);
2574         if (err)
2575                 goto out;
2576         /* If extent has less than 2*EXT4_EXT_ZERO_LEN zerout directly */
2577         if (ee_len <= 2*EXT4_EXT_ZERO_LEN && may_zeroout) {
2578                 err =  ext4_ext_zeroout(inode, &orig_ex);
2579                 if (err)
2580                         goto fix_extent_len;
2581                 /* update the extent length and mark as initialized */
2582                 ex->ee_block = orig_ex.ee_block;
2583                 ex->ee_len   = orig_ex.ee_len;
2584                 ext4_ext_store_pblock(ex, ext_pblock(&orig_ex));
2585                 ext4_ext_dirty(handle, inode, path + depth);
2586                 /* zeroed the full extent */
2587                 return allocated;
2588         }
2589
2590         /* ex1: ee_block to iblock - 1 : uninitialized */
2591         if (iblock > ee_block) {
2592                 ex1 = ex;
2593                 ex1->ee_len = cpu_to_le16(iblock - ee_block);
2594                 ext4_ext_mark_uninitialized(ex1);
2595                 ex2 = &newex;
2596         }
2597         /*
2598          * for sanity, update the length of the ex2 extent before
2599          * we insert ex3, if ex1 is NULL. This is to avoid temporary
2600          * overlap of blocks.
2601          */
2602         if (!ex1 && allocated > max_blocks)
2603                 ex2->ee_len = cpu_to_le16(max_blocks);
2604         /* ex3: to ee_block + ee_len : uninitialised */
2605         if (allocated > max_blocks) {
2606                 unsigned int newdepth;
2607                 /* If extent has less than EXT4_EXT_ZERO_LEN zerout directly */
2608                 if (allocated <= EXT4_EXT_ZERO_LEN && may_zeroout) {
2609                         /*
2610                          * iblock == ee_block is handled by the zerouout
2611                          * at the beginning.
2612                          * Mark first half uninitialized.
2613                          * Mark second half initialized and zero out the
2614                          * initialized extent
2615                          */
2616                         ex->ee_block = orig_ex.ee_block;
2617                         ex->ee_len   = cpu_to_le16(ee_len - allocated);
2618                         ext4_ext_mark_uninitialized(ex);
2619                         ext4_ext_store_pblock(ex, ext_pblock(&orig_ex));
2620                         ext4_ext_dirty(handle, inode, path + depth);
2621
2622                         ex3 = &newex;
2623                         ex3->ee_block = cpu_to_le32(iblock);
2624                         ext4_ext_store_pblock(ex3, newblock);
2625                         ex3->ee_len = cpu_to_le16(allocated);
2626                         err = ext4_ext_insert_extent(handle, inode, path,
2627                                                         ex3, 0);
2628                         if (err == -ENOSPC) {
2629                                 err =  ext4_ext_zeroout(inode, &orig_ex);
2630                                 if (err)
2631                                         goto fix_extent_len;
2632                                 ex->ee_block = orig_ex.ee_block;
2633                                 ex->ee_len   = orig_ex.ee_len;
2634                                 ext4_ext_store_pblock(ex, ext_pblock(&orig_ex));
2635                                 ext4_ext_dirty(handle, inode, path + depth);
2636                                 /* blocks available from iblock */
2637                                 return allocated;
2638
2639                         } else if (err)
2640                                 goto fix_extent_len;
2641
2642                         /*
2643                          * We need to zero out the second half because
2644                          * an fallocate request can update file size and
2645                          * converting the second half to initialized extent
2646                          * implies that we can leak some junk data to user
2647                          * space.
2648                          */
2649                         err =  ext4_ext_zeroout(inode, ex3);
2650                         if (err) {
2651                                 /*
2652                                  * We should actually mark the
2653                                  * second half as uninit and return error
2654                                  * Insert would have changed the extent
2655                                  */
2656                                 depth = ext_depth(inode);
2657                                 ext4_ext_drop_refs(path);
2658                                 path = ext4_ext_find_extent(inode,
2659                                                                 iblock, path);
2660                                 if (IS_ERR(path)) {
2661                                         err = PTR_ERR(path);
2662                                         return err;
2663                                 }
2664                                 /* get the second half extent details */
2665                                 ex = path[depth].p_ext;
2666                                 err = ext4_ext_get_access(handle, inode,
2667                                                                 path + depth);
2668                                 if (err)
2669                                         return err;
2670                                 ext4_ext_mark_uninitialized(ex);
2671                                 ext4_ext_dirty(handle, inode, path + depth);
2672                                 return err;
2673                         }
2674
2675                         /* zeroed the second half */
2676                         return allocated;
2677                 }
2678                 ex3 = &newex;
2679                 ex3->ee_block = cpu_to_le32(iblock + max_blocks);
2680                 ext4_ext_store_pblock(ex3, newblock + max_blocks);
2681                 ex3->ee_len = cpu_to_le16(allocated - max_blocks);
2682                 ext4_ext_mark_uninitialized(ex3);
2683                 err = ext4_ext_insert_extent(handle, inode, path, ex3, 0);
2684                 if (err == -ENOSPC && may_zeroout) {
2685                         err =  ext4_ext_zeroout(inode, &orig_ex);
2686                         if (err)
2687                                 goto fix_extent_len;
2688                         /* update the extent length and mark as initialized */
2689                         ex->ee_block = orig_ex.ee_block;
2690                         ex->ee_len   = orig_ex.ee_len;
2691                         ext4_ext_store_pblock(ex, ext_pblock(&orig_ex));
2692                         ext4_ext_dirty(handle, inode, path + depth);
2693                         /* zeroed the full extent */
2694                         /* blocks available from iblock */
2695                         return allocated;
2696
2697                 } else if (err)
2698                         goto fix_extent_len;
2699                 /*
2700                  * The depth, and hence eh & ex might change
2701                  * as part of the insert above.
2702                  */
2703                 newdepth = ext_depth(inode);
2704                 /*
2705                  * update the extent length after successful insert of the
2706                  * split extent
2707                  */
2708                 ee_len -= ext4_ext_get_actual_len(ex3);
2709                 orig_ex.ee_len = cpu_to_le16(ee_len);
2710                 may_zeroout = ee_block + ee_len <= eof_block;
2711
2712                 depth = newdepth;
2713                 ext4_ext_drop_refs(path);
2714                 path = ext4_ext_find_extent(inode, iblock, path);
2715                 if (IS_ERR(path)) {
2716                         err = PTR_ERR(path);
2717                         goto out;
2718                 }
2719                 eh = path[depth].p_hdr;
2720                 ex = path[depth].p_ext;
2721                 if (ex2 != &newex)
2722                         ex2 = ex;
2723
2724                 err = ext4_ext_get_access(handle, inode, path + depth);
2725                 if (err)
2726                         goto out;
2727
2728                 allocated = max_blocks;
2729
2730                 /* If extent has less than EXT4_EXT_ZERO_LEN and we are trying
2731                  * to insert a extent in the middle zerout directly
2732                  * otherwise give the extent a chance to merge to left
2733                  */
2734                 if (le16_to_cpu(orig_ex.ee_len) <= EXT4_EXT_ZERO_LEN &&
2735                         iblock != ee_block && may_zeroout) {
2736                         err =  ext4_ext_zeroout(inode, &orig_ex);
2737                         if (err)
2738                                 goto fix_extent_len;
2739                         /* update the extent length and mark as initialized */
2740                         ex->ee_block = orig_ex.ee_block;
2741                         ex->ee_len   = orig_ex.ee_len;
2742                         ext4_ext_store_pblock(ex, ext_pblock(&orig_ex));
2743                         ext4_ext_dirty(handle, inode, path + depth);
2744                         /* zero out the first half */
2745                         /* blocks available from iblock */
2746                         return allocated;
2747                 }
2748         }
2749         /*
2750          * If there was a change of depth as part of the
2751          * insertion of ex3 above, we need to update the length
2752          * of the ex1 extent again here
2753          */
2754         if (ex1 && ex1 != ex) {
2755                 ex1 = ex;
2756                 ex1->ee_len = cpu_to_le16(iblock - ee_block);
2757                 ext4_ext_mark_uninitialized(ex1);
2758                 ex2 = &newex;
2759         }
2760         /* ex2: iblock to iblock + maxblocks-1 : initialised */
2761         ex2->ee_block = cpu_to_le32(iblock);
2762         ext4_ext_store_pblock(ex2, newblock);
2763         ex2->ee_len = cpu_to_le16(allocated);
2764         if (ex2 != ex)
2765                 goto insert;
2766         /*
2767          * New (initialized) extent starts from the first block
2768          * in the current extent. i.e., ex2 == ex
2769          * We have to see if it can be merged with the extent
2770          * on the left.
2771          */
2772         if (ex2 > EXT_FIRST_EXTENT(eh)) {
2773                 /*
2774                  * To merge left, pass "ex2 - 1" to try_to_merge(),
2775                  * since it merges towards right _only_.
2776                  */
2777                 ret = ext4_ext_try_to_merge(inode, path, ex2 - 1);
2778                 if (ret) {
2779                         err = ext4_ext_correct_indexes(handle, inode, path);
2780                         if (err)
2781                                 goto out;
2782                         depth = ext_depth(inode);
2783                         ex2--;
2784                 }
2785         }
2786         /*
2787          * Try to Merge towards right. This might be required
2788          * only when the whole extent is being written to.
2789          * i.e. ex2 == ex and ex3 == NULL.
2790          */
2791         if (!ex3) {
2792                 ret = ext4_ext_try_to_merge(inode, path, ex2);
2793                 if (ret) {
2794                         err = ext4_ext_correct_indexes(handle, inode, path);
2795                         if (err)
2796                                 goto out;
2797                 }
2798         }
2799         /* Mark modified extent as dirty */
2800         err = ext4_ext_dirty(handle, inode, path + depth);
2801         goto out;
2802 insert:
2803         err = ext4_ext_insert_extent(handle, inode, path, &newex, 0);
2804         if (err == -ENOSPC && may_zeroout) {
2805                 err =  ext4_ext_zeroout(inode, &orig_ex);
2806                 if (err)
2807                         goto fix_extent_len;
2808                 /* update the extent length and mark as initialized */
2809                 ex->ee_block = orig_ex.ee_block;
2810                 ex->ee_len   = orig_ex.ee_len;
2811                 ext4_ext_store_pblock(ex, ext_pblock(&orig_ex));
2812                 ext4_ext_dirty(handle, inode, path + depth);
2813                 /* zero out the first half */
2814                 return allocated;
2815         } else if (err)
2816                 goto fix_extent_len;
2817 out:
2818         ext4_ext_show_leaf(inode, path);
2819         return err ? err : allocated;
2820
2821 fix_extent_len:
2822         ex->ee_block = orig_ex.ee_block;
2823         ex->ee_len   = orig_ex.ee_len;
2824         ext4_ext_store_pblock(ex, ext_pblock(&orig_ex));
2825         ext4_ext_mark_uninitialized(ex);
2826         ext4_ext_dirty(handle, inode, path + depth);
2827         return err;
2828 }
2829
2830 /*
2831  * This function is called by ext4_ext_get_blocks() from
2832  * ext4_get_blocks_dio_write() when DIO to write
2833  * to an uninitialized extent.
2834  *
2835  * Writing to an uninitized extent may result in splitting the uninitialized
2836  * extent into multiple /intialized unintialized extents (up to three)
2837  * There are three possibilities:
2838  *   a> There is no split required: Entire extent should be uninitialized
2839  *   b> Splits in two extents: Write is happening at either end of the extent
2840  *   c> Splits in three extents: Somone is writing in middle of the extent
2841  *
2842  * One of more index blocks maybe needed if the extent tree grow after
2843  * the unintialized extent split. To prevent ENOSPC occur at the IO
2844  * complete, we need to split the uninitialized extent before DIO submit
2845  * the IO. The uninitilized extent called at this time will be split
2846  * into three uninitialized extent(at most). After IO complete, the part
2847  * being filled will be convert to initialized by the end_io callback function
2848  * via ext4_convert_unwritten_extents().
2849  *
2850  * Returns the size of uninitialized extent to be written on success.
2851  */
2852 static int ext4_split_unwritten_extents(handle_t *handle,
2853                                         struct inode *inode,
2854                                         struct ext4_ext_path *path,
2855                                         ext4_lblk_t iblock,
2856                                         unsigned int max_blocks,
2857                                         int flags)
2858 {
2859         struct ext4_extent *ex, newex, orig_ex;
2860         struct ext4_extent *ex1 = NULL;
2861         struct ext4_extent *ex2 = NULL;
2862         struct ext4_extent *ex3 = NULL;
2863         struct ext4_extent_header *eh;
2864         ext4_lblk_t ee_block, eof_block;
2865         unsigned int allocated, ee_len, depth;
2866         ext4_fsblk_t newblock;
2867         int err = 0;
2868         int may_zeroout;
2869
2870         ext_debug("ext4_split_unwritten_extents: inode %lu, logical"
2871                 "block %llu, max_blocks %u\n", inode->i_ino,
2872                 (unsigned long long)iblock, max_blocks);
2873
2874         eof_block = (inode->i_size + inode->i_sb->s_blocksize - 1) >>
2875                 inode->i_sb->s_blocksize_bits;
2876         if (eof_block < iblock + max_blocks)
2877                 eof_block = iblock + max_blocks;
2878
2879         depth = ext_depth(inode);
2880         eh = path[depth].p_hdr;
2881         ex = path[depth].p_ext;
2882         ee_block = le32_to_cpu(ex->ee_block);
2883         ee_len = ext4_ext_get_actual_len(ex);
2884         allocated = ee_len - (iblock - ee_block);
2885         newblock = iblock - ee_block + ext_pblock(ex);
2886
2887         ex2 = ex;
2888         orig_ex.ee_block = ex->ee_block;
2889         orig_ex.ee_len   = cpu_to_le16(ee_len);
2890         ext4_ext_store_pblock(&orig_ex, ext_pblock(ex));
2891
2892         /*
2893          * It is safe to convert extent to initialized via explicit
2894          * zeroout only if extent is fully insde i_size or new_size.
2895          */
2896         may_zeroout = ee_block + ee_len <= eof_block;
2897
2898         /*
2899          * If the uninitialized extent begins at the same logical
2900          * block where the write begins, and the write completely
2901          * covers the extent, then we don't need to split it.
2902          */
2903         if ((iblock == ee_block) && (allocated <= max_blocks))
2904                 return allocated;
2905
2906         err = ext4_ext_get_access(handle, inode, path + depth);
2907         if (err)
2908                 goto out;
2909         /* ex1: ee_block to iblock - 1 : uninitialized */
2910         if (iblock > ee_block) {
2911                 ex1 = ex;
2912                 ex1->ee_len = cpu_to_le16(iblock - ee_block);
2913                 ext4_ext_mark_uninitialized(ex1);
2914                 ex2 = &newex;
2915         }
2916         /*
2917          * for sanity, update the length of the ex2 extent before
2918          * we insert ex3, if ex1 is NULL. This is to avoid temporary
2919          * overlap of blocks.
2920          */
2921         if (!ex1 && allocated > max_blocks)
2922                 ex2->ee_len = cpu_to_le16(max_blocks);
2923         /* ex3: to ee_block + ee_len : uninitialised */
2924         if (allocated > max_blocks) {
2925                 unsigned int newdepth;
2926                 ex3 = &newex;
2927                 ex3->ee_block = cpu_to_le32(iblock + max_blocks);
2928                 ext4_ext_store_pblock(ex3, newblock + max_blocks);
2929                 ex3->ee_len = cpu_to_le16(allocated - max_blocks);
2930                 ext4_ext_mark_uninitialized(ex3);
2931                 err = ext4_ext_insert_extent(handle, inode, path, ex3, flags);
2932                 if (err == -ENOSPC && may_zeroout) {
2933                         err =  ext4_ext_zeroout(inode, &orig_ex);
2934                         if (err)
2935                                 goto fix_extent_len;
2936                         /* update the extent length and mark as initialized */
2937                         ex->ee_block = orig_ex.ee_block;
2938                         ex->ee_len   = orig_ex.ee_len;
2939                         ext4_ext_store_pblock(ex, ext_pblock(&orig_ex));
2940                         ext4_ext_dirty(handle, inode, path + depth);
2941                         /* zeroed the full extent */
2942                         /* blocks available from iblock */
2943                         return allocated;
2944
2945                 } else if (err)
2946                         goto fix_extent_len;
2947                 /*
2948                  * The depth, and hence eh & ex might change
2949                  * as part of the insert above.
2950                  */
2951                 newdepth = ext_depth(inode);
2952                 /*
2953                  * update the extent length after successful insert of the
2954                  * split extent
2955                  */
2956                 ee_len -= ext4_ext_get_actual_len(ex3);
2957                 orig_ex.ee_len = cpu_to_le16(ee_len);
2958                 may_zeroout = ee_block + ee_len <= eof_block;
2959
2960                 depth = newdepth;
2961                 ext4_ext_drop_refs(path);
2962                 path = ext4_ext_find_extent(inode, iblock, path);
2963                 if (IS_ERR(path)) {
2964                         err = PTR_ERR(path);
2965                         goto out;
2966                 }
2967                 eh = path[depth].p_hdr;
2968                 ex = path[depth].p_ext;
2969                 if (ex2 != &newex)
2970                         ex2 = ex;
2971
2972                 err = ext4_ext_get_access(handle, inode, path + depth);
2973                 if (err)
2974                         goto out;
2975
2976                 allocated = max_blocks;
2977         }
2978         /*
2979          * If there was a change of depth as part of the
2980          * insertion of ex3 above, we need to update the length
2981          * of the ex1 extent again here
2982          */
2983         if (ex1 && ex1 != ex) {
2984                 ex1 = ex;
2985                 ex1->ee_len = cpu_to_le16(iblock - ee_block);
2986                 ext4_ext_mark_uninitialized(ex1);
2987                 ex2 = &newex;
2988         }
2989         /*
2990          * ex2: iblock to iblock + maxblocks-1 : to be direct IO written,
2991          * uninitialised still.
2992          */
2993         ex2->ee_block = cpu_to_le32(iblock);
2994         ext4_ext_store_pblock(ex2, newblock);
2995         ex2->ee_len = cpu_to_le16(allocated);
2996         ext4_ext_mark_uninitialized(ex2);
2997         if (ex2 != ex)
2998                 goto insert;
2999         /* Mark modified extent as dirty */
3000         err = ext4_ext_dirty(handle, inode, path + depth);
3001         ext_debug("out here\n");
3002         goto out;
3003 insert:
3004         err = ext4_ext_insert_extent(handle, inode, path, &newex, flags);
3005         if (err == -ENOSPC && may_zeroout) {
3006                 err =  ext4_ext_zeroout(inode, &orig_ex);
3007                 if (err)
3008                         goto fix_extent_len;
3009                 /* update the extent length and mark as initialized */
3010                 ex->ee_block = orig_ex.ee_block;
3011                 ex->ee_len   = orig_ex.ee_len;
3012                 ext4_ext_store_pblock(ex, ext_pblock(&orig_ex));
3013                 ext4_ext_dirty(handle, inode, path + depth);
3014                 /* zero out the first half */
3015                 return allocated;
3016         } else if (err)
3017                 goto fix_extent_len;
3018 out:
3019         ext4_ext_show_leaf(inode, path);
3020         return err ? err : allocated;
3021
3022 fix_extent_len:
3023         ex->ee_block = orig_ex.ee_block;
3024         ex->ee_len   = orig_ex.ee_len;
3025         ext4_ext_store_pblock(ex, ext_pblock(&orig_ex));
3026         ext4_ext_mark_uninitialized(ex);
3027         ext4_ext_dirty(handle, inode, path + depth);
3028         return err;
3029 }
3030 static int ext4_convert_unwritten_extents_dio(handle_t *handle,
3031                                               struct inode *inode,
3032                                               struct ext4_ext_path *path)
3033 {
3034         struct ext4_extent *ex;
3035         struct ext4_extent_header *eh;
3036         int depth;
3037         int err = 0;
3038         int ret = 0;
3039
3040         depth = ext_depth(inode);
3041         eh = path[depth].p_hdr;
3042         ex = path[depth].p_ext;
3043
3044         err = ext4_ext_get_access(handle, inode, path + depth);
3045         if (err)
3046                 goto out;
3047         /* first mark the extent as initialized */
3048         ext4_ext_mark_initialized(ex);
3049
3050         /*
3051          * We have to see if it can be merged with the extent
3052          * on the left.
3053          */
3054         if (ex > EXT_FIRST_EXTENT(eh)) {
3055                 /*
3056                  * To merge left, pass "ex - 1" to try_to_merge(),
3057                  * since it merges towards right _only_.
3058                  */
3059                 ret = ext4_ext_try_to_merge(inode, path, ex - 1);
3060                 if (ret) {
3061                         err = ext4_ext_correct_indexes(handle, inode, path);
3062                         if (err)
3063                                 goto out;
3064                         depth = ext_depth(inode);
3065                         ex--;
3066                 }
3067         }
3068         /*
3069          * Try to Merge towards right.
3070          */
3071         ret = ext4_ext_try_to_merge(inode, path, ex);
3072         if (ret) {
3073                 err = ext4_ext_correct_indexes(handle, inode, path);
3074                 if (err)
3075                         goto out;
3076                 depth = ext_depth(inode);
3077         }
3078         /* Mark modified extent as dirty */
3079         err = ext4_ext_dirty(handle, inode, path + depth);
3080 out:
3081         ext4_ext_show_leaf(inode, path);
3082         return err;
3083 }
3084
3085 static void unmap_underlying_metadata_blocks(struct block_device *bdev,
3086                         sector_t block, int count)
3087 {
3088         int i;
3089         for (i = 0; i < count; i++)
3090                 unmap_underlying_metadata(bdev, block + i);
3091 }
3092
3093 static int
3094 ext4_ext_handle_uninitialized_extents(handle_t *handle, struct inode *inode,
3095                         ext4_lblk_t iblock, unsigned int max_blocks,
3096                         struct ext4_ext_path *path, int flags,
3097                         unsigned int allocated, struct buffer_head *bh_result,
3098                         ext4_fsblk_t newblock)
3099 {
3100         int ret = 0;
3101         int err = 0;
3102         ext4_io_end_t *io = EXT4_I(inode)->cur_aio_dio;
3103
3104         ext_debug("ext4_ext_handle_uninitialized_extents: inode %lu, logical"
3105                   "block %llu, max_blocks %u, flags %d, allocated %u",
3106                   inode->i_ino, (unsigned long long)iblock, max_blocks,
3107                   flags, allocated);
3108         ext4_ext_show_leaf(inode, path);
3109
3110         /* DIO get_block() before submit the IO, split the extent */
3111         if (flags == EXT4_GET_BLOCKS_DIO_CREATE_EXT) {
3112                 ret = ext4_split_unwritten_extents(handle,
3113                                                 inode, path, iblock,
3114                                                 max_blocks, flags);
3115                 /*
3116                  * Flag the inode(non aio case) or end_io struct (aio case)
3117                  * that this IO needs to convertion to written when IO is
3118                  * completed
3119                  */
3120                 if (io)
3121                         io->flag = DIO_AIO_UNWRITTEN;
3122                 else
3123                         ext4_set_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
3124                 goto out;
3125         }
3126         /* async DIO end_io complete, convert the filled extent to written */
3127         if (flags == EXT4_GET_BLOCKS_DIO_CONVERT_EXT) {
3128                 ret = ext4_convert_unwritten_extents_dio(handle, inode,
3129                                                         path);
3130                 if (ret >= 0)
3131                         ext4_update_inode_fsync_trans(handle, inode, 1);
3132                 goto out2;
3133         }
3134         /* buffered IO case */
3135         /*
3136          * repeat fallocate creation request
3137          * we already have an unwritten extent
3138          */
3139         if (flags & EXT4_GET_BLOCKS_UNINIT_EXT)
3140                 goto map_out;
3141
3142         /* buffered READ or buffered write_begin() lookup */
3143         if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
3144                 /*
3145                  * We have blocks reserved already.  We
3146                  * return allocated blocks so that delalloc
3147                  * won't do block reservation for us.  But
3148                  * the buffer head will be unmapped so that
3149                  * a read from the block returns 0s.
3150                  */
3151                 set_buffer_unwritten(bh_result);
3152                 goto out1;
3153         }
3154
3155         /* buffered write, writepage time, convert*/
3156         ret = ext4_ext_convert_to_initialized(handle, inode,
3157                                                 path, iblock,
3158                                                 max_blocks);
3159         if (ret >= 0)
3160                 ext4_update_inode_fsync_trans(handle, inode, 1);
3161 out:
3162         if (ret <= 0) {
3163                 err = ret;
3164                 goto out2;
3165         } else
3166                 allocated = ret;
3167         set_buffer_new(bh_result);
3168         /*
3169          * if we allocated more blocks than requested
3170          * we need to make sure we unmap the extra block
3171          * allocated. The actual needed block will get
3172          * unmapped later when we find the buffer_head marked
3173          * new.
3174          */
3175         if (allocated > max_blocks) {
3176                 unmap_underlying_metadata_blocks(inode->i_sb->s_bdev,
3177                                         newblock + max_blocks,
3178                                         allocated - max_blocks);
3179                 allocated = max_blocks;
3180         }
3181
3182         /*
3183          * If we have done fallocate with the offset that is already
3184          * delayed allocated, we would have block reservation
3185          * and quota reservation done in the delayed write path.
3186          * But fallocate would have already updated quota and block
3187          * count for this offset. So cancel these reservation
3188          */
3189         if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
3190                 ext4_da_update_reserve_space(inode, allocated, 0);
3191
3192 map_out:
3193         set_buffer_mapped(bh_result);
3194 out1:
3195         if (allocated > max_blocks)
3196                 allocated = max_blocks;
3197         ext4_ext_show_leaf(inode, path);
3198         bh_result->b_bdev = inode->i_sb->s_bdev;
3199         bh_result->b_blocknr = newblock;
3200 out2:
3201         if (path) {
3202                 ext4_ext_drop_refs(path);
3203                 kfree(path);
3204         }
3205         return err ? err : allocated;
3206 }
3207 /*
3208  * Block allocation/map/preallocation routine for extents based files
3209  *
3210  *
3211  * Need to be called with
3212  * down_read(&EXT4_I(inode)->i_data_sem) if not allocating file system block
3213  * (ie, create is zero). Otherwise down_write(&EXT4_I(inode)->i_data_sem)
3214  *
3215  * return > 0, number of of blocks already mapped/allocated
3216  *          if create == 0 and these are pre-allocated blocks
3217  *              buffer head is unmapped
3218  *          otherwise blocks are mapped
3219  *
3220  * return = 0, if plain look up failed (blocks have not been allocated)
3221  *          buffer head is unmapped
3222  *
3223  * return < 0, error case.
3224  */
3225 int ext4_ext_get_blocks(handle_t *handle, struct inode *inode,
3226                         ext4_lblk_t iblock,
3227                         unsigned int max_blocks, struct buffer_head *bh_result,
3228                         int flags)
3229 {
3230         struct ext4_ext_path *path = NULL;
3231         struct ext4_extent_header *eh;
3232         struct ext4_extent newex, *ex, *last_ex;
3233         ext4_fsblk_t newblock;
3234         int i, err = 0, depth, ret, cache_type;
3235         unsigned int allocated = 0;
3236         struct ext4_allocation_request ar;
3237         ext4_io_end_t *io = EXT4_I(inode)->cur_aio_dio;
3238
3239         __clear_bit(BH_New, &bh_result->b_state);
3240         ext_debug("blocks %u/%u requested for inode %lu\n",
3241                         iblock, max_blocks, inode->i_ino);
3242
3243         /* check in cache */
3244         cache_type = ext4_ext_in_cache(inode, iblock, &newex);
3245         if (cache_type) {
3246                 if (cache_type == EXT4_EXT_CACHE_GAP) {
3247                         if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
3248                                 /*
3249                                  * block isn't allocated yet and
3250                                  * user doesn't want to allocate it
3251                                  */
3252                                 goto out2;
3253                         }
3254                         /* we should allocate requested block */
3255                 } else if (cache_type == EXT4_EXT_CACHE_EXTENT) {
3256                         /* block is already allocated */
3257                         newblock = iblock
3258                                    - le32_to_cpu(newex.ee_block)
3259                                    + ext_pblock(&newex);
3260                         /* number of remaining blocks in the extent */
3261                         allocated = ext4_ext_get_actual_len(&newex) -
3262                                         (iblock - le32_to_cpu(newex.ee_block));
3263                         goto out;
3264                 } else {
3265                         BUG();
3266                 }
3267         }
3268
3269         /* find extent for this block */
3270         path = ext4_ext_find_extent(inode, iblock, NULL);
3271         if (IS_ERR(path)) {
3272                 err = PTR_ERR(path);
3273                 path = NULL;
3274                 goto out2;
3275         }
3276
3277         depth = ext_depth(inode);
3278
3279         /*
3280          * consistent leaf must not be empty;
3281          * this situation is possible, though, _during_ tree modification;
3282          * this is why assert can't be put in ext4_ext_find_extent()
3283          */
3284         if (path[depth].p_ext == NULL && depth != 0) {
3285                 ext4_error(inode->i_sb, __func__, "bad extent address "
3286                            "inode: %lu, iblock: %lu, depth: %d",
3287                            inode->i_ino, (unsigned long) iblock, depth);
3288                 err = -EIO;
3289                 goto out2;
3290         }
3291         eh = path[depth].p_hdr;
3292
3293         ex = path[depth].p_ext;
3294         if (ex) {
3295                 ext4_lblk_t ee_block = le32_to_cpu(ex->ee_block);
3296                 ext4_fsblk_t ee_start = ext_pblock(ex);
3297                 unsigned short ee_len;
3298
3299                 /*
3300                  * Uninitialized extents are treated as holes, except that
3301                  * we split out initialized portions during a write.
3302                  */
3303                 ee_len = ext4_ext_get_actual_len(ex);
3304                 /* if found extent covers block, simply return it */
3305                 if (in_range(iblock, ee_block, ee_len)) {
3306                         newblock = iblock - ee_block + ee_start;
3307                         /* number of remaining blocks in the extent */
3308                         allocated = ee_len - (iblock - ee_block);
3309                         ext_debug("%u fit into %u:%d -> %llu\n", iblock,
3310                                         ee_block, ee_len, newblock);
3311
3312                         /* Do not put uninitialized extent in the cache */
3313                         if (!ext4_ext_is_uninitialized(ex)) {
3314                                 ext4_ext_put_in_cache(inode, ee_block,
3315                                                         ee_len, ee_start,
3316                                                         EXT4_EXT_CACHE_EXTENT);
3317                                 goto out;
3318                         }
3319                         ret = ext4_ext_handle_uninitialized_extents(handle,
3320                                         inode, iblock, max_blocks, path,
3321                                         flags, allocated, bh_result, newblock);
3322                         return ret;
3323                 }
3324         }
3325
3326         /*
3327          * requested block isn't allocated yet;
3328          * we couldn't try to create block if create flag is zero
3329          */
3330         if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
3331                 /*
3332                  * put just found gap into cache to speed up
3333                  * subsequent requests
3334                  */
3335                 ext4_ext_put_gap_in_cache(inode, path, iblock);
3336                 goto out2;
3337         }
3338         /*
3339          * Okay, we need to do block allocation.
3340          */
3341
3342         /* find neighbour allocated blocks */
3343         ar.lleft = iblock;
3344         err = ext4_ext_search_left(inode, path, &ar.lleft, &ar.pleft);
3345         if (err)
3346                 goto out2;
3347         ar.lright = iblock;
3348         err = ext4_ext_search_right(inode, path, &ar.lright, &ar.pright);
3349         if (err)
3350                 goto out2;
3351
3352         /*
3353          * See if request is beyond maximum number of blocks we can have in
3354          * a single extent. For an initialized extent this limit is
3355          * EXT_INIT_MAX_LEN and for an uninitialized extent this limit is
3356          * EXT_UNINIT_MAX_LEN.
3357          */
3358         if (max_blocks > EXT_INIT_MAX_LEN &&
3359             !(flags & EXT4_GET_BLOCKS_UNINIT_EXT))
3360                 max_blocks = EXT_INIT_MAX_LEN;
3361         else if (max_blocks > EXT_UNINIT_MAX_LEN &&
3362                  (flags & EXT4_GET_BLOCKS_UNINIT_EXT))
3363                 max_blocks = EXT_UNINIT_MAX_LEN;
3364
3365         /* Check if we can really insert (iblock)::(iblock+max_blocks) extent */
3366         newex.ee_block = cpu_to_le32(iblock);
3367         newex.ee_len = cpu_to_le16(max_blocks);
3368         err = ext4_ext_check_overlap(inode, &newex, path);
3369         if (err)
3370                 allocated = ext4_ext_get_actual_len(&newex);
3371         else
3372                 allocated = max_blocks;
3373
3374         /* allocate new block */
3375         ar.inode = inode;
3376         ar.goal = ext4_ext_find_goal(inode, path, iblock);
3377         ar.logical = iblock;
3378         ar.len = allocated;
3379         if (S_ISREG(inode->i_mode))
3380                 ar.flags = EXT4_MB_HINT_DATA;
3381         else
3382                 /* disable in-core preallocation for non-regular files */
3383                 ar.flags = 0;
3384         newblock = ext4_mb_new_blocks(handle, &ar, &err);
3385         if (!newblock)
3386                 goto out2;
3387         ext_debug("allocate new block: goal %llu, found %llu/%u\n",
3388                   ar.goal, newblock, allocated);
3389
3390         /* try to insert new extent into found leaf and return */
3391         ext4_ext_store_pblock(&newex, newblock);
3392         newex.ee_len = cpu_to_le16(ar.len);
3393         /* Mark uninitialized */
3394         if (flags & EXT4_GET_BLOCKS_UNINIT_EXT){
3395                 ext4_ext_mark_uninitialized(&newex);
3396                 /*
3397                  * io_end structure was created for every async
3398                  * direct IO write to the middle of the file.
3399                  * To avoid unecessary convertion for every aio dio rewrite
3400                  * to the mid of file, here we flag the IO that is really
3401                  * need the convertion.
3402                  * For non asycn direct IO case, flag the inode state
3403                  * that we need to perform convertion when IO is done.
3404                  */
3405                 if (flags == EXT4_GET_BLOCKS_DIO_CREATE_EXT) {
3406                         if (io)
3407                                 io->flag = DIO_AIO_UNWRITTEN;
3408                         else
3409                                 ext4_set_inode_state(inode,
3410                                                      EXT4_STATE_DIO_UNWRITTEN);
3411                 }
3412         }
3413
3414         if (unlikely(ext4_test_inode_flag(inode, EXT4_INODE_EOFBLOCKS))) {
3415                 if (unlikely(!eh->eh_entries)) {
3416                         ext4_error(inode->i_sb, __func__,
3417                                    "inode#%lu, eh->eh_entries = 0 and "
3418                                    "EOFBLOCKS_FL set", inode->i_ino);
3419                         err = -EIO;
3420                         goto out2;
3421                 }
3422                 last_ex = EXT_LAST_EXTENT(eh);
3423                 /*
3424                  * If the current leaf block was reached by looking at
3425                  * the last index block all the way down the tree, and
3426                  * we are extending the inode beyond the last extent
3427                  * in the current leaf block, then clear the
3428                  * EOFBLOCKS_FL flag.
3429                  */
3430                 for (i = depth-1; i >= 0; i--) {
3431                         if (path[i].p_idx != EXT_LAST_INDEX(path[i].p_hdr))
3432                                 break;
3433                 }
3434                 if ((i < 0) &&
3435                     (iblock + ar.len > le32_to_cpu(last_ex->ee_block) +
3436                      ext4_ext_get_actual_len(last_ex)))
3437                         ext4_clear_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
3438         }
3439         err = ext4_ext_insert_extent(handle, inode, path, &newex, flags);
3440         if (err) {
3441                 /* free data blocks we just allocated */
3442                 /* not a good idea to call discard here directly,
3443                  * but otherwise we'd need to call it every free() */
3444                 ext4_discard_preallocations(inode);
3445                 ext4_free_blocks(handle, inode, ext_pblock(&newex),
3446                                         ext4_ext_get_actual_len(&newex), 0);
3447                 goto out2;
3448         }
3449
3450         /* previous routine could use block we allocated */
3451         newblock = ext_pblock(&newex);
3452         allocated = ext4_ext_get_actual_len(&newex);
3453         if (allocated > max_blocks)
3454                 allocated = max_blocks;
3455         set_buffer_new(bh_result);
3456
3457         /*
3458          * Update reserved blocks/metadata blocks after successful
3459          * block allocation which had been deferred till now.
3460          */
3461         if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
3462                 ext4_da_update_reserve_space(inode, allocated, 1);
3463
3464         /*
3465          * Cache the extent and update transaction to commit on fdatasync only
3466          * when it is _not_ an uninitialized extent.
3467          */
3468         if ((flags & EXT4_GET_BLOCKS_UNINIT_EXT) == 0) {
3469                 ext4_ext_put_in_cache(inode, iblock, allocated, newblock,
3470                                                 EXT4_EXT_CACHE_EXTENT);
3471                 ext4_update_inode_fsync_trans(handle, inode, 1);
3472         } else
3473                 ext4_update_inode_fsync_trans(handle, inode, 0);
3474 out:
3475         if (allocated > max_blocks)
3476                 allocated = max_blocks;
3477         ext4_ext_show_leaf(inode, path);
3478         set_buffer_mapped(bh_result);
3479         bh_result->b_bdev = inode->i_sb->s_bdev;
3480         bh_result->b_blocknr = newblock;
3481 out2:
3482         if (path) {
3483                 ext4_ext_drop_refs(path);
3484                 kfree(path);
3485         }
3486         return err ? err : allocated;
3487 }
3488
3489 void ext4_ext_truncate(struct inode *inode)
3490 {
3491         struct address_space *mapping = inode->i_mapping;
3492         struct super_block *sb = inode->i_sb;
3493         ext4_lblk_t last_block;
3494         handle_t *handle;
3495         int err = 0;
3496
3497         /*
3498          * probably first extent we're gonna free will be last in block
3499          */
3500         err = ext4_writepage_trans_blocks(inode);
3501         handle = ext4_journal_start(inode, err);
3502         if (IS_ERR(handle))
3503                 return;
3504
3505         if (inode->i_size & (sb->s_blocksize - 1))
3506                 ext4_block_truncate_page(handle, mapping, inode->i_size);
3507
3508         if (ext4_orphan_add(handle, inode))
3509                 goto out_stop;
3510
3511         down_write(&EXT4_I(inode)->i_data_sem);
3512         ext4_ext_invalidate_cache(inode);
3513
3514         ext4_discard_preallocations(inode);
3515
3516         /*
3517          * TODO: optimization is possible here.
3518          * Probably we need not scan at all,
3519          * because page truncation is enough.
3520          */
3521
3522         /* we have to know where to truncate from in crash case */
3523         EXT4_I(inode)->i_disksize = inode->i_size;
3524         ext4_mark_inode_dirty(handle, inode);
3525
3526         last_block = (inode->i_size + sb->s_blocksize - 1)
3527                         >> EXT4_BLOCK_SIZE_BITS(sb);
3528         err = ext4_ext_remove_space(inode, last_block);
3529
3530         /* In a multi-transaction truncate, we only make the final
3531          * transaction synchronous.
3532          */
3533         if (IS_SYNC(inode))
3534                 ext4_handle_sync(handle);
3535
3536 out_stop:
3537         up_write(&EXT4_I(inode)->i_data_sem);
3538         /*
3539          * If this was a simple ftruncate() and the file will remain alive,
3540          * then we need to clear up the orphan record which we created above.
3541          * However, if this was a real unlink then we were called by
3542          * ext4_delete_inode(), and we allow that function to clean up the
3543          * orphan info for us.
3544          */
3545         if (inode->i_nlink)
3546                 ext4_orphan_del(handle, inode);
3547
3548         inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
3549         ext4_mark_inode_dirty(handle, inode);
3550         ext4_journal_stop(handle);
3551 }
3552
3553 static void ext4_falloc_update_inode(struct inode *inode,
3554                                 int mode, loff_t new_size, int update_ctime)
3555 {
3556         struct timespec now;
3557
3558         if (update_ctime) {
3559                 now = current_fs_time(inode->i_sb);
3560                 if (!timespec_equal(&inode->i_ctime, &now))
3561                         inode->i_ctime = now;
3562         }
3563         /*
3564          * Update only when preallocation was requested beyond
3565          * the file size.
3566          */
3567         if (!(mode & FALLOC_FL_KEEP_SIZE)) {
3568                 if (new_size > i_size_read(inode))
3569                         i_size_write(inode, new_size);
3570                 if (new_size > EXT4_I(inode)->i_disksize)
3571                         ext4_update_i_disksize(inode, new_size);
3572         } else {
3573                 /*
3574                  * Mark that we allocate beyond EOF so the subsequent truncate
3575                  * can proceed even if the new size is the same as i_size.
3576                  */
3577                 if (new_size > i_size_read(inode))
3578                         ext4_set_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
3579         }
3580
3581 }
3582
3583 /*
3584  * preallocate space for a file. This implements ext4's fallocate inode
3585  * operation, which gets called from sys_fallocate system call.
3586  * For block-mapped files, posix_fallocate should fall back to the method
3587  * of writing zeroes to the required new blocks (the same behavior which is
3588  * expected for file systems which do not support fallocate() system call).
3589  */
3590 long ext4_fallocate(struct inode *inode, int mode, loff_t offset, loff_t len)
3591 {
3592         handle_t *handle;
3593         ext4_lblk_t block;
3594         loff_t new_size;
3595         unsigned int max_blocks;
3596         int ret = 0;
3597         int ret2 = 0;
3598         int retries = 0;
3599         struct buffer_head map_bh;
3600         unsigned int credits, blkbits = inode->i_blkbits;
3601
3602         /*
3603          * currently supporting (pre)allocate mode for extent-based
3604          * files _only_
3605          */
3606         if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
3607                 return -EOPNOTSUPP;
3608
3609         /* preallocation to directories is currently not supported */
3610         if (S_ISDIR(inode->i_mode))
3611                 return -ENODEV;
3612
3613         block = offset >> blkbits;
3614         /*
3615          * We can't just convert len to max_blocks because
3616          * If blocksize = 4096 offset = 3072 and len = 2048
3617          */
3618         max_blocks = (EXT4_BLOCK_ALIGN(len + offset, blkbits) >> blkbits)
3619                                                         - block;
3620         /*
3621          * credits to insert 1 extent into extent tree
3622          */
3623         credits = ext4_chunk_trans_blocks(inode, max_blocks);
3624         mutex_lock(&inode->i_mutex);
3625         ret = inode_newsize_ok(inode, (len + offset));
3626         if (ret) {
3627                 mutex_unlock(&inode->i_mutex);
3628                 return ret;
3629         }
3630 retry:
3631         while (ret >= 0 && ret < max_blocks) {
3632                 block = block + ret;
3633                 max_blocks = max_blocks - ret;
3634                 handle = ext4_journal_start(inode, credits);
3635                 if (IS_ERR(handle)) {
3636                         ret = PTR_ERR(handle);
3637                         break;
3638                 }
3639                 map_bh.b_state = 0;
3640                 ret = ext4_get_blocks(handle, inode, block,
3641                                       max_blocks, &map_bh,
3642                                       EXT4_GET_BLOCKS_CREATE_UNINIT_EXT);
3643                 if (ret <= 0) {
3644 #ifdef EXT4FS_DEBUG
3645                         WARN_ON(ret <= 0);
3646                         printk(KERN_ERR "%s: ext4_ext_get_blocks "
3647                                     "returned error inode#%lu, block=%u, "
3648                                     "max_blocks=%u", __func__,
3649                                     inode->i_ino, block, max_blocks);
3650 #endif
3651                         ext4_mark_inode_dirty(handle, inode);
3652                         ret2 = ext4_journal_stop(handle);
3653                         break;
3654                 }
3655                 if ((block + ret) >= (EXT4_BLOCK_ALIGN(offset + len,
3656                                                 blkbits) >> blkbits))
3657                         new_size = offset + len;
3658                 else
3659                         new_size = (block + ret) << blkbits;
3660
3661                 ext4_falloc_update_inode(inode, mode, new_size,
3662                                                 buffer_new(&map_bh));
3663                 ext4_mark_inode_dirty(handle, inode);
3664                 ret2 = ext4_journal_stop(handle);
3665                 if (ret2)
3666                         break;
3667         }
3668         if (ret == -ENOSPC &&
3669                         ext4_should_retry_alloc(inode->i_sb, &retries)) {
3670                 ret = 0;
3671                 goto retry;
3672         }
3673         mutex_unlock(&inode->i_mutex);
3674         return ret > 0 ? ret2 : ret;
3675 }
3676
3677 /*
3678  * This function convert a range of blocks to written extents
3679  * The caller of this function will pass the start offset and the size.
3680  * all unwritten extents within this range will be converted to
3681  * written extents.
3682  *
3683  * This function is called from the direct IO end io call back
3684  * function, to convert the fallocated extents after IO is completed.
3685  * Returns 0 on success.
3686  */
3687 int ext4_convert_unwritten_extents(struct inode *inode, loff_t offset,
3688                                     ssize_t len)
3689 {
3690         handle_t *handle;
3691         ext4_lblk_t block;
3692         unsigned int max_blocks;
3693         int ret = 0;
3694         int ret2 = 0;
3695         struct buffer_head map_bh;
3696         unsigned int credits, blkbits = inode->i_blkbits;
3697
3698         block = offset >> blkbits;
3699         /*
3700          * We can't just convert len to max_blocks because
3701          * If blocksize = 4096 offset = 3072 and len = 2048
3702          */
3703         max_blocks = (EXT4_BLOCK_ALIGN(len + offset, blkbits) >> blkbits)
3704                                                         - block;
3705         /*
3706          * credits to insert 1 extent into extent tree
3707          */
3708         credits = ext4_chunk_trans_blocks(inode, max_blocks);
3709         while (ret >= 0 && ret < max_blocks) {
3710                 block = block + ret;
3711                 max_blocks = max_blocks - ret;
3712                 handle = ext4_journal_start(inode, credits);
3713                 if (IS_ERR(handle)) {
3714                         ret = PTR_ERR(handle);
3715                         break;
3716                 }
3717                 map_bh.b_state = 0;
3718                 ret = ext4_get_blocks(handle, inode, block,
3719                                       max_blocks, &map_bh,
3720                                       EXT4_GET_BLOCKS_DIO_CONVERT_EXT);
3721                 if (ret <= 0) {
3722                         WARN_ON(ret <= 0);
3723                         printk(KERN_ERR "%s: ext4_ext_get_blocks "
3724                                     "returned error inode#%lu, block=%u, "
3725                                     "max_blocks=%u", __func__,
3726                                     inode->i_ino, block, max_blocks);
3727                 }
3728                 ext4_mark_inode_dirty(handle, inode);
3729                 ret2 = ext4_journal_stop(handle);
3730                 if (ret <= 0 || ret2 )
3731                         break;
3732         }
3733         return ret > 0 ? ret2 : ret;
3734 }
3735 /*
3736  * Callback function called for each extent to gather FIEMAP information.
3737  */
3738 static int ext4_ext_fiemap_cb(struct inode *inode, struct ext4_ext_path *path,
3739                        struct ext4_ext_cache *newex, struct ext4_extent *ex,
3740                        void *data)
3741 {
3742         struct fiemap_extent_info *fieinfo = data;
3743         unsigned char blksize_bits = inode->i_sb->s_blocksize_bits;
3744         __u64   logical;
3745         __u64   physical;
3746         __u64   length;
3747         __u32   flags = 0;
3748         int     error;
3749
3750         logical =  (__u64)newex->ec_block << blksize_bits;
3751
3752         if (newex->ec_type == EXT4_EXT_CACHE_GAP) {
3753                 pgoff_t offset;
3754                 struct page *page;
3755                 struct buffer_head *bh = NULL;
3756
3757                 offset = logical >> PAGE_SHIFT;
3758                 page = find_get_page(inode->i_mapping, offset);
3759                 if (!page || !page_has_buffers(page))
3760                         return EXT_CONTINUE;
3761
3762                 bh = page_buffers(page);
3763
3764                 if (!bh)
3765                         return EXT_CONTINUE;
3766
3767                 if (buffer_delay(bh)) {
3768                         flags |= FIEMAP_EXTENT_DELALLOC;
3769                         page_cache_release(page);
3770                 } else {
3771                         page_cache_release(page);
3772                         return EXT_CONTINUE;
3773                 }
3774         }
3775
3776         physical = (__u64)newex->ec_start << blksize_bits;
3777         length =   (__u64)newex->ec_len << blksize_bits;
3778
3779         if (ex && ext4_ext_is_uninitialized(ex))
3780                 flags |= FIEMAP_EXTENT_UNWRITTEN;
3781
3782         /*
3783          * If this extent reaches EXT_MAX_BLOCK, it must be last.
3784          *
3785          * Or if ext4_ext_next_allocated_block is EXT_MAX_BLOCK,
3786          * this also indicates no more allocated blocks.
3787          *
3788          * XXX this might miss a single-block extent at EXT_MAX_BLOCK
3789          */
3790         if (ext4_ext_next_allocated_block(path) == EXT_MAX_BLOCK ||
3791             newex->ec_block + newex->ec_len - 1 == EXT_MAX_BLOCK) {
3792                 loff_t size = i_size_read(inode);
3793                 loff_t bs = EXT4_BLOCK_SIZE(inode->i_sb);
3794
3795                 flags |= FIEMAP_EXTENT_LAST;
3796                 if ((flags & FIEMAP_EXTENT_DELALLOC) &&
3797                     logical+length > size)
3798                         length = (size - logical + bs - 1) & ~(bs-1);
3799         }
3800
3801         error = fiemap_fill_next_extent(fieinfo, logical, physical,
3802                                         length, flags);
3803         if (error < 0)
3804                 return error;
3805         if (error == 1)
3806                 return EXT_BREAK;
3807
3808         return EXT_CONTINUE;
3809 }
3810
3811 /* fiemap flags we can handle specified here */
3812 #define EXT4_FIEMAP_FLAGS       (FIEMAP_FLAG_SYNC|FIEMAP_FLAG_XATTR)
3813
3814 static int ext4_xattr_fiemap(struct inode *inode,
3815                                 struct fiemap_extent_info *fieinfo)
3816 {
3817         __u64 physical = 0;
3818         __u64 length;
3819         __u32 flags = FIEMAP_EXTENT_LAST;
3820         int blockbits = inode->i_sb->s_blocksize_bits;
3821         int error = 0;
3822
3823         /* in-inode? */
3824         if (ext4_test_inode_state(inode, EXT4_STATE_XATTR)) {
3825                 struct ext4_iloc iloc;
3826                 int offset;     /* offset of xattr in inode */
3827
3828                 error = ext4_get_inode_loc(inode, &iloc);
3829                 if (error)
3830                         return error;
3831                 physical = iloc.bh->b_blocknr << blockbits;
3832                 offset = EXT4_GOOD_OLD_INODE_SIZE +
3833                                 EXT4_I(inode)->i_extra_isize;
3834                 physical += offset;
3835                 length = EXT4_SB(inode->i_sb)->s_inode_size - offset;
3836                 flags |= FIEMAP_EXTENT_DATA_INLINE;
3837                 brelse(iloc.bh);
3838         } else { /* external block */
3839                 physical = EXT4_I(inode)->i_file_acl << blockbits;
3840                 length = inode->i_sb->s_blocksize;
3841         }
3842
3843         if (physical)
3844                 error = fiemap_fill_next_extent(fieinfo, 0, physical,
3845                                                 length, flags);
3846         return (error < 0 ? error : 0);
3847 }
3848
3849 int ext4_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
3850                 __u64 start, __u64 len)
3851 {
3852         ext4_lblk_t start_blk;
3853         int error = 0;
3854
3855         /* fallback to generic here if not in extents fmt */
3856         if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
3857                 return generic_block_fiemap(inode, fieinfo, start, len,
3858                         ext4_get_block);
3859
3860         if (fiemap_check_flags(fieinfo, EXT4_FIEMAP_FLAGS))
3861                 return -EBADR;
3862
3863         if (fieinfo->fi_flags & FIEMAP_FLAG_XATTR) {
3864                 error = ext4_xattr_fiemap(inode, fieinfo);
3865         } else {
3866                 ext4_lblk_t len_blks;
3867                 __u64 last_blk;
3868
3869                 start_blk = start >> inode->i_sb->s_blocksize_bits;
3870                 last_blk = (start + len - 1) >> inode->i_sb->s_blocksize_bits;
3871                 if (last_blk >= EXT_MAX_BLOCK)
3872                         last_blk = EXT_MAX_BLOCK-1;
3873                 len_blks = ((ext4_lblk_t) last_blk) - start_blk + 1;
3874
3875                 /*
3876                  * Walk the extent tree gathering extent information.
3877                  * ext4_ext_fiemap_cb will push extents back to user.
3878                  */
3879                 error = ext4_ext_walk_space(inode, start_blk, len_blks,
3880                                           ext4_ext_fiemap_cb, fieinfo);
3881         }
3882
3883         return error;
3884 }
3885