]> www.pilppa.org Git - linux-2.6-omap-h63xx.git/blob - fs/ext4/extents.c
ext4: move headers out of include/linux
[linux-2.6-omap-h63xx.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 "ext4_jbd2.h"
44 #include "ext4_extents.h"
45
46
47 /*
48  * ext_pblock:
49  * combine low and high parts of physical block number into ext4_fsblk_t
50  */
51 static ext4_fsblk_t ext_pblock(struct ext4_extent *ex)
52 {
53         ext4_fsblk_t block;
54
55         block = le32_to_cpu(ex->ee_start_lo);
56         block |= ((ext4_fsblk_t) le16_to_cpu(ex->ee_start_hi) << 31) << 1;
57         return block;
58 }
59
60 /*
61  * idx_pblock:
62  * combine low and high parts of a leaf physical block number into ext4_fsblk_t
63  */
64 ext4_fsblk_t idx_pblock(struct ext4_extent_idx *ix)
65 {
66         ext4_fsblk_t block;
67
68         block = le32_to_cpu(ix->ei_leaf_lo);
69         block |= ((ext4_fsblk_t) le16_to_cpu(ix->ei_leaf_hi) << 31) << 1;
70         return block;
71 }
72
73 /*
74  * ext4_ext_store_pblock:
75  * stores a large physical block number into an extent struct,
76  * breaking it into parts
77  */
78 void ext4_ext_store_pblock(struct ext4_extent *ex, ext4_fsblk_t pb)
79 {
80         ex->ee_start_lo = cpu_to_le32((unsigned long) (pb & 0xffffffff));
81         ex->ee_start_hi = cpu_to_le16((unsigned long) ((pb >> 31) >> 1) & 0xffff);
82 }
83
84 /*
85  * ext4_idx_store_pblock:
86  * stores a large physical block number into an index struct,
87  * breaking it into parts
88  */
89 static void ext4_idx_store_pblock(struct ext4_extent_idx *ix, ext4_fsblk_t pb)
90 {
91         ix->ei_leaf_lo = cpu_to_le32((unsigned long) (pb & 0xffffffff));
92         ix->ei_leaf_hi = cpu_to_le16((unsigned long) ((pb >> 31) >> 1) & 0xffff);
93 }
94
95 static handle_t *ext4_ext_journal_restart(handle_t *handle, int needed)
96 {
97         int err;
98
99         if (handle->h_buffer_credits > needed)
100                 return handle;
101         if (!ext4_journal_extend(handle, needed))
102                 return handle;
103         err = ext4_journal_restart(handle, needed);
104
105         return handle;
106 }
107
108 /*
109  * could return:
110  *  - EROFS
111  *  - ENOMEM
112  */
113 static int ext4_ext_get_access(handle_t *handle, struct inode *inode,
114                                 struct ext4_ext_path *path)
115 {
116         if (path->p_bh) {
117                 /* path points to block */
118                 return ext4_journal_get_write_access(handle, path->p_bh);
119         }
120         /* path points to leaf/index in inode body */
121         /* we use in-core data, no need to protect them */
122         return 0;
123 }
124
125 /*
126  * could return:
127  *  - EROFS
128  *  - ENOMEM
129  *  - EIO
130  */
131 static int ext4_ext_dirty(handle_t *handle, struct inode *inode,
132                                 struct ext4_ext_path *path)
133 {
134         int err;
135         if (path->p_bh) {
136                 /* path points to block */
137                 err = ext4_journal_dirty_metadata(handle, path->p_bh);
138         } else {
139                 /* path points to leaf/index in inode body */
140                 err = ext4_mark_inode_dirty(handle, inode);
141         }
142         return err;
143 }
144
145 static ext4_fsblk_t ext4_ext_find_goal(struct inode *inode,
146                               struct ext4_ext_path *path,
147                               ext4_lblk_t block)
148 {
149         struct ext4_inode_info *ei = EXT4_I(inode);
150         ext4_fsblk_t bg_start;
151         ext4_fsblk_t last_block;
152         ext4_grpblk_t colour;
153         int depth;
154
155         if (path) {
156                 struct ext4_extent *ex;
157                 depth = path->p_depth;
158
159                 /* try to predict block placement */
160                 ex = path[depth].p_ext;
161                 if (ex)
162                         return ext_pblock(ex)+(block-le32_to_cpu(ex->ee_block));
163
164                 /* it looks like index is empty;
165                  * try to find starting block from index itself */
166                 if (path[depth].p_bh)
167                         return path[depth].p_bh->b_blocknr;
168         }
169
170         /* OK. use inode's group */
171         bg_start = (ei->i_block_group * EXT4_BLOCKS_PER_GROUP(inode->i_sb)) +
172                 le32_to_cpu(EXT4_SB(inode->i_sb)->s_es->s_first_data_block);
173         last_block = ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es) - 1;
174
175         if (bg_start + EXT4_BLOCKS_PER_GROUP(inode->i_sb) <= last_block)
176                 colour = (current->pid % 16) *
177                         (EXT4_BLOCKS_PER_GROUP(inode->i_sb) / 16);
178         else
179                 colour = (current->pid % 16) * ((last_block - bg_start) / 16);
180         return bg_start + colour + block;
181 }
182
183 static ext4_fsblk_t
184 ext4_ext_new_block(handle_t *handle, struct inode *inode,
185                         struct ext4_ext_path *path,
186                         struct ext4_extent *ex, int *err)
187 {
188         ext4_fsblk_t goal, newblock;
189
190         goal = ext4_ext_find_goal(inode, path, le32_to_cpu(ex->ee_block));
191         newblock = ext4_new_block(handle, inode, goal, err);
192         return newblock;
193 }
194
195 static int ext4_ext_space_block(struct inode *inode)
196 {
197         int size;
198
199         size = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
200                         / sizeof(struct ext4_extent);
201 #ifdef AGGRESSIVE_TEST
202         if (size > 6)
203                 size = 6;
204 #endif
205         return size;
206 }
207
208 static int ext4_ext_space_block_idx(struct inode *inode)
209 {
210         int size;
211
212         size = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
213                         / sizeof(struct ext4_extent_idx);
214 #ifdef AGGRESSIVE_TEST
215         if (size > 5)
216                 size = 5;
217 #endif
218         return size;
219 }
220
221 static int ext4_ext_space_root(struct inode *inode)
222 {
223         int size;
224
225         size = sizeof(EXT4_I(inode)->i_data);
226         size -= sizeof(struct ext4_extent_header);
227         size /= sizeof(struct ext4_extent);
228 #ifdef AGGRESSIVE_TEST
229         if (size > 3)
230                 size = 3;
231 #endif
232         return size;
233 }
234
235 static int ext4_ext_space_root_idx(struct inode *inode)
236 {
237         int size;
238
239         size = sizeof(EXT4_I(inode)->i_data);
240         size -= sizeof(struct ext4_extent_header);
241         size /= sizeof(struct ext4_extent_idx);
242 #ifdef AGGRESSIVE_TEST
243         if (size > 4)
244                 size = 4;
245 #endif
246         return size;
247 }
248
249 static int
250 ext4_ext_max_entries(struct inode *inode, int depth)
251 {
252         int max;
253
254         if (depth == ext_depth(inode)) {
255                 if (depth == 0)
256                         max = ext4_ext_space_root(inode);
257                 else
258                         max = ext4_ext_space_root_idx(inode);
259         } else {
260                 if (depth == 0)
261                         max = ext4_ext_space_block(inode);
262                 else
263                         max = ext4_ext_space_block_idx(inode);
264         }
265
266         return max;
267 }
268
269 static int __ext4_ext_check_header(const char *function, struct inode *inode,
270                                         struct ext4_extent_header *eh,
271                                         int depth)
272 {
273         const char *error_msg;
274         int max = 0;
275
276         if (unlikely(eh->eh_magic != EXT4_EXT_MAGIC)) {
277                 error_msg = "invalid magic";
278                 goto corrupted;
279         }
280         if (unlikely(le16_to_cpu(eh->eh_depth) != depth)) {
281                 error_msg = "unexpected eh_depth";
282                 goto corrupted;
283         }
284         if (unlikely(eh->eh_max == 0)) {
285                 error_msg = "invalid eh_max";
286                 goto corrupted;
287         }
288         max = ext4_ext_max_entries(inode, depth);
289         if (unlikely(le16_to_cpu(eh->eh_max) > max)) {
290                 error_msg = "too large eh_max";
291                 goto corrupted;
292         }
293         if (unlikely(le16_to_cpu(eh->eh_entries) > le16_to_cpu(eh->eh_max))) {
294                 error_msg = "invalid eh_entries";
295                 goto corrupted;
296         }
297         return 0;
298
299 corrupted:
300         ext4_error(inode->i_sb, function,
301                         "bad header in inode #%lu: %s - magic %x, "
302                         "entries %u, max %u(%u), depth %u(%u)",
303                         inode->i_ino, error_msg, le16_to_cpu(eh->eh_magic),
304                         le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max),
305                         max, le16_to_cpu(eh->eh_depth), depth);
306
307         return -EIO;
308 }
309
310 #define ext4_ext_check_header(inode, eh, depth) \
311         __ext4_ext_check_header(__func__, inode, eh, depth)
312
313 #ifdef EXT_DEBUG
314 static void ext4_ext_show_path(struct inode *inode, struct ext4_ext_path *path)
315 {
316         int k, l = path->p_depth;
317
318         ext_debug("path:");
319         for (k = 0; k <= l; k++, path++) {
320                 if (path->p_idx) {
321                   ext_debug("  %d->%llu", le32_to_cpu(path->p_idx->ei_block),
322                             idx_pblock(path->p_idx));
323                 } else if (path->p_ext) {
324                         ext_debug("  %d:%d:%llu ",
325                                   le32_to_cpu(path->p_ext->ee_block),
326                                   ext4_ext_get_actual_len(path->p_ext),
327                                   ext_pblock(path->p_ext));
328                 } else
329                         ext_debug("  []");
330         }
331         ext_debug("\n");
332 }
333
334 static void ext4_ext_show_leaf(struct inode *inode, struct ext4_ext_path *path)
335 {
336         int depth = ext_depth(inode);
337         struct ext4_extent_header *eh;
338         struct ext4_extent *ex;
339         int i;
340
341         if (!path)
342                 return;
343
344         eh = path[depth].p_hdr;
345         ex = EXT_FIRST_EXTENT(eh);
346
347         for (i = 0; i < le16_to_cpu(eh->eh_entries); i++, ex++) {
348                 ext_debug("%d:%d:%llu ", le32_to_cpu(ex->ee_block),
349                           ext4_ext_get_actual_len(ex), ext_pblock(ex));
350         }
351         ext_debug("\n");
352 }
353 #else
354 #define ext4_ext_show_path(inode,path)
355 #define ext4_ext_show_leaf(inode,path)
356 #endif
357
358 void ext4_ext_drop_refs(struct ext4_ext_path *path)
359 {
360         int depth = path->p_depth;
361         int i;
362
363         for (i = 0; i <= depth; i++, path++)
364                 if (path->p_bh) {
365                         brelse(path->p_bh);
366                         path->p_bh = NULL;
367                 }
368 }
369
370 /*
371  * ext4_ext_binsearch_idx:
372  * binary search for the closest index of the given block
373  * the header must be checked before calling this
374  */
375 static void
376 ext4_ext_binsearch_idx(struct inode *inode,
377                         struct ext4_ext_path *path, ext4_lblk_t block)
378 {
379         struct ext4_extent_header *eh = path->p_hdr;
380         struct ext4_extent_idx *r, *l, *m;
381
382
383         ext_debug("binsearch for %u(idx):  ", block);
384
385         l = EXT_FIRST_INDEX(eh) + 1;
386         r = EXT_LAST_INDEX(eh);
387         while (l <= r) {
388                 m = l + (r - l) / 2;
389                 if (block < le32_to_cpu(m->ei_block))
390                         r = m - 1;
391                 else
392                         l = m + 1;
393                 ext_debug("%p(%u):%p(%u):%p(%u) ", l, le32_to_cpu(l->ei_block),
394                                 m, le32_to_cpu(m->ei_block),
395                                 r, le32_to_cpu(r->ei_block));
396         }
397
398         path->p_idx = l - 1;
399         ext_debug("  -> %d->%lld ", le32_to_cpu(path->p_idx->ei_block),
400                   idx_pblock(path->p_idx));
401
402 #ifdef CHECK_BINSEARCH
403         {
404                 struct ext4_extent_idx *chix, *ix;
405                 int k;
406
407                 chix = ix = EXT_FIRST_INDEX(eh);
408                 for (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ix++) {
409                   if (k != 0 &&
410                       le32_to_cpu(ix->ei_block) <= le32_to_cpu(ix[-1].ei_block)) {
411                                 printk("k=%d, ix=0x%p, first=0x%p\n", k,
412                                         ix, EXT_FIRST_INDEX(eh));
413                                 printk("%u <= %u\n",
414                                        le32_to_cpu(ix->ei_block),
415                                        le32_to_cpu(ix[-1].ei_block));
416                         }
417                         BUG_ON(k && le32_to_cpu(ix->ei_block)
418                                            <= le32_to_cpu(ix[-1].ei_block));
419                         if (block < le32_to_cpu(ix->ei_block))
420                                 break;
421                         chix = ix;
422                 }
423                 BUG_ON(chix != path->p_idx);
424         }
425 #endif
426
427 }
428
429 /*
430  * ext4_ext_binsearch:
431  * binary search for closest extent of the given block
432  * the header must be checked before calling this
433  */
434 static void
435 ext4_ext_binsearch(struct inode *inode,
436                 struct ext4_ext_path *path, ext4_lblk_t block)
437 {
438         struct ext4_extent_header *eh = path->p_hdr;
439         struct ext4_extent *r, *l, *m;
440
441         if (eh->eh_entries == 0) {
442                 /*
443                  * this leaf is empty:
444                  * we get such a leaf in split/add case
445                  */
446                 return;
447         }
448
449         ext_debug("binsearch for %u:  ", block);
450
451         l = EXT_FIRST_EXTENT(eh) + 1;
452         r = EXT_LAST_EXTENT(eh);
453
454         while (l <= r) {
455                 m = l + (r - l) / 2;
456                 if (block < le32_to_cpu(m->ee_block))
457                         r = m - 1;
458                 else
459                         l = m + 1;
460                 ext_debug("%p(%u):%p(%u):%p(%u) ", l, le32_to_cpu(l->ee_block),
461                                 m, le32_to_cpu(m->ee_block),
462                                 r, le32_to_cpu(r->ee_block));
463         }
464
465         path->p_ext = l - 1;
466         ext_debug("  -> %d:%llu:%d ",
467                         le32_to_cpu(path->p_ext->ee_block),
468                         ext_pblock(path->p_ext),
469                         ext4_ext_get_actual_len(path->p_ext));
470
471 #ifdef CHECK_BINSEARCH
472         {
473                 struct ext4_extent *chex, *ex;
474                 int k;
475
476                 chex = ex = EXT_FIRST_EXTENT(eh);
477                 for (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ex++) {
478                         BUG_ON(k && le32_to_cpu(ex->ee_block)
479                                           <= le32_to_cpu(ex[-1].ee_block));
480                         if (block < le32_to_cpu(ex->ee_block))
481                                 break;
482                         chex = ex;
483                 }
484                 BUG_ON(chex != path->p_ext);
485         }
486 #endif
487
488 }
489
490 int ext4_ext_tree_init(handle_t *handle, struct inode *inode)
491 {
492         struct ext4_extent_header *eh;
493
494         eh = ext_inode_hdr(inode);
495         eh->eh_depth = 0;
496         eh->eh_entries = 0;
497         eh->eh_magic = EXT4_EXT_MAGIC;
498         eh->eh_max = cpu_to_le16(ext4_ext_space_root(inode));
499         ext4_mark_inode_dirty(handle, inode);
500         ext4_ext_invalidate_cache(inode);
501         return 0;
502 }
503
504 struct ext4_ext_path *
505 ext4_ext_find_extent(struct inode *inode, ext4_lblk_t block,
506                                         struct ext4_ext_path *path)
507 {
508         struct ext4_extent_header *eh;
509         struct buffer_head *bh;
510         short int depth, i, ppos = 0, alloc = 0;
511
512         eh = ext_inode_hdr(inode);
513         depth = ext_depth(inode);
514         if (ext4_ext_check_header(inode, eh, depth))
515                 return ERR_PTR(-EIO);
516
517
518         /* account possible depth increase */
519         if (!path) {
520                 path = kzalloc(sizeof(struct ext4_ext_path) * (depth + 2),
521                                 GFP_NOFS);
522                 if (!path)
523                         return ERR_PTR(-ENOMEM);
524                 alloc = 1;
525         }
526         path[0].p_hdr = eh;
527
528         i = depth;
529         /* walk through the tree */
530         while (i) {
531                 ext_debug("depth %d: num %d, max %d\n",
532                           ppos, le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
533
534                 ext4_ext_binsearch_idx(inode, path + ppos, block);
535                 path[ppos].p_block = idx_pblock(path[ppos].p_idx);
536                 path[ppos].p_depth = i;
537                 path[ppos].p_ext = NULL;
538
539                 bh = sb_bread(inode->i_sb, path[ppos].p_block);
540                 if (!bh)
541                         goto err;
542
543                 eh = ext_block_hdr(bh);
544                 ppos++;
545                 BUG_ON(ppos > depth);
546                 path[ppos].p_bh = bh;
547                 path[ppos].p_hdr = eh;
548                 i--;
549
550                 if (ext4_ext_check_header(inode, eh, i))
551                         goto err;
552         }
553
554         path[ppos].p_depth = i;
555         path[ppos].p_hdr = eh;
556         path[ppos].p_ext = NULL;
557         path[ppos].p_idx = NULL;
558
559         /* find extent */
560         ext4_ext_binsearch(inode, path + ppos, block);
561
562         ext4_ext_show_path(inode, path);
563
564         return path;
565
566 err:
567         ext4_ext_drop_refs(path);
568         if (alloc)
569                 kfree(path);
570         return ERR_PTR(-EIO);
571 }
572
573 /*
574  * ext4_ext_insert_index:
575  * insert new index [@logical;@ptr] into the block at @curp;
576  * check where to insert: before @curp or after @curp
577  */
578 static int ext4_ext_insert_index(handle_t *handle, struct inode *inode,
579                                 struct ext4_ext_path *curp,
580                                 int logical, ext4_fsblk_t ptr)
581 {
582         struct ext4_extent_idx *ix;
583         int len, err;
584
585         err = ext4_ext_get_access(handle, inode, curp);
586         if (err)
587                 return err;
588
589         BUG_ON(logical == le32_to_cpu(curp->p_idx->ei_block));
590         len = EXT_MAX_INDEX(curp->p_hdr) - curp->p_idx;
591         if (logical > le32_to_cpu(curp->p_idx->ei_block)) {
592                 /* insert after */
593                 if (curp->p_idx != EXT_LAST_INDEX(curp->p_hdr)) {
594                         len = (len - 1) * sizeof(struct ext4_extent_idx);
595                         len = len < 0 ? 0 : len;
596                         ext_debug("insert new index %d after: %llu. "
597                                         "move %d from 0x%p to 0x%p\n",
598                                         logical, ptr, len,
599                                         (curp->p_idx + 1), (curp->p_idx + 2));
600                         memmove(curp->p_idx + 2, curp->p_idx + 1, len);
601                 }
602                 ix = curp->p_idx + 1;
603         } else {
604                 /* insert before */
605                 len = len * sizeof(struct ext4_extent_idx);
606                 len = len < 0 ? 0 : len;
607                 ext_debug("insert new index %d before: %llu. "
608                                 "move %d from 0x%p to 0x%p\n",
609                                 logical, ptr, len,
610                                 curp->p_idx, (curp->p_idx + 1));
611                 memmove(curp->p_idx + 1, curp->p_idx, len);
612                 ix = curp->p_idx;
613         }
614
615         ix->ei_block = cpu_to_le32(logical);
616         ext4_idx_store_pblock(ix, ptr);
617         le16_add_cpu(&curp->p_hdr->eh_entries, 1);
618
619         BUG_ON(le16_to_cpu(curp->p_hdr->eh_entries)
620                              > le16_to_cpu(curp->p_hdr->eh_max));
621         BUG_ON(ix > EXT_LAST_INDEX(curp->p_hdr));
622
623         err = ext4_ext_dirty(handle, inode, curp);
624         ext4_std_error(inode->i_sb, err);
625
626         return err;
627 }
628
629 /*
630  * ext4_ext_split:
631  * inserts new subtree into the path, using free index entry
632  * at depth @at:
633  * - allocates all needed blocks (new leaf and all intermediate index blocks)
634  * - makes decision where to split
635  * - moves remaining extents and index entries (right to the split point)
636  *   into the newly allocated blocks
637  * - initializes subtree
638  */
639 static int ext4_ext_split(handle_t *handle, struct inode *inode,
640                                 struct ext4_ext_path *path,
641                                 struct ext4_extent *newext, int at)
642 {
643         struct buffer_head *bh = NULL;
644         int depth = ext_depth(inode);
645         struct ext4_extent_header *neh;
646         struct ext4_extent_idx *fidx;
647         struct ext4_extent *ex;
648         int i = at, k, m, a;
649         ext4_fsblk_t newblock, oldblock;
650         __le32 border;
651         ext4_fsblk_t *ablocks = NULL; /* array of allocated blocks */
652         int err = 0;
653
654         /* make decision: where to split? */
655         /* FIXME: now decision is simplest: at current extent */
656
657         /* if current leaf will be split, then we should use
658          * border from split point */
659         BUG_ON(path[depth].p_ext > EXT_MAX_EXTENT(path[depth].p_hdr));
660         if (path[depth].p_ext != EXT_MAX_EXTENT(path[depth].p_hdr)) {
661                 border = path[depth].p_ext[1].ee_block;
662                 ext_debug("leaf will be split."
663                                 " next leaf starts at %d\n",
664                                   le32_to_cpu(border));
665         } else {
666                 border = newext->ee_block;
667                 ext_debug("leaf will be added."
668                                 " next leaf starts at %d\n",
669                                 le32_to_cpu(border));
670         }
671
672         /*
673          * If error occurs, then we break processing
674          * and mark filesystem read-only. index won't
675          * be inserted and tree will be in consistent
676          * state. Next mount will repair buffers too.
677          */
678
679         /*
680          * Get array to track all allocated blocks.
681          * We need this to handle errors and free blocks
682          * upon them.
683          */
684         ablocks = kzalloc(sizeof(ext4_fsblk_t) * depth, GFP_NOFS);
685         if (!ablocks)
686                 return -ENOMEM;
687
688         /* allocate all needed blocks */
689         ext_debug("allocate %d blocks for indexes/leaf\n", depth - at);
690         for (a = 0; a < depth - at; a++) {
691                 newblock = ext4_ext_new_block(handle, inode, path, newext, &err);
692                 if (newblock == 0)
693                         goto cleanup;
694                 ablocks[a] = newblock;
695         }
696
697         /* initialize new leaf */
698         newblock = ablocks[--a];
699         BUG_ON(newblock == 0);
700         bh = sb_getblk(inode->i_sb, newblock);
701         if (!bh) {
702                 err = -EIO;
703                 goto cleanup;
704         }
705         lock_buffer(bh);
706
707         err = ext4_journal_get_create_access(handle, bh);
708         if (err)
709                 goto cleanup;
710
711         neh = ext_block_hdr(bh);
712         neh->eh_entries = 0;
713         neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode));
714         neh->eh_magic = EXT4_EXT_MAGIC;
715         neh->eh_depth = 0;
716         ex = EXT_FIRST_EXTENT(neh);
717
718         /* move remainder of path[depth] to the new leaf */
719         BUG_ON(path[depth].p_hdr->eh_entries != path[depth].p_hdr->eh_max);
720         /* start copy from next extent */
721         /* TODO: we could do it by single memmove */
722         m = 0;
723         path[depth].p_ext++;
724         while (path[depth].p_ext <=
725                         EXT_MAX_EXTENT(path[depth].p_hdr)) {
726                 ext_debug("move %d:%llu:%d in new leaf %llu\n",
727                                 le32_to_cpu(path[depth].p_ext->ee_block),
728                                 ext_pblock(path[depth].p_ext),
729                                 ext4_ext_get_actual_len(path[depth].p_ext),
730                                 newblock);
731                 /*memmove(ex++, path[depth].p_ext++,
732                                 sizeof(struct ext4_extent));
733                 neh->eh_entries++;*/
734                 path[depth].p_ext++;
735                 m++;
736         }
737         if (m) {
738                 memmove(ex, path[depth].p_ext-m, sizeof(struct ext4_extent)*m);
739                 le16_add_cpu(&neh->eh_entries, m);
740         }
741
742         set_buffer_uptodate(bh);
743         unlock_buffer(bh);
744
745         err = ext4_journal_dirty_metadata(handle, bh);
746         if (err)
747                 goto cleanup;
748         brelse(bh);
749         bh = NULL;
750
751         /* correct old leaf */
752         if (m) {
753                 err = ext4_ext_get_access(handle, inode, path + depth);
754                 if (err)
755                         goto cleanup;
756                 le16_add_cpu(&path[depth].p_hdr->eh_entries, -m);
757                 err = ext4_ext_dirty(handle, inode, path + depth);
758                 if (err)
759                         goto cleanup;
760
761         }
762
763         /* create intermediate indexes */
764         k = depth - at - 1;
765         BUG_ON(k < 0);
766         if (k)
767                 ext_debug("create %d intermediate indices\n", k);
768         /* insert new index into current index block */
769         /* current depth stored in i var */
770         i = depth - 1;
771         while (k--) {
772                 oldblock = newblock;
773                 newblock = ablocks[--a];
774                 bh = sb_getblk(inode->i_sb, newblock);
775                 if (!bh) {
776                         err = -EIO;
777                         goto cleanup;
778                 }
779                 lock_buffer(bh);
780
781                 err = ext4_journal_get_create_access(handle, bh);
782                 if (err)
783                         goto cleanup;
784
785                 neh = ext_block_hdr(bh);
786                 neh->eh_entries = cpu_to_le16(1);
787                 neh->eh_magic = EXT4_EXT_MAGIC;
788                 neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode));
789                 neh->eh_depth = cpu_to_le16(depth - i);
790                 fidx = EXT_FIRST_INDEX(neh);
791                 fidx->ei_block = border;
792                 ext4_idx_store_pblock(fidx, oldblock);
793
794                 ext_debug("int.index at %d (block %llu): %u -> %llu\n",
795                                 i, newblock, le32_to_cpu(border), oldblock);
796                 /* copy indexes */
797                 m = 0;
798                 path[i].p_idx++;
799
800                 ext_debug("cur 0x%p, last 0x%p\n", path[i].p_idx,
801                                 EXT_MAX_INDEX(path[i].p_hdr));
802                 BUG_ON(EXT_MAX_INDEX(path[i].p_hdr) !=
803                                 EXT_LAST_INDEX(path[i].p_hdr));
804                 while (path[i].p_idx <= EXT_MAX_INDEX(path[i].p_hdr)) {
805                         ext_debug("%d: move %d:%llu in new index %llu\n", i,
806                                         le32_to_cpu(path[i].p_idx->ei_block),
807                                         idx_pblock(path[i].p_idx),
808                                         newblock);
809                         /*memmove(++fidx, path[i].p_idx++,
810                                         sizeof(struct ext4_extent_idx));
811                         neh->eh_entries++;
812                         BUG_ON(neh->eh_entries > neh->eh_max);*/
813                         path[i].p_idx++;
814                         m++;
815                 }
816                 if (m) {
817                         memmove(++fidx, path[i].p_idx - m,
818                                 sizeof(struct ext4_extent_idx) * m);
819                         le16_add_cpu(&neh->eh_entries, m);
820                 }
821                 set_buffer_uptodate(bh);
822                 unlock_buffer(bh);
823
824                 err = ext4_journal_dirty_metadata(handle, bh);
825                 if (err)
826                         goto cleanup;
827                 brelse(bh);
828                 bh = NULL;
829
830                 /* correct old index */
831                 if (m) {
832                         err = ext4_ext_get_access(handle, inode, path + i);
833                         if (err)
834                                 goto cleanup;
835                         le16_add_cpu(&path[i].p_hdr->eh_entries, -m);
836                         err = ext4_ext_dirty(handle, inode, path + i);
837                         if (err)
838                                 goto cleanup;
839                 }
840
841                 i--;
842         }
843
844         /* insert new index */
845         err = ext4_ext_insert_index(handle, inode, path + at,
846                                     le32_to_cpu(border), newblock);
847
848 cleanup:
849         if (bh) {
850                 if (buffer_locked(bh))
851                         unlock_buffer(bh);
852                 brelse(bh);
853         }
854
855         if (err) {
856                 /* free all allocated blocks in error case */
857                 for (i = 0; i < depth; i++) {
858                         if (!ablocks[i])
859                                 continue;
860                         ext4_free_blocks(handle, inode, ablocks[i], 1, 1);
861                 }
862         }
863         kfree(ablocks);
864
865         return err;
866 }
867
868 /*
869  * ext4_ext_grow_indepth:
870  * implements tree growing procedure:
871  * - allocates new block
872  * - moves top-level data (index block or leaf) into the new block
873  * - initializes new top-level, creating index that points to the
874  *   just created block
875  */
876 static int ext4_ext_grow_indepth(handle_t *handle, struct inode *inode,
877                                         struct ext4_ext_path *path,
878                                         struct ext4_extent *newext)
879 {
880         struct ext4_ext_path *curp = path;
881         struct ext4_extent_header *neh;
882         struct ext4_extent_idx *fidx;
883         struct buffer_head *bh;
884         ext4_fsblk_t newblock;
885         int err = 0;
886
887         newblock = ext4_ext_new_block(handle, inode, path, newext, &err);
888         if (newblock == 0)
889                 return err;
890
891         bh = sb_getblk(inode->i_sb, newblock);
892         if (!bh) {
893                 err = -EIO;
894                 ext4_std_error(inode->i_sb, err);
895                 return err;
896         }
897         lock_buffer(bh);
898
899         err = ext4_journal_get_create_access(handle, bh);
900         if (err) {
901                 unlock_buffer(bh);
902                 goto out;
903         }
904
905         /* move top-level index/leaf into new block */
906         memmove(bh->b_data, curp->p_hdr, sizeof(EXT4_I(inode)->i_data));
907
908         /* set size of new block */
909         neh = ext_block_hdr(bh);
910         /* old root could have indexes or leaves
911          * so calculate e_max right way */
912         if (ext_depth(inode))
913           neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode));
914         else
915           neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode));
916         neh->eh_magic = EXT4_EXT_MAGIC;
917         set_buffer_uptodate(bh);
918         unlock_buffer(bh);
919
920         err = ext4_journal_dirty_metadata(handle, bh);
921         if (err)
922                 goto out;
923
924         /* create index in new top-level index: num,max,pointer */
925         err = ext4_ext_get_access(handle, inode, curp);
926         if (err)
927                 goto out;
928
929         curp->p_hdr->eh_magic = EXT4_EXT_MAGIC;
930         curp->p_hdr->eh_max = cpu_to_le16(ext4_ext_space_root_idx(inode));
931         curp->p_hdr->eh_entries = cpu_to_le16(1);
932         curp->p_idx = EXT_FIRST_INDEX(curp->p_hdr);
933
934         if (path[0].p_hdr->eh_depth)
935                 curp->p_idx->ei_block =
936                         EXT_FIRST_INDEX(path[0].p_hdr)->ei_block;
937         else
938                 curp->p_idx->ei_block =
939                         EXT_FIRST_EXTENT(path[0].p_hdr)->ee_block;
940         ext4_idx_store_pblock(curp->p_idx, newblock);
941
942         neh = ext_inode_hdr(inode);
943         fidx = EXT_FIRST_INDEX(neh);
944         ext_debug("new root: num %d(%d), lblock %d, ptr %llu\n",
945                   le16_to_cpu(neh->eh_entries), le16_to_cpu(neh->eh_max),
946                   le32_to_cpu(fidx->ei_block), idx_pblock(fidx));
947
948         neh->eh_depth = cpu_to_le16(path->p_depth + 1);
949         err = ext4_ext_dirty(handle, inode, curp);
950 out:
951         brelse(bh);
952
953         return err;
954 }
955
956 /*
957  * ext4_ext_create_new_leaf:
958  * finds empty index and adds new leaf.
959  * if no free index is found, then it requests in-depth growing.
960  */
961 static int ext4_ext_create_new_leaf(handle_t *handle, struct inode *inode,
962                                         struct ext4_ext_path *path,
963                                         struct ext4_extent *newext)
964 {
965         struct ext4_ext_path *curp;
966         int depth, i, err = 0;
967
968 repeat:
969         i = depth = ext_depth(inode);
970
971         /* walk up to the tree and look for free index entry */
972         curp = path + depth;
973         while (i > 0 && !EXT_HAS_FREE_INDEX(curp)) {
974                 i--;
975                 curp--;
976         }
977
978         /* we use already allocated block for index block,
979          * so subsequent data blocks should be contiguous */
980         if (EXT_HAS_FREE_INDEX(curp)) {
981                 /* if we found index with free entry, then use that
982                  * entry: create all needed subtree and add new leaf */
983                 err = ext4_ext_split(handle, inode, path, newext, i);
984
985                 /* refill path */
986                 ext4_ext_drop_refs(path);
987                 path = ext4_ext_find_extent(inode,
988                                     (ext4_lblk_t)le32_to_cpu(newext->ee_block),
989                                     path);
990                 if (IS_ERR(path))
991                         err = PTR_ERR(path);
992         } else {
993                 /* tree is full, time to grow in depth */
994                 err = ext4_ext_grow_indepth(handle, inode, path, newext);
995                 if (err)
996                         goto out;
997
998                 /* refill path */
999                 ext4_ext_drop_refs(path);
1000                 path = ext4_ext_find_extent(inode,
1001                                    (ext4_lblk_t)le32_to_cpu(newext->ee_block),
1002                                     path);
1003                 if (IS_ERR(path)) {
1004                         err = PTR_ERR(path);
1005                         goto out;
1006                 }
1007
1008                 /*
1009                  * only first (depth 0 -> 1) produces free space;
1010                  * in all other cases we have to split the grown tree
1011                  */
1012                 depth = ext_depth(inode);
1013                 if (path[depth].p_hdr->eh_entries == path[depth].p_hdr->eh_max) {
1014                         /* now we need to split */
1015                         goto repeat;
1016                 }
1017         }
1018
1019 out:
1020         return err;
1021 }
1022
1023 /*
1024  * search the closest allocated block to the left for *logical
1025  * and returns it at @logical + it's physical address at @phys
1026  * if *logical is the smallest allocated block, the function
1027  * returns 0 at @phys
1028  * return value contains 0 (success) or error code
1029  */
1030 int
1031 ext4_ext_search_left(struct inode *inode, struct ext4_ext_path *path,
1032                         ext4_lblk_t *logical, ext4_fsblk_t *phys)
1033 {
1034         struct ext4_extent_idx *ix;
1035         struct ext4_extent *ex;
1036         int depth, ee_len;
1037
1038         BUG_ON(path == NULL);
1039         depth = path->p_depth;
1040         *phys = 0;
1041
1042         if (depth == 0 && path->p_ext == NULL)
1043                 return 0;
1044
1045         /* usually extent in the path covers blocks smaller
1046          * then *logical, but it can be that extent is the
1047          * first one in the file */
1048
1049         ex = path[depth].p_ext;
1050         ee_len = ext4_ext_get_actual_len(ex);
1051         if (*logical < le32_to_cpu(ex->ee_block)) {
1052                 BUG_ON(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex);
1053                 while (--depth >= 0) {
1054                         ix = path[depth].p_idx;
1055                         BUG_ON(ix != EXT_FIRST_INDEX(path[depth].p_hdr));
1056                 }
1057                 return 0;
1058         }
1059
1060         BUG_ON(*logical < (le32_to_cpu(ex->ee_block) + ee_len));
1061
1062         *logical = le32_to_cpu(ex->ee_block) + ee_len - 1;
1063         *phys = ext_pblock(ex) + ee_len - 1;
1064         return 0;
1065 }
1066
1067 /*
1068  * search the closest allocated block to the right for *logical
1069  * and returns it at @logical + it's physical address at @phys
1070  * if *logical is the smallest allocated block, the function
1071  * returns 0 at @phys
1072  * return value contains 0 (success) or error code
1073  */
1074 int
1075 ext4_ext_search_right(struct inode *inode, struct ext4_ext_path *path,
1076                         ext4_lblk_t *logical, ext4_fsblk_t *phys)
1077 {
1078         struct buffer_head *bh = NULL;
1079         struct ext4_extent_header *eh;
1080         struct ext4_extent_idx *ix;
1081         struct ext4_extent *ex;
1082         ext4_fsblk_t block;
1083         int depth, ee_len;
1084
1085         BUG_ON(path == NULL);
1086         depth = path->p_depth;
1087         *phys = 0;
1088
1089         if (depth == 0 && path->p_ext == NULL)
1090                 return 0;
1091
1092         /* usually extent in the path covers blocks smaller
1093          * then *logical, but it can be that extent is the
1094          * first one in the file */
1095
1096         ex = path[depth].p_ext;
1097         ee_len = ext4_ext_get_actual_len(ex);
1098         if (*logical < le32_to_cpu(ex->ee_block)) {
1099                 BUG_ON(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex);
1100                 while (--depth >= 0) {
1101                         ix = path[depth].p_idx;
1102                         BUG_ON(ix != EXT_FIRST_INDEX(path[depth].p_hdr));
1103                 }
1104                 *logical = le32_to_cpu(ex->ee_block);
1105                 *phys = ext_pblock(ex);
1106                 return 0;
1107         }
1108
1109         BUG_ON(*logical < (le32_to_cpu(ex->ee_block) + ee_len));
1110
1111         if (ex != EXT_LAST_EXTENT(path[depth].p_hdr)) {
1112                 /* next allocated block in this leaf */
1113                 ex++;
1114                 *logical = le32_to_cpu(ex->ee_block);
1115                 *phys = ext_pblock(ex);
1116                 return 0;
1117         }
1118
1119         /* go up and search for index to the right */
1120         while (--depth >= 0) {
1121                 ix = path[depth].p_idx;
1122                 if (ix != EXT_LAST_INDEX(path[depth].p_hdr))
1123                         break;
1124         }
1125
1126         if (depth < 0) {
1127                 /* we've gone up to the root and
1128                  * found no index to the right */
1129                 return 0;
1130         }
1131
1132         /* we've found index to the right, let's
1133          * follow it and find the closest allocated
1134          * block to the right */
1135         ix++;
1136         block = idx_pblock(ix);
1137         while (++depth < path->p_depth) {
1138                 bh = sb_bread(inode->i_sb, block);
1139                 if (bh == NULL)
1140                         return -EIO;
1141                 eh = ext_block_hdr(bh);
1142                 if (ext4_ext_check_header(inode, eh, depth)) {
1143                         put_bh(bh);
1144                         return -EIO;
1145                 }
1146                 ix = EXT_FIRST_INDEX(eh);
1147                 block = idx_pblock(ix);
1148                 put_bh(bh);
1149         }
1150
1151         bh = sb_bread(inode->i_sb, block);
1152         if (bh == NULL)
1153                 return -EIO;
1154         eh = ext_block_hdr(bh);
1155         if (ext4_ext_check_header(inode, eh, path->p_depth - depth)) {
1156                 put_bh(bh);
1157                 return -EIO;
1158         }
1159         ex = EXT_FIRST_EXTENT(eh);
1160         *logical = le32_to_cpu(ex->ee_block);
1161         *phys = ext_pblock(ex);
1162         put_bh(bh);
1163         return 0;
1164
1165 }
1166
1167 /*
1168  * ext4_ext_next_allocated_block:
1169  * returns allocated block in subsequent extent or EXT_MAX_BLOCK.
1170  * NOTE: it considers block number from index entry as
1171  * allocated block. Thus, index entries have to be consistent
1172  * with leaves.
1173  */
1174 static ext4_lblk_t
1175 ext4_ext_next_allocated_block(struct ext4_ext_path *path)
1176 {
1177         int depth;
1178
1179         BUG_ON(path == NULL);
1180         depth = path->p_depth;
1181
1182         if (depth == 0 && path->p_ext == NULL)
1183                 return EXT_MAX_BLOCK;
1184
1185         while (depth >= 0) {
1186                 if (depth == path->p_depth) {
1187                         /* leaf */
1188                         if (path[depth].p_ext !=
1189                                         EXT_LAST_EXTENT(path[depth].p_hdr))
1190                           return le32_to_cpu(path[depth].p_ext[1].ee_block);
1191                 } else {
1192                         /* index */
1193                         if (path[depth].p_idx !=
1194                                         EXT_LAST_INDEX(path[depth].p_hdr))
1195                           return le32_to_cpu(path[depth].p_idx[1].ei_block);
1196                 }
1197                 depth--;
1198         }
1199
1200         return EXT_MAX_BLOCK;
1201 }
1202
1203 /*
1204  * ext4_ext_next_leaf_block:
1205  * returns first allocated block from next leaf or EXT_MAX_BLOCK
1206  */
1207 static ext4_lblk_t ext4_ext_next_leaf_block(struct inode *inode,
1208                                         struct ext4_ext_path *path)
1209 {
1210         int depth;
1211
1212         BUG_ON(path == NULL);
1213         depth = path->p_depth;
1214
1215         /* zero-tree has no leaf blocks at all */
1216         if (depth == 0)
1217                 return EXT_MAX_BLOCK;
1218
1219         /* go to index block */
1220         depth--;
1221
1222         while (depth >= 0) {
1223                 if (path[depth].p_idx !=
1224                                 EXT_LAST_INDEX(path[depth].p_hdr))
1225                         return (ext4_lblk_t)
1226                                 le32_to_cpu(path[depth].p_idx[1].ei_block);
1227                 depth--;
1228         }
1229
1230         return EXT_MAX_BLOCK;
1231 }
1232
1233 /*
1234  * ext4_ext_correct_indexes:
1235  * if leaf gets modified and modified extent is first in the leaf,
1236  * then we have to correct all indexes above.
1237  * TODO: do we need to correct tree in all cases?
1238  */
1239 static int ext4_ext_correct_indexes(handle_t *handle, struct inode *inode,
1240                                 struct ext4_ext_path *path)
1241 {
1242         struct ext4_extent_header *eh;
1243         int depth = ext_depth(inode);
1244         struct ext4_extent *ex;
1245         __le32 border;
1246         int k, err = 0;
1247
1248         eh = path[depth].p_hdr;
1249         ex = path[depth].p_ext;
1250         BUG_ON(ex == NULL);
1251         BUG_ON(eh == NULL);
1252
1253         if (depth == 0) {
1254                 /* there is no tree at all */
1255                 return 0;
1256         }
1257
1258         if (ex != EXT_FIRST_EXTENT(eh)) {
1259                 /* we correct tree if first leaf got modified only */
1260                 return 0;
1261         }
1262
1263         /*
1264          * TODO: we need correction if border is smaller than current one
1265          */
1266         k = depth - 1;
1267         border = path[depth].p_ext->ee_block;
1268         err = ext4_ext_get_access(handle, inode, path + k);
1269         if (err)
1270                 return err;
1271         path[k].p_idx->ei_block = border;
1272         err = ext4_ext_dirty(handle, inode, path + k);
1273         if (err)
1274                 return err;
1275
1276         while (k--) {
1277                 /* change all left-side indexes */
1278                 if (path[k+1].p_idx != EXT_FIRST_INDEX(path[k+1].p_hdr))
1279                         break;
1280                 err = ext4_ext_get_access(handle, inode, path + k);
1281                 if (err)
1282                         break;
1283                 path[k].p_idx->ei_block = border;
1284                 err = ext4_ext_dirty(handle, inode, path + k);
1285                 if (err)
1286                         break;
1287         }
1288
1289         return err;
1290 }
1291
1292 static int
1293 ext4_can_extents_be_merged(struct inode *inode, struct ext4_extent *ex1,
1294                                 struct ext4_extent *ex2)
1295 {
1296         unsigned short ext1_ee_len, ext2_ee_len, max_len;
1297
1298         /*
1299          * Make sure that either both extents are uninitialized, or
1300          * both are _not_.
1301          */
1302         if (ext4_ext_is_uninitialized(ex1) ^ ext4_ext_is_uninitialized(ex2))
1303                 return 0;
1304
1305         if (ext4_ext_is_uninitialized(ex1))
1306                 max_len = EXT_UNINIT_MAX_LEN;
1307         else
1308                 max_len = EXT_INIT_MAX_LEN;
1309
1310         ext1_ee_len = ext4_ext_get_actual_len(ex1);
1311         ext2_ee_len = ext4_ext_get_actual_len(ex2);
1312
1313         if (le32_to_cpu(ex1->ee_block) + ext1_ee_len !=
1314                         le32_to_cpu(ex2->ee_block))
1315                 return 0;
1316
1317         /*
1318          * To allow future support for preallocated extents to be added
1319          * as an RO_COMPAT feature, refuse to merge to extents if
1320          * this can result in the top bit of ee_len being set.
1321          */
1322         if (ext1_ee_len + ext2_ee_len > max_len)
1323                 return 0;
1324 #ifdef AGGRESSIVE_TEST
1325         if (ext1_ee_len >= 4)
1326                 return 0;
1327 #endif
1328
1329         if (ext_pblock(ex1) + ext1_ee_len == ext_pblock(ex2))
1330                 return 1;
1331         return 0;
1332 }
1333
1334 /*
1335  * This function tries to merge the "ex" extent to the next extent in the tree.
1336  * It always tries to merge towards right. If you want to merge towards
1337  * left, pass "ex - 1" as argument instead of "ex".
1338  * Returns 0 if the extents (ex and ex+1) were _not_ merged and returns
1339  * 1 if they got merged.
1340  */
1341 int ext4_ext_try_to_merge(struct inode *inode,
1342                           struct ext4_ext_path *path,
1343                           struct ext4_extent *ex)
1344 {
1345         struct ext4_extent_header *eh;
1346         unsigned int depth, len;
1347         int merge_done = 0;
1348         int uninitialized = 0;
1349
1350         depth = ext_depth(inode);
1351         BUG_ON(path[depth].p_hdr == NULL);
1352         eh = path[depth].p_hdr;
1353
1354         while (ex < EXT_LAST_EXTENT(eh)) {
1355                 if (!ext4_can_extents_be_merged(inode, ex, ex + 1))
1356                         break;
1357                 /* merge with next extent! */
1358                 if (ext4_ext_is_uninitialized(ex))
1359                         uninitialized = 1;
1360                 ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
1361                                 + ext4_ext_get_actual_len(ex + 1));
1362                 if (uninitialized)
1363                         ext4_ext_mark_uninitialized(ex);
1364
1365                 if (ex + 1 < EXT_LAST_EXTENT(eh)) {
1366                         len = (EXT_LAST_EXTENT(eh) - ex - 1)
1367                                 * sizeof(struct ext4_extent);
1368                         memmove(ex + 1, ex + 2, len);
1369                 }
1370                 le16_add_cpu(&eh->eh_entries, -1);
1371                 merge_done = 1;
1372                 WARN_ON(eh->eh_entries == 0);
1373                 if (!eh->eh_entries)
1374                         ext4_error(inode->i_sb, "ext4_ext_try_to_merge",
1375                            "inode#%lu, eh->eh_entries = 0!", inode->i_ino);
1376         }
1377
1378         return merge_done;
1379 }
1380
1381 /*
1382  * check if a portion of the "newext" extent overlaps with an
1383  * existing extent.
1384  *
1385  * If there is an overlap discovered, it updates the length of the newext
1386  * such that there will be no overlap, and then returns 1.
1387  * If there is no overlap found, it returns 0.
1388  */
1389 unsigned int ext4_ext_check_overlap(struct inode *inode,
1390                                     struct ext4_extent *newext,
1391                                     struct ext4_ext_path *path)
1392 {
1393         ext4_lblk_t b1, b2;
1394         unsigned int depth, len1;
1395         unsigned int ret = 0;
1396
1397         b1 = le32_to_cpu(newext->ee_block);
1398         len1 = ext4_ext_get_actual_len(newext);
1399         depth = ext_depth(inode);
1400         if (!path[depth].p_ext)
1401                 goto out;
1402         b2 = le32_to_cpu(path[depth].p_ext->ee_block);
1403
1404         /*
1405          * get the next allocated block if the extent in the path
1406          * is before the requested block(s) 
1407          */
1408         if (b2 < b1) {
1409                 b2 = ext4_ext_next_allocated_block(path);
1410                 if (b2 == EXT_MAX_BLOCK)
1411                         goto out;
1412         }
1413
1414         /* check for wrap through zero on extent logical start block*/
1415         if (b1 + len1 < b1) {
1416                 len1 = EXT_MAX_BLOCK - b1;
1417                 newext->ee_len = cpu_to_le16(len1);
1418                 ret = 1;
1419         }
1420
1421         /* check for overlap */
1422         if (b1 + len1 > b2) {
1423                 newext->ee_len = cpu_to_le16(b2 - b1);
1424                 ret = 1;
1425         }
1426 out:
1427         return ret;
1428 }
1429
1430 /*
1431  * ext4_ext_insert_extent:
1432  * tries to merge requsted extent into the existing extent or
1433  * inserts requested extent as new one into the tree,
1434  * creating new leaf in the no-space case.
1435  */
1436 int ext4_ext_insert_extent(handle_t *handle, struct inode *inode,
1437                                 struct ext4_ext_path *path,
1438                                 struct ext4_extent *newext)
1439 {
1440         struct ext4_extent_header * eh;
1441         struct ext4_extent *ex, *fex;
1442         struct ext4_extent *nearex; /* nearest extent */
1443         struct ext4_ext_path *npath = NULL;
1444         int depth, len, err;
1445         ext4_lblk_t next;
1446         unsigned uninitialized = 0;
1447
1448         BUG_ON(ext4_ext_get_actual_len(newext) == 0);
1449         depth = ext_depth(inode);
1450         ex = path[depth].p_ext;
1451         BUG_ON(path[depth].p_hdr == NULL);
1452
1453         /* try to insert block into found extent and return */
1454         if (ex && ext4_can_extents_be_merged(inode, ex, newext)) {
1455                 ext_debug("append %d block to %d:%d (from %llu)\n",
1456                                 ext4_ext_get_actual_len(newext),
1457                                 le32_to_cpu(ex->ee_block),
1458                                 ext4_ext_get_actual_len(ex), ext_pblock(ex));
1459                 err = ext4_ext_get_access(handle, inode, path + depth);
1460                 if (err)
1461                         return err;
1462
1463                 /*
1464                  * ext4_can_extents_be_merged should have checked that either
1465                  * both extents are uninitialized, or both aren't. Thus we
1466                  * need to check only one of them here.
1467                  */
1468                 if (ext4_ext_is_uninitialized(ex))
1469                         uninitialized = 1;
1470                 ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
1471                                         + ext4_ext_get_actual_len(newext));
1472                 if (uninitialized)
1473                         ext4_ext_mark_uninitialized(ex);
1474                 eh = path[depth].p_hdr;
1475                 nearex = ex;
1476                 goto merge;
1477         }
1478
1479 repeat:
1480         depth = ext_depth(inode);
1481         eh = path[depth].p_hdr;
1482         if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max))
1483                 goto has_space;
1484
1485         /* probably next leaf has space for us? */
1486         fex = EXT_LAST_EXTENT(eh);
1487         next = ext4_ext_next_leaf_block(inode, path);
1488         if (le32_to_cpu(newext->ee_block) > le32_to_cpu(fex->ee_block)
1489             && next != EXT_MAX_BLOCK) {
1490                 ext_debug("next leaf block - %d\n", next);
1491                 BUG_ON(npath != NULL);
1492                 npath = ext4_ext_find_extent(inode, next, NULL);
1493                 if (IS_ERR(npath))
1494                         return PTR_ERR(npath);
1495                 BUG_ON(npath->p_depth != path->p_depth);
1496                 eh = npath[depth].p_hdr;
1497                 if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max)) {
1498                         ext_debug("next leaf isnt full(%d)\n",
1499                                   le16_to_cpu(eh->eh_entries));
1500                         path = npath;
1501                         goto repeat;
1502                 }
1503                 ext_debug("next leaf has no free space(%d,%d)\n",
1504                           le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
1505         }
1506
1507         /*
1508          * There is no free space in the found leaf.
1509          * We're gonna add a new leaf in the tree.
1510          */
1511         err = ext4_ext_create_new_leaf(handle, inode, path, newext);
1512         if (err)
1513                 goto cleanup;
1514         depth = ext_depth(inode);
1515         eh = path[depth].p_hdr;
1516
1517 has_space:
1518         nearex = path[depth].p_ext;
1519
1520         err = ext4_ext_get_access(handle, inode, path + depth);
1521         if (err)
1522                 goto cleanup;
1523
1524         if (!nearex) {
1525                 /* there is no extent in this leaf, create first one */
1526                 ext_debug("first extent in the leaf: %d:%llu:%d\n",
1527                                 le32_to_cpu(newext->ee_block),
1528                                 ext_pblock(newext),
1529                                 ext4_ext_get_actual_len(newext));
1530                 path[depth].p_ext = EXT_FIRST_EXTENT(eh);
1531         } else if (le32_to_cpu(newext->ee_block)
1532                            > le32_to_cpu(nearex->ee_block)) {
1533 /*              BUG_ON(newext->ee_block == nearex->ee_block); */
1534                 if (nearex != EXT_LAST_EXTENT(eh)) {
1535                         len = EXT_MAX_EXTENT(eh) - nearex;
1536                         len = (len - 1) * sizeof(struct ext4_extent);
1537                         len = len < 0 ? 0 : len;
1538                         ext_debug("insert %d:%llu:%d after: nearest 0x%p, "
1539                                         "move %d from 0x%p to 0x%p\n",
1540                                         le32_to_cpu(newext->ee_block),
1541                                         ext_pblock(newext),
1542                                         ext4_ext_get_actual_len(newext),
1543                                         nearex, len, nearex + 1, nearex + 2);
1544                         memmove(nearex + 2, nearex + 1, len);
1545                 }
1546                 path[depth].p_ext = nearex + 1;
1547         } else {
1548                 BUG_ON(newext->ee_block == nearex->ee_block);
1549                 len = (EXT_MAX_EXTENT(eh) - nearex) * sizeof(struct ext4_extent);
1550                 len = len < 0 ? 0 : len;
1551                 ext_debug("insert %d:%llu:%d before: nearest 0x%p, "
1552                                 "move %d from 0x%p to 0x%p\n",
1553                                 le32_to_cpu(newext->ee_block),
1554                                 ext_pblock(newext),
1555                                 ext4_ext_get_actual_len(newext),
1556                                 nearex, len, nearex + 1, nearex + 2);
1557                 memmove(nearex + 1, nearex, len);
1558                 path[depth].p_ext = nearex;
1559         }
1560
1561         le16_add_cpu(&eh->eh_entries, 1);
1562         nearex = path[depth].p_ext;
1563         nearex->ee_block = newext->ee_block;
1564         ext4_ext_store_pblock(nearex, ext_pblock(newext));
1565         nearex->ee_len = newext->ee_len;
1566
1567 merge:
1568         /* try to merge extents to the right */
1569         ext4_ext_try_to_merge(inode, path, nearex);
1570
1571         /* try to merge extents to the left */
1572
1573         /* time to correct all indexes above */
1574         err = ext4_ext_correct_indexes(handle, inode, path);
1575         if (err)
1576                 goto cleanup;
1577
1578         err = ext4_ext_dirty(handle, inode, path + depth);
1579
1580 cleanup:
1581         if (npath) {
1582                 ext4_ext_drop_refs(npath);
1583                 kfree(npath);
1584         }
1585         ext4_ext_tree_changed(inode);
1586         ext4_ext_invalidate_cache(inode);
1587         return err;
1588 }
1589
1590 static void
1591 ext4_ext_put_in_cache(struct inode *inode, ext4_lblk_t block,
1592                         __u32 len, ext4_fsblk_t start, int type)
1593 {
1594         struct ext4_ext_cache *cex;
1595         BUG_ON(len == 0);
1596         cex = &EXT4_I(inode)->i_cached_extent;
1597         cex->ec_type = type;
1598         cex->ec_block = block;
1599         cex->ec_len = len;
1600         cex->ec_start = start;
1601 }
1602
1603 /*
1604  * ext4_ext_put_gap_in_cache:
1605  * calculate boundaries of the gap that the requested block fits into
1606  * and cache this gap
1607  */
1608 static void
1609 ext4_ext_put_gap_in_cache(struct inode *inode, struct ext4_ext_path *path,
1610                                 ext4_lblk_t block)
1611 {
1612         int depth = ext_depth(inode);
1613         unsigned long len;
1614         ext4_lblk_t lblock;
1615         struct ext4_extent *ex;
1616
1617         ex = path[depth].p_ext;
1618         if (ex == NULL) {
1619                 /* there is no extent yet, so gap is [0;-] */
1620                 lblock = 0;
1621                 len = EXT_MAX_BLOCK;
1622                 ext_debug("cache gap(whole file):");
1623         } else if (block < le32_to_cpu(ex->ee_block)) {
1624                 lblock = block;
1625                 len = le32_to_cpu(ex->ee_block) - block;
1626                 ext_debug("cache gap(before): %u [%u:%u]",
1627                                 block,
1628                                 le32_to_cpu(ex->ee_block),
1629                                  ext4_ext_get_actual_len(ex));
1630         } else if (block >= le32_to_cpu(ex->ee_block)
1631                         + ext4_ext_get_actual_len(ex)) {
1632                 ext4_lblk_t next;
1633                 lblock = le32_to_cpu(ex->ee_block)
1634                         + ext4_ext_get_actual_len(ex);
1635
1636                 next = ext4_ext_next_allocated_block(path);
1637                 ext_debug("cache gap(after): [%u:%u] %u",
1638                                 le32_to_cpu(ex->ee_block),
1639                                 ext4_ext_get_actual_len(ex),
1640                                 block);
1641                 BUG_ON(next == lblock);
1642                 len = next - lblock;
1643         } else {
1644                 lblock = len = 0;
1645                 BUG();
1646         }
1647
1648         ext_debug(" -> %u:%lu\n", lblock, len);
1649         ext4_ext_put_in_cache(inode, lblock, len, 0, EXT4_EXT_CACHE_GAP);
1650 }
1651
1652 static int
1653 ext4_ext_in_cache(struct inode *inode, ext4_lblk_t block,
1654                         struct ext4_extent *ex)
1655 {
1656         struct ext4_ext_cache *cex;
1657
1658         cex = &EXT4_I(inode)->i_cached_extent;
1659
1660         /* has cache valid data? */
1661         if (cex->ec_type == EXT4_EXT_CACHE_NO)
1662                 return EXT4_EXT_CACHE_NO;
1663
1664         BUG_ON(cex->ec_type != EXT4_EXT_CACHE_GAP &&
1665                         cex->ec_type != EXT4_EXT_CACHE_EXTENT);
1666         if (block >= cex->ec_block && block < cex->ec_block + cex->ec_len) {
1667                 ex->ee_block = cpu_to_le32(cex->ec_block);
1668                 ext4_ext_store_pblock(ex, cex->ec_start);
1669                 ex->ee_len = cpu_to_le16(cex->ec_len);
1670                 ext_debug("%u cached by %u:%u:%llu\n",
1671                                 block,
1672                                 cex->ec_block, cex->ec_len, cex->ec_start);
1673                 return cex->ec_type;
1674         }
1675
1676         /* not in cache */
1677         return EXT4_EXT_CACHE_NO;
1678 }
1679
1680 /*
1681  * ext4_ext_rm_idx:
1682  * removes index from the index block.
1683  * It's used in truncate case only, thus all requests are for
1684  * last index in the block only.
1685  */
1686 static int ext4_ext_rm_idx(handle_t *handle, struct inode *inode,
1687                         struct ext4_ext_path *path)
1688 {
1689         struct buffer_head *bh;
1690         int err;
1691         ext4_fsblk_t leaf;
1692
1693         /* free index block */
1694         path--;
1695         leaf = idx_pblock(path->p_idx);
1696         BUG_ON(path->p_hdr->eh_entries == 0);
1697         err = ext4_ext_get_access(handle, inode, path);
1698         if (err)
1699                 return err;
1700         le16_add_cpu(&path->p_hdr->eh_entries, -1);
1701         err = ext4_ext_dirty(handle, inode, path);
1702         if (err)
1703                 return err;
1704         ext_debug("index is empty, remove it, free block %llu\n", leaf);
1705         bh = sb_find_get_block(inode->i_sb, leaf);
1706         ext4_forget(handle, 1, inode, bh, leaf);
1707         ext4_free_blocks(handle, inode, leaf, 1, 1);
1708         return err;
1709 }
1710
1711 /*
1712  * ext4_ext_calc_credits_for_insert:
1713  * This routine returns max. credits that the extent tree can consume.
1714  * It should be OK for low-performance paths like ->writepage()
1715  * To allow many writing processes to fit into a single transaction,
1716  * the caller should calculate credits under i_data_sem and
1717  * pass the actual path.
1718  */
1719 int ext4_ext_calc_credits_for_insert(struct inode *inode,
1720                                                 struct ext4_ext_path *path)
1721 {
1722         int depth, needed;
1723
1724         if (path) {
1725                 /* probably there is space in leaf? */
1726                 depth = ext_depth(inode);
1727                 if (le16_to_cpu(path[depth].p_hdr->eh_entries)
1728                                 < le16_to_cpu(path[depth].p_hdr->eh_max))
1729                         return 1;
1730         }
1731
1732         /*
1733          * given 32-bit logical block (4294967296 blocks), max. tree
1734          * can be 4 levels in depth -- 4 * 340^4 == 53453440000.
1735          * Let's also add one more level for imbalance.
1736          */
1737         depth = 5;
1738
1739         /* allocation of new data block(s) */
1740         needed = 2;
1741
1742         /*
1743          * tree can be full, so it would need to grow in depth:
1744          * we need one credit to modify old root, credits for
1745          * new root will be added in split accounting
1746          */
1747         needed += 1;
1748
1749         /*
1750          * Index split can happen, we would need:
1751          *    allocate intermediate indexes (bitmap + group)
1752          *  + change two blocks at each level, but root (already included)
1753          */
1754         needed += (depth * 2) + (depth * 2);
1755
1756         /* any allocation modifies superblock */
1757         needed += 1;
1758
1759         return needed;
1760 }
1761
1762 static int ext4_remove_blocks(handle_t *handle, struct inode *inode,
1763                                 struct ext4_extent *ex,
1764                                 ext4_lblk_t from, ext4_lblk_t to)
1765 {
1766         struct buffer_head *bh;
1767         unsigned short ee_len =  ext4_ext_get_actual_len(ex);
1768         int i, metadata = 0;
1769
1770         if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode))
1771                 metadata = 1;
1772 #ifdef EXTENTS_STATS
1773         {
1774                 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1775                 spin_lock(&sbi->s_ext_stats_lock);
1776                 sbi->s_ext_blocks += ee_len;
1777                 sbi->s_ext_extents++;
1778                 if (ee_len < sbi->s_ext_min)
1779                         sbi->s_ext_min = ee_len;
1780                 if (ee_len > sbi->s_ext_max)
1781                         sbi->s_ext_max = ee_len;
1782                 if (ext_depth(inode) > sbi->s_depth_max)
1783                         sbi->s_depth_max = ext_depth(inode);
1784                 spin_unlock(&sbi->s_ext_stats_lock);
1785         }
1786 #endif
1787         if (from >= le32_to_cpu(ex->ee_block)
1788             && to == le32_to_cpu(ex->ee_block) + ee_len - 1) {
1789                 /* tail removal */
1790                 ext4_lblk_t num;
1791                 ext4_fsblk_t start;
1792
1793                 num = le32_to_cpu(ex->ee_block) + ee_len - from;
1794                 start = ext_pblock(ex) + ee_len - num;
1795                 ext_debug("free last %u blocks starting %llu\n", num, start);
1796                 for (i = 0; i < num; i++) {
1797                         bh = sb_find_get_block(inode->i_sb, start + i);
1798                         ext4_forget(handle, 0, inode, bh, start + i);
1799                 }
1800                 ext4_free_blocks(handle, inode, start, num, metadata);
1801         } else if (from == le32_to_cpu(ex->ee_block)
1802                    && to <= le32_to_cpu(ex->ee_block) + ee_len - 1) {
1803                 printk(KERN_INFO "strange request: removal %u-%u from %u:%u\n",
1804                         from, to, le32_to_cpu(ex->ee_block), ee_len);
1805         } else {
1806                 printk(KERN_INFO "strange request: removal(2) "
1807                                 "%u-%u from %u:%u\n",
1808                                 from, to, le32_to_cpu(ex->ee_block), ee_len);
1809         }
1810         return 0;
1811 }
1812
1813 static int
1814 ext4_ext_rm_leaf(handle_t *handle, struct inode *inode,
1815                 struct ext4_ext_path *path, ext4_lblk_t start)
1816 {
1817         int err = 0, correct_index = 0;
1818         int depth = ext_depth(inode), credits;
1819         struct ext4_extent_header *eh;
1820         ext4_lblk_t a, b, block;
1821         unsigned num;
1822         ext4_lblk_t ex_ee_block;
1823         unsigned short ex_ee_len;
1824         unsigned uninitialized = 0;
1825         struct ext4_extent *ex;
1826
1827         /* the header must be checked already in ext4_ext_remove_space() */
1828         ext_debug("truncate since %u in leaf\n", start);
1829         if (!path[depth].p_hdr)
1830                 path[depth].p_hdr = ext_block_hdr(path[depth].p_bh);
1831         eh = path[depth].p_hdr;
1832         BUG_ON(eh == NULL);
1833
1834         /* find where to start removing */
1835         ex = EXT_LAST_EXTENT(eh);
1836
1837         ex_ee_block = le32_to_cpu(ex->ee_block);
1838         if (ext4_ext_is_uninitialized(ex))
1839                 uninitialized = 1;
1840         ex_ee_len = ext4_ext_get_actual_len(ex);
1841
1842         while (ex >= EXT_FIRST_EXTENT(eh) &&
1843                         ex_ee_block + ex_ee_len > start) {
1844                 ext_debug("remove ext %lu:%u\n", ex_ee_block, ex_ee_len);
1845                 path[depth].p_ext = ex;
1846
1847                 a = ex_ee_block > start ? ex_ee_block : start;
1848                 b = ex_ee_block + ex_ee_len - 1 < EXT_MAX_BLOCK ?
1849                         ex_ee_block + ex_ee_len - 1 : EXT_MAX_BLOCK;
1850
1851                 ext_debug("  border %u:%u\n", a, b);
1852
1853                 if (a != ex_ee_block && b != ex_ee_block + ex_ee_len - 1) {
1854                         block = 0;
1855                         num = 0;
1856                         BUG();
1857                 } else if (a != ex_ee_block) {
1858                         /* remove tail of the extent */
1859                         block = ex_ee_block;
1860                         num = a - block;
1861                 } else if (b != ex_ee_block + ex_ee_len - 1) {
1862                         /* remove head of the extent */
1863                         block = a;
1864                         num = b - a;
1865                         /* there is no "make a hole" API yet */
1866                         BUG();
1867                 } else {
1868                         /* remove whole extent: excellent! */
1869                         block = ex_ee_block;
1870                         num = 0;
1871                         BUG_ON(a != ex_ee_block);
1872                         BUG_ON(b != ex_ee_block + ex_ee_len - 1);
1873                 }
1874
1875                 /* at present, extent can't cross block group: */
1876                 /* leaf + bitmap + group desc + sb + inode */
1877                 credits = 5;
1878                 if (ex == EXT_FIRST_EXTENT(eh)) {
1879                         correct_index = 1;
1880                         credits += (ext_depth(inode)) + 1;
1881                 }
1882 #ifdef CONFIG_QUOTA
1883                 credits += 2 * EXT4_QUOTA_TRANS_BLOCKS(inode->i_sb);
1884 #endif
1885
1886                 handle = ext4_ext_journal_restart(handle, credits);
1887                 if (IS_ERR(handle)) {
1888                         err = PTR_ERR(handle);
1889                         goto out;
1890                 }
1891
1892                 err = ext4_ext_get_access(handle, inode, path + depth);
1893                 if (err)
1894                         goto out;
1895
1896                 err = ext4_remove_blocks(handle, inode, ex, a, b);
1897                 if (err)
1898                         goto out;
1899
1900                 if (num == 0) {
1901                         /* this extent is removed; mark slot entirely unused */
1902                         ext4_ext_store_pblock(ex, 0);
1903                         le16_add_cpu(&eh->eh_entries, -1);
1904                 }
1905
1906                 ex->ee_block = cpu_to_le32(block);
1907                 ex->ee_len = cpu_to_le16(num);
1908                 /*
1909                  * Do not mark uninitialized if all the blocks in the
1910                  * extent have been removed.
1911                  */
1912                 if (uninitialized && num)
1913                         ext4_ext_mark_uninitialized(ex);
1914
1915                 err = ext4_ext_dirty(handle, inode, path + depth);
1916                 if (err)
1917                         goto out;
1918
1919                 ext_debug("new extent: %u:%u:%llu\n", block, num,
1920                                 ext_pblock(ex));
1921                 ex--;
1922                 ex_ee_block = le32_to_cpu(ex->ee_block);
1923                 ex_ee_len = ext4_ext_get_actual_len(ex);
1924         }
1925
1926         if (correct_index && eh->eh_entries)
1927                 err = ext4_ext_correct_indexes(handle, inode, path);
1928
1929         /* if this leaf is free, then we should
1930          * remove it from index block above */
1931         if (err == 0 && eh->eh_entries == 0 && path[depth].p_bh != NULL)
1932                 err = ext4_ext_rm_idx(handle, inode, path + depth);
1933
1934 out:
1935         return err;
1936 }
1937
1938 /*
1939  * ext4_ext_more_to_rm:
1940  * returns 1 if current index has to be freed (even partial)
1941  */
1942 static int
1943 ext4_ext_more_to_rm(struct ext4_ext_path *path)
1944 {
1945         BUG_ON(path->p_idx == NULL);
1946
1947         if (path->p_idx < EXT_FIRST_INDEX(path->p_hdr))
1948                 return 0;
1949
1950         /*
1951          * if truncate on deeper level happened, it wasn't partial,
1952          * so we have to consider current index for truncation
1953          */
1954         if (le16_to_cpu(path->p_hdr->eh_entries) == path->p_block)
1955                 return 0;
1956         return 1;
1957 }
1958
1959 static int ext4_ext_remove_space(struct inode *inode, ext4_lblk_t start)
1960 {
1961         struct super_block *sb = inode->i_sb;
1962         int depth = ext_depth(inode);
1963         struct ext4_ext_path *path;
1964         handle_t *handle;
1965         int i = 0, err = 0;
1966
1967         ext_debug("truncate since %u\n", start);
1968
1969         /* probably first extent we're gonna free will be last in block */
1970         handle = ext4_journal_start(inode, depth + 1);
1971         if (IS_ERR(handle))
1972                 return PTR_ERR(handle);
1973
1974         ext4_ext_invalidate_cache(inode);
1975
1976         /*
1977          * We start scanning from right side, freeing all the blocks
1978          * after i_size and walking into the tree depth-wise.
1979          */
1980         path = kzalloc(sizeof(struct ext4_ext_path) * (depth + 1), GFP_NOFS);
1981         if (path == NULL) {
1982                 ext4_journal_stop(handle);
1983                 return -ENOMEM;
1984         }
1985         path[0].p_hdr = ext_inode_hdr(inode);
1986         if (ext4_ext_check_header(inode, path[0].p_hdr, depth)) {
1987                 err = -EIO;
1988                 goto out;
1989         }
1990         path[0].p_depth = depth;
1991
1992         while (i >= 0 && err == 0) {
1993                 if (i == depth) {
1994                         /* this is leaf block */
1995                         err = ext4_ext_rm_leaf(handle, inode, path, start);
1996                         /* root level has p_bh == NULL, brelse() eats this */
1997                         brelse(path[i].p_bh);
1998                         path[i].p_bh = NULL;
1999                         i--;
2000                         continue;
2001                 }
2002
2003                 /* this is index block */
2004                 if (!path[i].p_hdr) {
2005                         ext_debug("initialize header\n");
2006                         path[i].p_hdr = ext_block_hdr(path[i].p_bh);
2007                 }
2008
2009                 if (!path[i].p_idx) {
2010                         /* this level hasn't been touched yet */
2011                         path[i].p_idx = EXT_LAST_INDEX(path[i].p_hdr);
2012                         path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries)+1;
2013                         ext_debug("init index ptr: hdr 0x%p, num %d\n",
2014                                   path[i].p_hdr,
2015                                   le16_to_cpu(path[i].p_hdr->eh_entries));
2016                 } else {
2017                         /* we were already here, see at next index */
2018                         path[i].p_idx--;
2019                 }
2020
2021                 ext_debug("level %d - index, first 0x%p, cur 0x%p\n",
2022                                 i, EXT_FIRST_INDEX(path[i].p_hdr),
2023                                 path[i].p_idx);
2024                 if (ext4_ext_more_to_rm(path + i)) {
2025                         struct buffer_head *bh;
2026                         /* go to the next level */
2027                         ext_debug("move to level %d (block %llu)\n",
2028                                   i + 1, idx_pblock(path[i].p_idx));
2029                         memset(path + i + 1, 0, sizeof(*path));
2030                         bh = sb_bread(sb, idx_pblock(path[i].p_idx));
2031                         if (!bh) {
2032                                 /* should we reset i_size? */
2033                                 err = -EIO;
2034                                 break;
2035                         }
2036                         if (WARN_ON(i + 1 > depth)) {
2037                                 err = -EIO;
2038                                 break;
2039                         }
2040                         if (ext4_ext_check_header(inode, ext_block_hdr(bh),
2041                                                         depth - i - 1)) {
2042                                 err = -EIO;
2043                                 break;
2044                         }
2045                         path[i + 1].p_bh = bh;
2046
2047                         /* save actual number of indexes since this
2048                          * number is changed at the next iteration */
2049                         path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries);
2050                         i++;
2051                 } else {
2052                         /* we finished processing this index, go up */
2053                         if (path[i].p_hdr->eh_entries == 0 && i > 0) {
2054                                 /* index is empty, remove it;
2055                                  * handle must be already prepared by the
2056                                  * truncatei_leaf() */
2057                                 err = ext4_ext_rm_idx(handle, inode, path + i);
2058                         }
2059                         /* root level has p_bh == NULL, brelse() eats this */
2060                         brelse(path[i].p_bh);
2061                         path[i].p_bh = NULL;
2062                         i--;
2063                         ext_debug("return to level %d\n", i);
2064                 }
2065         }
2066
2067         /* TODO: flexible tree reduction should be here */
2068         if (path->p_hdr->eh_entries == 0) {
2069                 /*
2070                  * truncate to zero freed all the tree,
2071                  * so we need to correct eh_depth
2072                  */
2073                 err = ext4_ext_get_access(handle, inode, path);
2074                 if (err == 0) {
2075                         ext_inode_hdr(inode)->eh_depth = 0;
2076                         ext_inode_hdr(inode)->eh_max =
2077                                 cpu_to_le16(ext4_ext_space_root(inode));
2078                         err = ext4_ext_dirty(handle, inode, path);
2079                 }
2080         }
2081 out:
2082         ext4_ext_tree_changed(inode);
2083         ext4_ext_drop_refs(path);
2084         kfree(path);
2085         ext4_journal_stop(handle);
2086
2087         return err;
2088 }
2089
2090 /*
2091  * called at mount time
2092  */
2093 void ext4_ext_init(struct super_block *sb)
2094 {
2095         /*
2096          * possible initialization would be here
2097          */
2098
2099         if (test_opt(sb, EXTENTS)) {
2100                 printk("EXT4-fs: file extents enabled");
2101 #ifdef AGGRESSIVE_TEST
2102                 printk(", aggressive tests");
2103 #endif
2104 #ifdef CHECK_BINSEARCH
2105                 printk(", check binsearch");
2106 #endif
2107 #ifdef EXTENTS_STATS
2108                 printk(", stats");
2109 #endif
2110                 printk("\n");
2111 #ifdef EXTENTS_STATS
2112                 spin_lock_init(&EXT4_SB(sb)->s_ext_stats_lock);
2113                 EXT4_SB(sb)->s_ext_min = 1 << 30;
2114                 EXT4_SB(sb)->s_ext_max = 0;
2115 #endif
2116         }
2117 }
2118
2119 /*
2120  * called at umount time
2121  */
2122 void ext4_ext_release(struct super_block *sb)
2123 {
2124         if (!test_opt(sb, EXTENTS))
2125                 return;
2126
2127 #ifdef EXTENTS_STATS
2128         if (EXT4_SB(sb)->s_ext_blocks && EXT4_SB(sb)->s_ext_extents) {
2129                 struct ext4_sb_info *sbi = EXT4_SB(sb);
2130                 printk(KERN_ERR "EXT4-fs: %lu blocks in %lu extents (%lu ave)\n",
2131                         sbi->s_ext_blocks, sbi->s_ext_extents,
2132                         sbi->s_ext_blocks / sbi->s_ext_extents);
2133                 printk(KERN_ERR "EXT4-fs: extents: %lu min, %lu max, max depth %lu\n",
2134                         sbi->s_ext_min, sbi->s_ext_max, sbi->s_depth_max);
2135         }
2136 #endif
2137 }
2138
2139 static void bi_complete(struct bio *bio, int error)
2140 {
2141         complete((struct completion *)bio->bi_private);
2142 }
2143
2144 /* FIXME!! we need to try to merge to left or right after zero-out  */
2145 static int ext4_ext_zeroout(struct inode *inode, struct ext4_extent *ex)
2146 {
2147         int ret = -EIO;
2148         struct bio *bio;
2149         int blkbits, blocksize;
2150         sector_t ee_pblock;
2151         struct completion event;
2152         unsigned int ee_len, len, done, offset;
2153
2154
2155         blkbits   = inode->i_blkbits;
2156         blocksize = inode->i_sb->s_blocksize;
2157         ee_len    = ext4_ext_get_actual_len(ex);
2158         ee_pblock = ext_pblock(ex);
2159
2160         /* convert ee_pblock to 512 byte sectors */
2161         ee_pblock = ee_pblock << (blkbits - 9);
2162
2163         while (ee_len > 0) {
2164
2165                 if (ee_len > BIO_MAX_PAGES)
2166                         len = BIO_MAX_PAGES;
2167                 else
2168                         len = ee_len;
2169
2170                 bio = bio_alloc(GFP_NOIO, len);
2171                 if (!bio)
2172                         return -ENOMEM;
2173                 bio->bi_sector = ee_pblock;
2174                 bio->bi_bdev   = inode->i_sb->s_bdev;
2175
2176                 done = 0;
2177                 offset = 0;
2178                 while (done < len) {
2179                         ret = bio_add_page(bio, ZERO_PAGE(0),
2180                                                         blocksize, offset);
2181                         if (ret != blocksize) {
2182                                 /*
2183                                  * We can't add any more pages because of
2184                                  * hardware limitations.  Start a new bio.
2185                                  */
2186                                 break;
2187                         }
2188                         done++;
2189                         offset += blocksize;
2190                         if (offset >= PAGE_CACHE_SIZE)
2191                                 offset = 0;
2192                 }
2193
2194                 init_completion(&event);
2195                 bio->bi_private = &event;
2196                 bio->bi_end_io = bi_complete;
2197                 submit_bio(WRITE, bio);
2198                 wait_for_completion(&event);
2199
2200                 if (test_bit(BIO_UPTODATE, &bio->bi_flags))
2201                         ret = 0;
2202                 else {
2203                         ret = -EIO;
2204                         break;
2205                 }
2206                 bio_put(bio);
2207                 ee_len    -= done;
2208                 ee_pblock += done  << (blkbits - 9);
2209         }
2210         return ret;
2211 }
2212
2213 #define EXT4_EXT_ZERO_LEN 7
2214
2215 /*
2216  * This function is called by ext4_ext_get_blocks() if someone tries to write
2217  * to an uninitialized extent. It may result in splitting the uninitialized
2218  * extent into multiple extents (upto three - one initialized and two
2219  * uninitialized).
2220  * There are three possibilities:
2221  *   a> There is no split required: Entire extent should be initialized
2222  *   b> Splits in two extents: Write is happening at either end of the extent
2223  *   c> Splits in three extents: Somone is writing in middle of the extent
2224  */
2225 static int ext4_ext_convert_to_initialized(handle_t *handle,
2226                                                 struct inode *inode,
2227                                                 struct ext4_ext_path *path,
2228                                                 ext4_lblk_t iblock,
2229                                                 unsigned long max_blocks)
2230 {
2231         struct ext4_extent *ex, newex, orig_ex;
2232         struct ext4_extent *ex1 = NULL;
2233         struct ext4_extent *ex2 = NULL;
2234         struct ext4_extent *ex3 = NULL;
2235         struct ext4_extent_header *eh;
2236         ext4_lblk_t ee_block;
2237         unsigned int allocated, ee_len, depth;
2238         ext4_fsblk_t newblock;
2239         int err = 0;
2240         int ret = 0;
2241
2242         depth = ext_depth(inode);
2243         eh = path[depth].p_hdr;
2244         ex = path[depth].p_ext;
2245         ee_block = le32_to_cpu(ex->ee_block);
2246         ee_len = ext4_ext_get_actual_len(ex);
2247         allocated = ee_len - (iblock - ee_block);
2248         newblock = iblock - ee_block + ext_pblock(ex);
2249         ex2 = ex;
2250         orig_ex.ee_block = ex->ee_block;
2251         orig_ex.ee_len   = cpu_to_le16(ee_len);
2252         ext4_ext_store_pblock(&orig_ex, ext_pblock(ex));
2253
2254         err = ext4_ext_get_access(handle, inode, path + depth);
2255         if (err)
2256                 goto out;
2257         /* If extent has less than 2*EXT4_EXT_ZERO_LEN zerout directly */
2258         if (ee_len <= 2*EXT4_EXT_ZERO_LEN) {
2259                 err =  ext4_ext_zeroout(inode, &orig_ex);
2260                 if (err)
2261                         goto fix_extent_len;
2262                 /* update the extent length and mark as initialized */
2263                 ex->ee_block = orig_ex.ee_block;
2264                 ex->ee_len   = orig_ex.ee_len;
2265                 ext4_ext_store_pblock(ex, ext_pblock(&orig_ex));
2266                 ext4_ext_dirty(handle, inode, path + depth);
2267                 /* zeroed the full extent */
2268                 return allocated;
2269         }
2270
2271         /* ex1: ee_block to iblock - 1 : uninitialized */
2272         if (iblock > ee_block) {
2273                 ex1 = ex;
2274                 ex1->ee_len = cpu_to_le16(iblock - ee_block);
2275                 ext4_ext_mark_uninitialized(ex1);
2276                 ex2 = &newex;
2277         }
2278         /*
2279          * for sanity, update the length of the ex2 extent before
2280          * we insert ex3, if ex1 is NULL. This is to avoid temporary
2281          * overlap of blocks.
2282          */
2283         if (!ex1 && allocated > max_blocks)
2284                 ex2->ee_len = cpu_to_le16(max_blocks);
2285         /* ex3: to ee_block + ee_len : uninitialised */
2286         if (allocated > max_blocks) {
2287                 unsigned int newdepth;
2288                 /* If extent has less than EXT4_EXT_ZERO_LEN zerout directly */
2289                 if (allocated <= EXT4_EXT_ZERO_LEN) {
2290                         /* Mark first half uninitialized.
2291                          * Mark second half initialized and zero out the
2292                          * initialized extent
2293                          */
2294                         ex->ee_block = orig_ex.ee_block;
2295                         ex->ee_len   = cpu_to_le16(ee_len - allocated);
2296                         ext4_ext_mark_uninitialized(ex);
2297                         ext4_ext_store_pblock(ex, ext_pblock(&orig_ex));
2298                         ext4_ext_dirty(handle, inode, path + depth);
2299
2300                         ex3 = &newex;
2301                         ex3->ee_block = cpu_to_le32(iblock);
2302                         ext4_ext_store_pblock(ex3, newblock);
2303                         ex3->ee_len = cpu_to_le16(allocated);
2304                         err = ext4_ext_insert_extent(handle, inode, path, ex3);
2305                         if (err == -ENOSPC) {
2306                                 err =  ext4_ext_zeroout(inode, &orig_ex);
2307                                 if (err)
2308                                         goto fix_extent_len;
2309                                 ex->ee_block = orig_ex.ee_block;
2310                                 ex->ee_len   = orig_ex.ee_len;
2311                                 ext4_ext_store_pblock(ex, ext_pblock(&orig_ex));
2312                                 ext4_ext_dirty(handle, inode, path + depth);
2313                                 /* zeroed the full extent */
2314                                 return allocated;
2315
2316                         } else if (err)
2317                                 goto fix_extent_len;
2318
2319                         /*
2320                          * We need to zero out the second half because
2321                          * an fallocate request can update file size and
2322                          * converting the second half to initialized extent
2323                          * implies that we can leak some junk data to user
2324                          * space.
2325                          */
2326                         err =  ext4_ext_zeroout(inode, ex3);
2327                         if (err) {
2328                                 /*
2329                                  * We should actually mark the
2330                                  * second half as uninit and return error
2331                                  * Insert would have changed the extent
2332                                  */
2333                                 depth = ext_depth(inode);
2334                                 ext4_ext_drop_refs(path);
2335                                 path = ext4_ext_find_extent(inode,
2336                                                                 iblock, path);
2337                                 if (IS_ERR(path)) {
2338                                         err = PTR_ERR(path);
2339                                         return err;
2340                                 }
2341                                 ex = path[depth].p_ext;
2342                                 err = ext4_ext_get_access(handle, inode,
2343                                                                 path + depth);
2344                                 if (err)
2345                                         return err;
2346                                 ext4_ext_mark_uninitialized(ex);
2347                                 ext4_ext_dirty(handle, inode, path + depth);
2348                                 return err;
2349                         }
2350
2351                         /* zeroed the second half */
2352                         return allocated;
2353                 }
2354                 ex3 = &newex;
2355                 ex3->ee_block = cpu_to_le32(iblock + max_blocks);
2356                 ext4_ext_store_pblock(ex3, newblock + max_blocks);
2357                 ex3->ee_len = cpu_to_le16(allocated - max_blocks);
2358                 ext4_ext_mark_uninitialized(ex3);
2359                 err = ext4_ext_insert_extent(handle, inode, path, ex3);
2360                 if (err == -ENOSPC) {
2361                         err =  ext4_ext_zeroout(inode, &orig_ex);
2362                         if (err)
2363                                 goto fix_extent_len;
2364                         /* update the extent length and mark as initialized */
2365                         ex->ee_block = orig_ex.ee_block;
2366                         ex->ee_len   = orig_ex.ee_len;
2367                         ext4_ext_store_pblock(ex, ext_pblock(&orig_ex));
2368                         ext4_ext_dirty(handle, inode, path + depth);
2369                         /* zeroed the full extent */
2370                         return allocated;
2371
2372                 } else if (err)
2373                         goto fix_extent_len;
2374                 /*
2375                  * The depth, and hence eh & ex might change
2376                  * as part of the insert above.
2377                  */
2378                 newdepth = ext_depth(inode);
2379                 /*
2380                  * update the extent length after successfull insert of the
2381                  * split extent
2382                  */
2383                 orig_ex.ee_len = cpu_to_le16(ee_len -
2384                                                 ext4_ext_get_actual_len(ex3));
2385                 if (newdepth != depth) {
2386                         depth = newdepth;
2387                         ext4_ext_drop_refs(path);
2388                         path = ext4_ext_find_extent(inode, iblock, path);
2389                         if (IS_ERR(path)) {
2390                                 err = PTR_ERR(path);
2391                                 goto out;
2392                         }
2393                         eh = path[depth].p_hdr;
2394                         ex = path[depth].p_ext;
2395                         if (ex2 != &newex)
2396                                 ex2 = ex;
2397
2398                         err = ext4_ext_get_access(handle, inode, path + depth);
2399                         if (err)
2400                                 goto out;
2401                 }
2402                 allocated = max_blocks;
2403
2404                 /* If extent has less than EXT4_EXT_ZERO_LEN and we are trying
2405                  * to insert a extent in the middle zerout directly
2406                  * otherwise give the extent a chance to merge to left
2407                  */
2408                 if (le16_to_cpu(orig_ex.ee_len) <= EXT4_EXT_ZERO_LEN &&
2409                                                         iblock != ee_block) {
2410                         err =  ext4_ext_zeroout(inode, &orig_ex);
2411                         if (err)
2412                                 goto fix_extent_len;
2413                         /* update the extent length and mark as initialized */
2414                         ex->ee_block = orig_ex.ee_block;
2415                         ex->ee_len   = orig_ex.ee_len;
2416                         ext4_ext_store_pblock(ex, ext_pblock(&orig_ex));
2417                         ext4_ext_dirty(handle, inode, path + depth);
2418                         /* zero out the first half */
2419                         return allocated;
2420                 }
2421         }
2422         /*
2423          * If there was a change of depth as part of the
2424          * insertion of ex3 above, we need to update the length
2425          * of the ex1 extent again here
2426          */
2427         if (ex1 && ex1 != ex) {
2428                 ex1 = ex;
2429                 ex1->ee_len = cpu_to_le16(iblock - ee_block);
2430                 ext4_ext_mark_uninitialized(ex1);
2431                 ex2 = &newex;
2432         }
2433         /* ex2: iblock to iblock + maxblocks-1 : initialised */
2434         ex2->ee_block = cpu_to_le32(iblock);
2435         ext4_ext_store_pblock(ex2, newblock);
2436         ex2->ee_len = cpu_to_le16(allocated);
2437         if (ex2 != ex)
2438                 goto insert;
2439         /*
2440          * New (initialized) extent starts from the first block
2441          * in the current extent. i.e., ex2 == ex
2442          * We have to see if it can be merged with the extent
2443          * on the left.
2444          */
2445         if (ex2 > EXT_FIRST_EXTENT(eh)) {
2446                 /*
2447                  * To merge left, pass "ex2 - 1" to try_to_merge(),
2448                  * since it merges towards right _only_.
2449                  */
2450                 ret = ext4_ext_try_to_merge(inode, path, ex2 - 1);
2451                 if (ret) {
2452                         err = ext4_ext_correct_indexes(handle, inode, path);
2453                         if (err)
2454                                 goto out;
2455                         depth = ext_depth(inode);
2456                         ex2--;
2457                 }
2458         }
2459         /*
2460          * Try to Merge towards right. This might be required
2461          * only when the whole extent is being written to.
2462          * i.e. ex2 == ex and ex3 == NULL.
2463          */
2464         if (!ex3) {
2465                 ret = ext4_ext_try_to_merge(inode, path, ex2);
2466                 if (ret) {
2467                         err = ext4_ext_correct_indexes(handle, inode, path);
2468                         if (err)
2469                                 goto out;
2470                 }
2471         }
2472         /* Mark modified extent as dirty */
2473         err = ext4_ext_dirty(handle, inode, path + depth);
2474         goto out;
2475 insert:
2476         err = ext4_ext_insert_extent(handle, inode, path, &newex);
2477         if (err == -ENOSPC) {
2478                 err =  ext4_ext_zeroout(inode, &orig_ex);
2479                 if (err)
2480                         goto fix_extent_len;
2481                 /* update the extent length and mark as initialized */
2482                 ex->ee_block = orig_ex.ee_block;
2483                 ex->ee_len   = orig_ex.ee_len;
2484                 ext4_ext_store_pblock(ex, ext_pblock(&orig_ex));
2485                 ext4_ext_dirty(handle, inode, path + depth);
2486                 /* zero out the first half */
2487                 return allocated;
2488         } else if (err)
2489                 goto fix_extent_len;
2490 out:
2491         return err ? err : allocated;
2492
2493 fix_extent_len:
2494         ex->ee_block = orig_ex.ee_block;
2495         ex->ee_len   = orig_ex.ee_len;
2496         ext4_ext_store_pblock(ex, ext_pblock(&orig_ex));
2497         ext4_ext_mark_uninitialized(ex);
2498         ext4_ext_dirty(handle, inode, path + depth);
2499         return err;
2500 }
2501
2502 /*
2503  * Block allocation/map/preallocation routine for extents based files
2504  *
2505  *
2506  * Need to be called with
2507  * down_read(&EXT4_I(inode)->i_data_sem) if not allocating file system block
2508  * (ie, create is zero). Otherwise down_write(&EXT4_I(inode)->i_data_sem)
2509  *
2510  * return > 0, number of of blocks already mapped/allocated
2511  *          if create == 0 and these are pre-allocated blocks
2512  *              buffer head is unmapped
2513  *          otherwise blocks are mapped
2514  *
2515  * return = 0, if plain look up failed (blocks have not been allocated)
2516  *          buffer head is unmapped
2517  *
2518  * return < 0, error case.
2519  */
2520 int ext4_ext_get_blocks(handle_t *handle, struct inode *inode,
2521                         ext4_lblk_t iblock,
2522                         unsigned long max_blocks, struct buffer_head *bh_result,
2523                         int create, int extend_disksize)
2524 {
2525         struct ext4_ext_path *path = NULL;
2526         struct ext4_extent_header *eh;
2527         struct ext4_extent newex, *ex;
2528         ext4_fsblk_t goal, newblock;
2529         int err = 0, depth, ret;
2530         unsigned long allocated = 0;
2531         struct ext4_allocation_request ar;
2532
2533         __clear_bit(BH_New, &bh_result->b_state);
2534         ext_debug("blocks %u/%lu requested for inode %u\n",
2535                         iblock, max_blocks, inode->i_ino);
2536
2537         /* check in cache */
2538         goal = ext4_ext_in_cache(inode, iblock, &newex);
2539         if (goal) {
2540                 if (goal == EXT4_EXT_CACHE_GAP) {
2541                         if (!create) {
2542                                 /*
2543                                  * block isn't allocated yet and
2544                                  * user doesn't want to allocate it
2545                                  */
2546                                 goto out2;
2547                         }
2548                         /* we should allocate requested block */
2549                 } else if (goal == EXT4_EXT_CACHE_EXTENT) {
2550                         /* block is already allocated */
2551                         newblock = iblock
2552                                    - le32_to_cpu(newex.ee_block)
2553                                    + ext_pblock(&newex);
2554                         /* number of remaining blocks in the extent */
2555                         allocated = ext4_ext_get_actual_len(&newex) -
2556                                         (iblock - le32_to_cpu(newex.ee_block));
2557                         goto out;
2558                 } else {
2559                         BUG();
2560                 }
2561         }
2562
2563         /* find extent for this block */
2564         path = ext4_ext_find_extent(inode, iblock, NULL);
2565         if (IS_ERR(path)) {
2566                 err = PTR_ERR(path);
2567                 path = NULL;
2568                 goto out2;
2569         }
2570
2571         depth = ext_depth(inode);
2572
2573         /*
2574          * consistent leaf must not be empty;
2575          * this situation is possible, though, _during_ tree modification;
2576          * this is why assert can't be put in ext4_ext_find_extent()
2577          */
2578         BUG_ON(path[depth].p_ext == NULL && depth != 0);
2579         eh = path[depth].p_hdr;
2580
2581         ex = path[depth].p_ext;
2582         if (ex) {
2583                 ext4_lblk_t ee_block = le32_to_cpu(ex->ee_block);
2584                 ext4_fsblk_t ee_start = ext_pblock(ex);
2585                 unsigned short ee_len;
2586
2587                 /*
2588                  * Uninitialized extents are treated as holes, except that
2589                  * we split out initialized portions during a write.
2590                  */
2591                 ee_len = ext4_ext_get_actual_len(ex);
2592                 /* if found extent covers block, simply return it */
2593                 if (iblock >= ee_block && iblock < ee_block + ee_len) {
2594                         newblock = iblock - ee_block + ee_start;
2595                         /* number of remaining blocks in the extent */
2596                         allocated = ee_len - (iblock - ee_block);
2597                         ext_debug("%u fit into %lu:%d -> %llu\n", iblock,
2598                                         ee_block, ee_len, newblock);
2599
2600                         /* Do not put uninitialized extent in the cache */
2601                         if (!ext4_ext_is_uninitialized(ex)) {
2602                                 ext4_ext_put_in_cache(inode, ee_block,
2603                                                         ee_len, ee_start,
2604                                                         EXT4_EXT_CACHE_EXTENT);
2605                                 goto out;
2606                         }
2607                         if (create == EXT4_CREATE_UNINITIALIZED_EXT)
2608                                 goto out;
2609                         if (!create) {
2610                                 /*
2611                                  * We have blocks reserved already.  We
2612                                  * return allocated blocks so that delalloc
2613                                  * won't do block reservation for us.  But
2614                                  * the buffer head will be unmapped so that
2615                                  * a read from the block returns 0s.
2616                                  */
2617                                 if (allocated > max_blocks)
2618                                         allocated = max_blocks;
2619                                 /* mark the buffer unwritten */
2620                                 __set_bit(BH_Unwritten, &bh_result->b_state);
2621                                 goto out2;
2622                         }
2623
2624                         ret = ext4_ext_convert_to_initialized(handle, inode,
2625                                                                 path, iblock,
2626                                                                 max_blocks);
2627                         if (ret <= 0) {
2628                                 err = ret;
2629                                 goto out2;
2630                         } else
2631                                 allocated = ret;
2632                         goto outnew;
2633                 }
2634         }
2635
2636         /*
2637          * requested block isn't allocated yet;
2638          * we couldn't try to create block if create flag is zero
2639          */
2640         if (!create) {
2641                 /*
2642                  * put just found gap into cache to speed up
2643                  * subsequent requests
2644                  */
2645                 ext4_ext_put_gap_in_cache(inode, path, iblock);
2646                 goto out2;
2647         }
2648         /*
2649          * Okay, we need to do block allocation.  Lazily initialize the block
2650          * allocation info here if necessary.
2651          */
2652         if (S_ISREG(inode->i_mode) && (!EXT4_I(inode)->i_block_alloc_info))
2653                 ext4_init_block_alloc_info(inode);
2654
2655         /* find neighbour allocated blocks */
2656         ar.lleft = iblock;
2657         err = ext4_ext_search_left(inode, path, &ar.lleft, &ar.pleft);
2658         if (err)
2659                 goto out2;
2660         ar.lright = iblock;
2661         err = ext4_ext_search_right(inode, path, &ar.lright, &ar.pright);
2662         if (err)
2663                 goto out2;
2664
2665         /*
2666          * See if request is beyond maximum number of blocks we can have in
2667          * a single extent. For an initialized extent this limit is
2668          * EXT_INIT_MAX_LEN and for an uninitialized extent this limit is
2669          * EXT_UNINIT_MAX_LEN.
2670          */
2671         if (max_blocks > EXT_INIT_MAX_LEN &&
2672             create != EXT4_CREATE_UNINITIALIZED_EXT)
2673                 max_blocks = EXT_INIT_MAX_LEN;
2674         else if (max_blocks > EXT_UNINIT_MAX_LEN &&
2675                  create == EXT4_CREATE_UNINITIALIZED_EXT)
2676                 max_blocks = EXT_UNINIT_MAX_LEN;
2677
2678         /* Check if we can really insert (iblock)::(iblock+max_blocks) extent */
2679         newex.ee_block = cpu_to_le32(iblock);
2680         newex.ee_len = cpu_to_le16(max_blocks);
2681         err = ext4_ext_check_overlap(inode, &newex, path);
2682         if (err)
2683                 allocated = ext4_ext_get_actual_len(&newex);
2684         else
2685                 allocated = max_blocks;
2686
2687         /* allocate new block */
2688         ar.inode = inode;
2689         ar.goal = ext4_ext_find_goal(inode, path, iblock);
2690         ar.logical = iblock;
2691         ar.len = allocated;
2692         if (S_ISREG(inode->i_mode))
2693                 ar.flags = EXT4_MB_HINT_DATA;
2694         else
2695                 /* disable in-core preallocation for non-regular files */
2696                 ar.flags = 0;
2697         newblock = ext4_mb_new_blocks(handle, &ar, &err);
2698         if (!newblock)
2699                 goto out2;
2700         ext_debug("allocate new block: goal %llu, found %llu/%lu\n",
2701                         goal, newblock, allocated);
2702
2703         /* try to insert new extent into found leaf and return */
2704         ext4_ext_store_pblock(&newex, newblock);
2705         newex.ee_len = cpu_to_le16(ar.len);
2706         if (create == EXT4_CREATE_UNINITIALIZED_EXT)  /* Mark uninitialized */
2707                 ext4_ext_mark_uninitialized(&newex);
2708         err = ext4_ext_insert_extent(handle, inode, path, &newex);
2709         if (err) {
2710                 /* free data blocks we just allocated */
2711                 /* not a good idea to call discard here directly,
2712                  * but otherwise we'd need to call it every free() */
2713                 ext4_mb_discard_inode_preallocations(inode);
2714                 ext4_free_blocks(handle, inode, ext_pblock(&newex),
2715                                         ext4_ext_get_actual_len(&newex), 0);
2716                 goto out2;
2717         }
2718
2719         if (extend_disksize && inode->i_size > EXT4_I(inode)->i_disksize)
2720                 EXT4_I(inode)->i_disksize = inode->i_size;
2721
2722         /* previous routine could use block we allocated */
2723         newblock = ext_pblock(&newex);
2724         allocated = ext4_ext_get_actual_len(&newex);
2725 outnew:
2726         __set_bit(BH_New, &bh_result->b_state);
2727
2728         /* Cache only when it is _not_ an uninitialized extent */
2729         if (create != EXT4_CREATE_UNINITIALIZED_EXT)
2730                 ext4_ext_put_in_cache(inode, iblock, allocated, newblock,
2731                                                 EXT4_EXT_CACHE_EXTENT);
2732 out:
2733         if (allocated > max_blocks)
2734                 allocated = max_blocks;
2735         ext4_ext_show_leaf(inode, path);
2736         __set_bit(BH_Mapped, &bh_result->b_state);
2737         bh_result->b_bdev = inode->i_sb->s_bdev;
2738         bh_result->b_blocknr = newblock;
2739 out2:
2740         if (path) {
2741                 ext4_ext_drop_refs(path);
2742                 kfree(path);
2743         }
2744         return err ? err : allocated;
2745 }
2746
2747 void ext4_ext_truncate(struct inode * inode, struct page *page)
2748 {
2749         struct address_space *mapping = inode->i_mapping;
2750         struct super_block *sb = inode->i_sb;
2751         ext4_lblk_t last_block;
2752         handle_t *handle;
2753         int err = 0;
2754
2755         /*
2756          * probably first extent we're gonna free will be last in block
2757          */
2758         err = ext4_writepage_trans_blocks(inode) + 3;
2759         handle = ext4_journal_start(inode, err);
2760         if (IS_ERR(handle)) {
2761                 if (page) {
2762                         clear_highpage(page);
2763                         flush_dcache_page(page);
2764                         unlock_page(page);
2765                         page_cache_release(page);
2766                 }
2767                 return;
2768         }
2769
2770         if (page)
2771                 ext4_block_truncate_page(handle, page, mapping, inode->i_size);
2772
2773         down_write(&EXT4_I(inode)->i_data_sem);
2774         ext4_ext_invalidate_cache(inode);
2775
2776         ext4_mb_discard_inode_preallocations(inode);
2777
2778         /*
2779          * TODO: optimization is possible here.
2780          * Probably we need not scan at all,
2781          * because page truncation is enough.
2782          */
2783         if (ext4_orphan_add(handle, inode))
2784                 goto out_stop;
2785
2786         /* we have to know where to truncate from in crash case */
2787         EXT4_I(inode)->i_disksize = inode->i_size;
2788         ext4_mark_inode_dirty(handle, inode);
2789
2790         last_block = (inode->i_size + sb->s_blocksize - 1)
2791                         >> EXT4_BLOCK_SIZE_BITS(sb);
2792         err = ext4_ext_remove_space(inode, last_block);
2793
2794         /* In a multi-transaction truncate, we only make the final
2795          * transaction synchronous.
2796          */
2797         if (IS_SYNC(inode))
2798                 handle->h_sync = 1;
2799
2800 out_stop:
2801         /*
2802          * If this was a simple ftruncate() and the file will remain alive,
2803          * then we need to clear up the orphan record which we created above.
2804          * However, if this was a real unlink then we were called by
2805          * ext4_delete_inode(), and we allow that function to clean up the
2806          * orphan info for us.
2807          */
2808         if (inode->i_nlink)
2809                 ext4_orphan_del(handle, inode);
2810
2811         up_write(&EXT4_I(inode)->i_data_sem);
2812         ext4_journal_stop(handle);
2813 }
2814
2815 /*
2816  * ext4_ext_writepage_trans_blocks:
2817  * calculate max number of blocks we could modify
2818  * in order to allocate new block for an inode
2819  */
2820 int ext4_ext_writepage_trans_blocks(struct inode *inode, int num)
2821 {
2822         int needed;
2823
2824         needed = ext4_ext_calc_credits_for_insert(inode, NULL);
2825
2826         /* caller wants to allocate num blocks, but note it includes sb */
2827         needed = needed * num - (num - 1);
2828
2829 #ifdef CONFIG_QUOTA
2830         needed += 2 * EXT4_QUOTA_TRANS_BLOCKS(inode->i_sb);
2831 #endif
2832
2833         return needed;
2834 }
2835
2836 static void ext4_falloc_update_inode(struct inode *inode,
2837                                 int mode, loff_t new_size, int update_ctime)
2838 {
2839         struct timespec now;
2840
2841         if (update_ctime) {
2842                 now = current_fs_time(inode->i_sb);
2843                 if (!timespec_equal(&inode->i_ctime, &now))
2844                         inode->i_ctime = now;
2845         }
2846         /*
2847          * Update only when preallocation was requested beyond
2848          * the file size.
2849          */
2850         if (!(mode & FALLOC_FL_KEEP_SIZE) &&
2851                                 new_size > i_size_read(inode)) {
2852                 i_size_write(inode, new_size);
2853                 EXT4_I(inode)->i_disksize = new_size;
2854         }
2855
2856 }
2857
2858 /*
2859  * preallocate space for a file. This implements ext4's fallocate inode
2860  * operation, which gets called from sys_fallocate system call.
2861  * For block-mapped files, posix_fallocate should fall back to the method
2862  * of writing zeroes to the required new blocks (the same behavior which is
2863  * expected for file systems which do not support fallocate() system call).
2864  */
2865 long ext4_fallocate(struct inode *inode, int mode, loff_t offset, loff_t len)
2866 {
2867         handle_t *handle;
2868         ext4_lblk_t block;
2869         loff_t new_size;
2870         unsigned long max_blocks;
2871         int ret = 0;
2872         int ret2 = 0;
2873         int retries = 0;
2874         struct buffer_head map_bh;
2875         unsigned int credits, blkbits = inode->i_blkbits;
2876
2877         /*
2878          * currently supporting (pre)allocate mode for extent-based
2879          * files _only_
2880          */
2881         if (!(EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL))
2882                 return -EOPNOTSUPP;
2883
2884         /* preallocation to directories is currently not supported */
2885         if (S_ISDIR(inode->i_mode))
2886                 return -ENODEV;
2887
2888         block = offset >> blkbits;
2889         /*
2890          * We can't just convert len to max_blocks because
2891          * If blocksize = 4096 offset = 3072 and len = 2048
2892          */
2893         max_blocks = (EXT4_BLOCK_ALIGN(len + offset, blkbits) >> blkbits)
2894                                                         - block;
2895         /*
2896          * credits to insert 1 extent into extent tree + buffers to be able to
2897          * modify 1 super block, 1 block bitmap and 1 group descriptor.
2898          */
2899         credits = EXT4_DATA_TRANS_BLOCKS(inode->i_sb) + 3;
2900         mutex_lock(&inode->i_mutex);
2901 retry:
2902         while (ret >= 0 && ret < max_blocks) {
2903                 block = block + ret;
2904                 max_blocks = max_blocks - ret;
2905                 handle = ext4_journal_start(inode, credits);
2906                 if (IS_ERR(handle)) {
2907                         ret = PTR_ERR(handle);
2908                         break;
2909                 }
2910                 ret = ext4_get_blocks_wrap(handle, inode, block,
2911                                           max_blocks, &map_bh,
2912                                           EXT4_CREATE_UNINITIALIZED_EXT, 0);
2913                 if (ret <= 0) {
2914 #ifdef EXT4FS_DEBUG
2915                         WARN_ON(ret <= 0);
2916                         printk(KERN_ERR "%s: ext4_ext_get_blocks "
2917                                     "returned error inode#%lu, block=%u, "
2918                                     "max_blocks=%lu", __func__,
2919                                     inode->i_ino, block, max_blocks);
2920 #endif
2921                         ext4_mark_inode_dirty(handle, inode);
2922                         ret2 = ext4_journal_stop(handle);
2923                         break;
2924                 }
2925                 if ((block + ret) >= (EXT4_BLOCK_ALIGN(offset + len,
2926                                                 blkbits) >> blkbits))
2927                         new_size = offset + len;
2928                 else
2929                         new_size = (block + ret) << blkbits;
2930
2931                 ext4_falloc_update_inode(inode, mode, new_size,
2932                                                 buffer_new(&map_bh));
2933                 ext4_mark_inode_dirty(handle, inode);
2934                 ret2 = ext4_journal_stop(handle);
2935                 if (ret2)
2936                         break;
2937         }
2938         if (ret == -ENOSPC &&
2939                         ext4_should_retry_alloc(inode->i_sb, &retries)) {
2940                 ret = 0;
2941                 goto retry;
2942         }
2943         mutex_unlock(&inode->i_mutex);
2944         return ret > 0 ? ret2 : ret;
2945 }