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