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