]> git.proxmox.com Git - mirror_ubuntu-bionic-kernel.git/blame - fs/ext4/extents.c
ext4: fix races between changing inode journal mode and ext4_writepages
[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 *
b8a07463 18 * You should have received a copy of the GNU General Public License
a86c6181
AT
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
a86c6181
AT
32#include <linux/fs.h>
33#include <linux/time.h>
cd02ff0b 34#include <linux/jbd2.h>
a86c6181
AT
35#include <linux/highuid.h>
36#include <linux/pagemap.h>
37#include <linux/quotaops.h>
38#include <linux/string.h>
39#include <linux/slab.h>
a86c6181 40#include <asm/uaccess.h>
6873fa0d 41#include <linux/fiemap.h>
66114cad 42#include <linux/backing-dev.h>
3dcf5451 43#include "ext4_jbd2.h"
4a092d73 44#include "ext4_extents.h"
f19d5870 45#include "xattr.h"
a86c6181 46
0562e0ba
JZ
47#include <trace/events/ext4.h>
48
5f95d21f
LC
49/*
50 * used by extent splitting.
51 */
52#define EXT4_EXT_MAY_ZEROOUT 0x1 /* safe to zeroout if split fails \
53 due to ENOSPC */
556615dc
LC
54#define EXT4_EXT_MARK_UNWRIT1 0x2 /* mark first half unwritten */
55#define EXT4_EXT_MARK_UNWRIT2 0x4 /* mark second half unwritten */
5f95d21f 56
dee1f973
DM
57#define EXT4_EXT_DATA_VALID1 0x8 /* first half contains valid data */
58#define EXT4_EXT_DATA_VALID2 0x10 /* second half contains valid data */
59
7ac5990d
DW
60static __le32 ext4_extent_block_csum(struct inode *inode,
61 struct ext4_extent_header *eh)
62{
63 struct ext4_inode_info *ei = EXT4_I(inode);
64 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
65 __u32 csum;
66
67 csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)eh,
68 EXT4_EXTENT_TAIL_OFFSET(eh));
69 return cpu_to_le32(csum);
70}
71
72static int ext4_extent_block_csum_verify(struct inode *inode,
73 struct ext4_extent_header *eh)
74{
75 struct ext4_extent_tail *et;
76
9aa5d32b 77 if (!ext4_has_metadata_csum(inode->i_sb))
7ac5990d
DW
78 return 1;
79
80 et = find_ext4_extent_tail(eh);
81 if (et->et_checksum != ext4_extent_block_csum(inode, eh))
82 return 0;
83 return 1;
84}
85
86static void ext4_extent_block_csum_set(struct inode *inode,
87 struct ext4_extent_header *eh)
88{
89 struct ext4_extent_tail *et;
90
9aa5d32b 91 if (!ext4_has_metadata_csum(inode->i_sb))
7ac5990d
DW
92 return;
93
94 et = find_ext4_extent_tail(eh);
95 et->et_checksum = ext4_extent_block_csum(inode, eh);
96}
97
d583fb87
AH
98static int ext4_split_extent(handle_t *handle,
99 struct inode *inode,
dfe50809 100 struct ext4_ext_path **ppath,
d583fb87
AH
101 struct ext4_map_blocks *map,
102 int split_flag,
103 int flags);
104
5f95d21f
LC
105static int ext4_split_extent_at(handle_t *handle,
106 struct inode *inode,
dfe50809 107 struct ext4_ext_path **ppath,
5f95d21f
LC
108 ext4_lblk_t split,
109 int split_flag,
110 int flags);
111
91dd8c11 112static int ext4_find_delayed_extent(struct inode *inode,
69eb33dc 113 struct extent_status *newes);
91dd8c11 114
487caeef
JK
115static int ext4_ext_truncate_extend_restart(handle_t *handle,
116 struct inode *inode,
117 int needed)
a86c6181
AT
118{
119 int err;
120
0390131b
FM
121 if (!ext4_handle_valid(handle))
122 return 0;
7b808191 123 if (handle->h_buffer_credits >= needed)
9102e4fa 124 return 0;
7b808191
TT
125 /*
126 * If we need to extend the journal get a few extra blocks
127 * while we're at it for efficiency's sake.
128 */
129 needed += 3;
130 err = ext4_journal_extend(handle, needed - handle->h_buffer_credits);
0123c939 131 if (err <= 0)
9102e4fa 132 return err;
487caeef 133 err = ext4_truncate_restart_trans(handle, inode, needed);
0617b83f
DM
134 if (err == 0)
135 err = -EAGAIN;
487caeef
JK
136
137 return err;
a86c6181
AT
138}
139
140/*
141 * could return:
142 * - EROFS
143 * - ENOMEM
144 */
145static int ext4_ext_get_access(handle_t *handle, struct inode *inode,
146 struct ext4_ext_path *path)
147{
148 if (path->p_bh) {
149 /* path points to block */
5d601255 150 BUFFER_TRACE(path->p_bh, "get_write_access");
a86c6181
AT
151 return ext4_journal_get_write_access(handle, path->p_bh);
152 }
153 /* path points to leaf/index in inode body */
154 /* we use in-core data, no need to protect them */
155 return 0;
156}
157
158/*
159 * could return:
160 * - EROFS
161 * - ENOMEM
162 * - EIO
163 */
2656497b
DW
164int __ext4_ext_dirty(const char *where, unsigned int line, handle_t *handle,
165 struct inode *inode, struct ext4_ext_path *path)
a86c6181
AT
166{
167 int err;
4b1f1660
DM
168
169 WARN_ON(!rwsem_is_locked(&EXT4_I(inode)->i_data_sem));
a86c6181 170 if (path->p_bh) {
7ac5990d 171 ext4_extent_block_csum_set(inode, ext_block_hdr(path->p_bh));
a86c6181 172 /* path points to block */
9ea7a0df
TT
173 err = __ext4_handle_dirty_metadata(where, line, handle,
174 inode, path->p_bh);
a86c6181
AT
175 } else {
176 /* path points to leaf/index in inode body */
177 err = ext4_mark_inode_dirty(handle, inode);
178 }
179 return err;
180}
181
f65e6fba 182static ext4_fsblk_t ext4_ext_find_goal(struct inode *inode,
a86c6181 183 struct ext4_ext_path *path,
725d26d3 184 ext4_lblk_t block)
a86c6181 185{
a86c6181 186 if (path) {
81fdbb4a 187 int depth = path->p_depth;
a86c6181 188 struct ext4_extent *ex;
a86c6181 189
ad4fb9ca
KM
190 /*
191 * Try to predict block placement assuming that we are
192 * filling in a file which will eventually be
193 * non-sparse --- i.e., in the case of libbfd writing
194 * an ELF object sections out-of-order but in a way
195 * the eventually results in a contiguous object or
196 * executable file, or some database extending a table
197 * space file. However, this is actually somewhat
198 * non-ideal if we are writing a sparse file such as
199 * qemu or KVM writing a raw image file that is going
200 * to stay fairly sparse, since it will end up
201 * fragmenting the file system's free space. Maybe we
202 * should have some hueristics or some way to allow
203 * userspace to pass a hint to file system,
b8d6568a 204 * especially if the latter case turns out to be
ad4fb9ca
KM
205 * common.
206 */
7e028976 207 ex = path[depth].p_ext;
ad4fb9ca
KM
208 if (ex) {
209 ext4_fsblk_t ext_pblk = ext4_ext_pblock(ex);
210 ext4_lblk_t ext_block = le32_to_cpu(ex->ee_block);
211
212 if (block > ext_block)
213 return ext_pblk + (block - ext_block);
214 else
215 return ext_pblk - (ext_block - block);
216 }
a86c6181 217
d0d856e8
RD
218 /* it looks like index is empty;
219 * try to find starting block from index itself */
a86c6181
AT
220 if (path[depth].p_bh)
221 return path[depth].p_bh->b_blocknr;
222 }
223
224 /* OK. use inode's group */
f86186b4 225 return ext4_inode_to_goal_block(inode);
a86c6181
AT
226}
227
654b4908
AK
228/*
229 * Allocation for a meta data block
230 */
f65e6fba 231static ext4_fsblk_t
654b4908 232ext4_ext_new_meta_block(handle_t *handle, struct inode *inode,
a86c6181 233 struct ext4_ext_path *path,
55f020db 234 struct ext4_extent *ex, int *err, unsigned int flags)
a86c6181 235{
f65e6fba 236 ext4_fsblk_t goal, newblock;
a86c6181
AT
237
238 goal = ext4_ext_find_goal(inode, path, le32_to_cpu(ex->ee_block));
55f020db
AH
239 newblock = ext4_new_meta_blocks(handle, inode, goal, flags,
240 NULL, err);
a86c6181
AT
241 return newblock;
242}
243
55ad63bf 244static inline int ext4_ext_space_block(struct inode *inode, int check)
a86c6181
AT
245{
246 int size;
247
248 size = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
249 / sizeof(struct ext4_extent);
bbf2f9fb 250#ifdef AGGRESSIVE_TEST
02dc62fb
YY
251 if (!check && size > 6)
252 size = 6;
a86c6181
AT
253#endif
254 return size;
255}
256
55ad63bf 257static inline int ext4_ext_space_block_idx(struct inode *inode, int check)
a86c6181
AT
258{
259 int size;
260
261 size = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
262 / sizeof(struct ext4_extent_idx);
bbf2f9fb 263#ifdef AGGRESSIVE_TEST
02dc62fb
YY
264 if (!check && size > 5)
265 size = 5;
a86c6181
AT
266#endif
267 return size;
268}
269
55ad63bf 270static inline int ext4_ext_space_root(struct inode *inode, int check)
a86c6181
AT
271{
272 int size;
273
274 size = sizeof(EXT4_I(inode)->i_data);
275 size -= sizeof(struct ext4_extent_header);
276 size /= sizeof(struct ext4_extent);
bbf2f9fb 277#ifdef AGGRESSIVE_TEST
02dc62fb
YY
278 if (!check && size > 3)
279 size = 3;
a86c6181
AT
280#endif
281 return size;
282}
283
55ad63bf 284static inline int ext4_ext_space_root_idx(struct inode *inode, int check)
a86c6181
AT
285{
286 int size;
287
288 size = sizeof(EXT4_I(inode)->i_data);
289 size -= sizeof(struct ext4_extent_header);
290 size /= sizeof(struct ext4_extent_idx);
bbf2f9fb 291#ifdef AGGRESSIVE_TEST
02dc62fb
YY
292 if (!check && size > 4)
293 size = 4;
a86c6181
AT
294#endif
295 return size;
296}
297
fcf6b1b7
DM
298static inline int
299ext4_force_split_extent_at(handle_t *handle, struct inode *inode,
dfe50809 300 struct ext4_ext_path **ppath, ext4_lblk_t lblk,
fcf6b1b7
DM
301 int nofail)
302{
dfe50809 303 struct ext4_ext_path *path = *ppath;
fcf6b1b7
DM
304 int unwritten = ext4_ext_is_unwritten(path[path->p_depth].p_ext);
305
dfe50809 306 return ext4_split_extent_at(handle, inode, ppath, lblk, unwritten ?
fcf6b1b7
DM
307 EXT4_EXT_MARK_UNWRIT1|EXT4_EXT_MARK_UNWRIT2 : 0,
308 EXT4_EX_NOCACHE | EXT4_GET_BLOCKS_PRE_IO |
309 (nofail ? EXT4_GET_BLOCKS_METADATA_NOFAIL:0));
310}
311
d2a17637
MC
312/*
313 * Calculate the number of metadata blocks needed
314 * to allocate @blocks
315 * Worse case is one block per extent
316 */
01f49d0b 317int ext4_ext_calc_metadata_amount(struct inode *inode, ext4_lblk_t lblock)
d2a17637 318{
9d0be502 319 struct ext4_inode_info *ei = EXT4_I(inode);
81fdbb4a 320 int idxs;
d2a17637 321
9d0be502
TT
322 idxs = ((inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
323 / sizeof(struct ext4_extent_idx));
d2a17637
MC
324
325 /*
9d0be502
TT
326 * If the new delayed allocation block is contiguous with the
327 * previous da block, it can share index blocks with the
328 * previous block, so we only need to allocate a new index
329 * block every idxs leaf blocks. At ldxs**2 blocks, we need
330 * an additional index block, and at ldxs**3 blocks, yet
331 * another index blocks.
d2a17637 332 */
9d0be502
TT
333 if (ei->i_da_metadata_calc_len &&
334 ei->i_da_metadata_calc_last_lblock+1 == lblock) {
81fdbb4a
YY
335 int num = 0;
336
9d0be502
TT
337 if ((ei->i_da_metadata_calc_len % idxs) == 0)
338 num++;
339 if ((ei->i_da_metadata_calc_len % (idxs*idxs)) == 0)
340 num++;
341 if ((ei->i_da_metadata_calc_len % (idxs*idxs*idxs)) == 0) {
342 num++;
343 ei->i_da_metadata_calc_len = 0;
344 } else
345 ei->i_da_metadata_calc_len++;
346 ei->i_da_metadata_calc_last_lblock++;
347 return num;
348 }
d2a17637 349
9d0be502
TT
350 /*
351 * In the worst case we need a new set of index blocks at
352 * every level of the inode's extent tree.
353 */
354 ei->i_da_metadata_calc_len = 1;
355 ei->i_da_metadata_calc_last_lblock = lblock;
356 return ext_depth(inode) + 1;
d2a17637
MC
357}
358
c29c0ae7
AT
359static int
360ext4_ext_max_entries(struct inode *inode, int depth)
361{
362 int max;
363
364 if (depth == ext_depth(inode)) {
365 if (depth == 0)
55ad63bf 366 max = ext4_ext_space_root(inode, 1);
c29c0ae7 367 else
55ad63bf 368 max = ext4_ext_space_root_idx(inode, 1);
c29c0ae7
AT
369 } else {
370 if (depth == 0)
55ad63bf 371 max = ext4_ext_space_block(inode, 1);
c29c0ae7 372 else
55ad63bf 373 max = ext4_ext_space_block_idx(inode, 1);
c29c0ae7
AT
374 }
375
376 return max;
377}
378
56b19868
AK
379static int ext4_valid_extent(struct inode *inode, struct ext4_extent *ext)
380{
bf89d16f 381 ext4_fsblk_t block = ext4_ext_pblock(ext);
56b19868 382 int len = ext4_ext_get_actual_len(ext);
5946d089
EG
383 ext4_lblk_t lblock = le32_to_cpu(ext->ee_block);
384 ext4_lblk_t last = lblock + len - 1;
e84a26ce 385
2f974865 386 if (len == 0 || lblock > last)
31d4f3a2 387 return 0;
6fd058f7 388 return ext4_data_block_valid(EXT4_SB(inode->i_sb), block, len);
56b19868
AK
389}
390
391static int ext4_valid_extent_idx(struct inode *inode,
392 struct ext4_extent_idx *ext_idx)
393{
bf89d16f 394 ext4_fsblk_t block = ext4_idx_pblock(ext_idx);
e84a26ce 395
6fd058f7 396 return ext4_data_block_valid(EXT4_SB(inode->i_sb), block, 1);
56b19868
AK
397}
398
399static int ext4_valid_extent_entries(struct inode *inode,
400 struct ext4_extent_header *eh,
401 int depth)
402{
56b19868
AK
403 unsigned short entries;
404 if (eh->eh_entries == 0)
405 return 1;
406
407 entries = le16_to_cpu(eh->eh_entries);
408
409 if (depth == 0) {
410 /* leaf entries */
81fdbb4a 411 struct ext4_extent *ext = EXT_FIRST_EXTENT(eh);
5946d089
EG
412 struct ext4_super_block *es = EXT4_SB(inode->i_sb)->s_es;
413 ext4_fsblk_t pblock = 0;
414 ext4_lblk_t lblock = 0;
415 ext4_lblk_t prev = 0;
416 int len = 0;
56b19868
AK
417 while (entries) {
418 if (!ext4_valid_extent(inode, ext))
419 return 0;
5946d089
EG
420
421 /* Check for overlapping extents */
422 lblock = le32_to_cpu(ext->ee_block);
423 len = ext4_ext_get_actual_len(ext);
424 if ((lblock <= prev) && prev) {
425 pblock = ext4_ext_pblock(ext);
426 es->s_last_error_block = cpu_to_le64(pblock);
427 return 0;
428 }
56b19868
AK
429 ext++;
430 entries--;
5946d089 431 prev = lblock + len - 1;
56b19868
AK
432 }
433 } else {
81fdbb4a 434 struct ext4_extent_idx *ext_idx = EXT_FIRST_INDEX(eh);
56b19868
AK
435 while (entries) {
436 if (!ext4_valid_extent_idx(inode, ext_idx))
437 return 0;
438 ext_idx++;
439 entries--;
440 }
441 }
442 return 1;
443}
444
c398eda0
TT
445static int __ext4_ext_check(const char *function, unsigned int line,
446 struct inode *inode, struct ext4_extent_header *eh,
c349179b 447 int depth, ext4_fsblk_t pblk)
c29c0ae7
AT
448{
449 const char *error_msg;
6a797d27 450 int max = 0, err = -EFSCORRUPTED;
c29c0ae7
AT
451
452 if (unlikely(eh->eh_magic != EXT4_EXT_MAGIC)) {
453 error_msg = "invalid magic";
454 goto corrupted;
455 }
456 if (unlikely(le16_to_cpu(eh->eh_depth) != depth)) {
457 error_msg = "unexpected eh_depth";
458 goto corrupted;
459 }
460 if (unlikely(eh->eh_max == 0)) {
461 error_msg = "invalid eh_max";
462 goto corrupted;
463 }
464 max = ext4_ext_max_entries(inode, depth);
465 if (unlikely(le16_to_cpu(eh->eh_max) > max)) {
466 error_msg = "too large eh_max";
467 goto corrupted;
468 }
469 if (unlikely(le16_to_cpu(eh->eh_entries) > le16_to_cpu(eh->eh_max))) {
470 error_msg = "invalid eh_entries";
471 goto corrupted;
472 }
56b19868
AK
473 if (!ext4_valid_extent_entries(inode, eh, depth)) {
474 error_msg = "invalid extent entries";
475 goto corrupted;
476 }
7ac5990d
DW
477 /* Verify checksum on non-root extent tree nodes */
478 if (ext_depth(inode) != depth &&
479 !ext4_extent_block_csum_verify(inode, eh)) {
480 error_msg = "extent tree corrupted";
6a797d27 481 err = -EFSBADCRC;
7ac5990d
DW
482 goto corrupted;
483 }
c29c0ae7
AT
484 return 0;
485
486corrupted:
c398eda0 487 ext4_error_inode(inode, function, line, 0,
c349179b
TT
488 "pblk %llu bad header/extent: %s - magic %x, "
489 "entries %u, max %u(%u), depth %u(%u)",
490 (unsigned long long) pblk, error_msg,
491 le16_to_cpu(eh->eh_magic),
492 le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max),
493 max, le16_to_cpu(eh->eh_depth), depth);
6a797d27 494 return err;
c29c0ae7
AT
495}
496
c349179b
TT
497#define ext4_ext_check(inode, eh, depth, pblk) \
498 __ext4_ext_check(__func__, __LINE__, (inode), (eh), (depth), (pblk))
c29c0ae7 499
7a262f7c
AK
500int ext4_ext_check_inode(struct inode *inode)
501{
c349179b 502 return ext4_ext_check(inode, ext_inode_hdr(inode), ext_depth(inode), 0);
7a262f7c
AK
503}
504
7d7ea89e
TT
505static struct buffer_head *
506__read_extent_tree_block(const char *function, unsigned int line,
107a7bd3
TT
507 struct inode *inode, ext4_fsblk_t pblk, int depth,
508 int flags)
f8489128 509{
7d7ea89e
TT
510 struct buffer_head *bh;
511 int err;
512
c45653c3 513 bh = sb_getblk_gfp(inode->i_sb, pblk, __GFP_MOVABLE | GFP_NOFS);
7d7ea89e
TT
514 if (unlikely(!bh))
515 return ERR_PTR(-ENOMEM);
f8489128 516
7d7ea89e
TT
517 if (!bh_uptodate_or_lock(bh)) {
518 trace_ext4_ext_load_extent(inode, pblk, _RET_IP_);
519 err = bh_submit_read(bh);
520 if (err < 0)
521 goto errout;
522 }
7869a4a6 523 if (buffer_verified(bh) && !(flags & EXT4_EX_FORCE_CACHE))
7d7ea89e
TT
524 return bh;
525 err = __ext4_ext_check(function, line, inode,
c349179b 526 ext_block_hdr(bh), depth, pblk);
7d7ea89e
TT
527 if (err)
528 goto errout;
f8489128 529 set_buffer_verified(bh);
107a7bd3
TT
530 /*
531 * If this is a leaf block, cache all of its entries
532 */
533 if (!(flags & EXT4_EX_NOCACHE) && depth == 0) {
534 struct ext4_extent_header *eh = ext_block_hdr(bh);
535 struct ext4_extent *ex = EXT_FIRST_EXTENT(eh);
536 ext4_lblk_t prev = 0;
537 int i;
538
539 for (i = le16_to_cpu(eh->eh_entries); i > 0; i--, ex++) {
540 unsigned int status = EXTENT_STATUS_WRITTEN;
541 ext4_lblk_t lblk = le32_to_cpu(ex->ee_block);
542 int len = ext4_ext_get_actual_len(ex);
543
544 if (prev && (prev != lblk))
545 ext4_es_cache_extent(inode, prev,
546 lblk - prev, ~0,
547 EXTENT_STATUS_HOLE);
548
556615dc 549 if (ext4_ext_is_unwritten(ex))
107a7bd3
TT
550 status = EXTENT_STATUS_UNWRITTEN;
551 ext4_es_cache_extent(inode, lblk, len,
552 ext4_ext_pblock(ex), status);
553 prev = lblk + len;
554 }
555 }
7d7ea89e
TT
556 return bh;
557errout:
558 put_bh(bh);
559 return ERR_PTR(err);
560
f8489128
DW
561}
562
107a7bd3
TT
563#define read_extent_tree_block(inode, pblk, depth, flags) \
564 __read_extent_tree_block(__func__, __LINE__, (inode), (pblk), \
565 (depth), (flags))
f8489128 566
7869a4a6
TT
567/*
568 * This function is called to cache a file's extent information in the
569 * extent status tree
570 */
571int ext4_ext_precache(struct inode *inode)
572{
573 struct ext4_inode_info *ei = EXT4_I(inode);
574 struct ext4_ext_path *path = NULL;
575 struct buffer_head *bh;
576 int i = 0, depth, ret = 0;
577
578 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
579 return 0; /* not an extent-mapped inode */
580
581 down_read(&ei->i_data_sem);
582 depth = ext_depth(inode);
583
584 path = kzalloc(sizeof(struct ext4_ext_path) * (depth + 1),
585 GFP_NOFS);
586 if (path == NULL) {
587 up_read(&ei->i_data_sem);
588 return -ENOMEM;
589 }
590
591 /* Don't cache anything if there are no external extent blocks */
592 if (depth == 0)
593 goto out;
594 path[0].p_hdr = ext_inode_hdr(inode);
595 ret = ext4_ext_check(inode, path[0].p_hdr, depth, 0);
596 if (ret)
597 goto out;
598 path[0].p_idx = EXT_FIRST_INDEX(path[0].p_hdr);
599 while (i >= 0) {
600 /*
601 * If this is a leaf block or we've reached the end of
602 * the index block, go up
603 */
604 if ((i == depth) ||
605 path[i].p_idx > EXT_LAST_INDEX(path[i].p_hdr)) {
606 brelse(path[i].p_bh);
607 path[i].p_bh = NULL;
608 i--;
609 continue;
610 }
611 bh = read_extent_tree_block(inode,
612 ext4_idx_pblock(path[i].p_idx++),
613 depth - i - 1,
614 EXT4_EX_FORCE_CACHE);
615 if (IS_ERR(bh)) {
616 ret = PTR_ERR(bh);
617 break;
618 }
619 i++;
620 path[i].p_bh = bh;
621 path[i].p_hdr = ext_block_hdr(bh);
622 path[i].p_idx = EXT_FIRST_INDEX(path[i].p_hdr);
623 }
624 ext4_set_inode_state(inode, EXT4_STATE_EXT_PRECACHED);
625out:
626 up_read(&ei->i_data_sem);
627 ext4_ext_drop_refs(path);
628 kfree(path);
629 return ret;
630}
631
a86c6181
AT
632#ifdef EXT_DEBUG
633static void ext4_ext_show_path(struct inode *inode, struct ext4_ext_path *path)
634{
635 int k, l = path->p_depth;
636
637 ext_debug("path:");
638 for (k = 0; k <= l; k++, path++) {
639 if (path->p_idx) {
2ae02107 640 ext_debug(" %d->%llu", le32_to_cpu(path->p_idx->ei_block),
bf89d16f 641 ext4_idx_pblock(path->p_idx));
a86c6181 642 } else if (path->p_ext) {
553f9008 643 ext_debug(" %d:[%d]%d:%llu ",
a86c6181 644 le32_to_cpu(path->p_ext->ee_block),
556615dc 645 ext4_ext_is_unwritten(path->p_ext),
a2df2a63 646 ext4_ext_get_actual_len(path->p_ext),
bf89d16f 647 ext4_ext_pblock(path->p_ext));
a86c6181
AT
648 } else
649 ext_debug(" []");
650 }
651 ext_debug("\n");
652}
653
654static void ext4_ext_show_leaf(struct inode *inode, struct ext4_ext_path *path)
655{
656 int depth = ext_depth(inode);
657 struct ext4_extent_header *eh;
658 struct ext4_extent *ex;
659 int i;
660
661 if (!path)
662 return;
663
664 eh = path[depth].p_hdr;
665 ex = EXT_FIRST_EXTENT(eh);
666
553f9008
M
667 ext_debug("Displaying leaf extents for inode %lu\n", inode->i_ino);
668
a86c6181 669 for (i = 0; i < le16_to_cpu(eh->eh_entries); i++, ex++) {
553f9008 670 ext_debug("%d:[%d]%d:%llu ", le32_to_cpu(ex->ee_block),
556615dc 671 ext4_ext_is_unwritten(ex),
bf89d16f 672 ext4_ext_get_actual_len(ex), ext4_ext_pblock(ex));
a86c6181
AT
673 }
674 ext_debug("\n");
675}
1b16da77
YY
676
677static void ext4_ext_show_move(struct inode *inode, struct ext4_ext_path *path,
678 ext4_fsblk_t newblock, int level)
679{
680 int depth = ext_depth(inode);
681 struct ext4_extent *ex;
682
683 if (depth != level) {
684 struct ext4_extent_idx *idx;
685 idx = path[level].p_idx;
686 while (idx <= EXT_MAX_INDEX(path[level].p_hdr)) {
687 ext_debug("%d: move %d:%llu in new index %llu\n", level,
688 le32_to_cpu(idx->ei_block),
689 ext4_idx_pblock(idx),
690 newblock);
691 idx++;
692 }
693
694 return;
695 }
696
697 ex = path[depth].p_ext;
698 while (ex <= EXT_MAX_EXTENT(path[depth].p_hdr)) {
699 ext_debug("move %d:%llu:[%d]%d in new leaf %llu\n",
700 le32_to_cpu(ex->ee_block),
701 ext4_ext_pblock(ex),
556615dc 702 ext4_ext_is_unwritten(ex),
1b16da77
YY
703 ext4_ext_get_actual_len(ex),
704 newblock);
705 ex++;
706 }
707}
708
a86c6181 709#else
af5bc92d
TT
710#define ext4_ext_show_path(inode, path)
711#define ext4_ext_show_leaf(inode, path)
1b16da77 712#define ext4_ext_show_move(inode, path, newblock, level)
a86c6181
AT
713#endif
714
b35905c1 715void ext4_ext_drop_refs(struct ext4_ext_path *path)
a86c6181 716{
b7ea89ad 717 int depth, i;
a86c6181 718
b7ea89ad
TT
719 if (!path)
720 return;
721 depth = path->p_depth;
a86c6181
AT
722 for (i = 0; i <= depth; i++, path++)
723 if (path->p_bh) {
724 brelse(path->p_bh);
725 path->p_bh = NULL;
726 }
727}
728
729/*
d0d856e8
RD
730 * ext4_ext_binsearch_idx:
731 * binary search for the closest index of the given block
c29c0ae7 732 * the header must be checked before calling this
a86c6181
AT
733 */
734static void
725d26d3
AK
735ext4_ext_binsearch_idx(struct inode *inode,
736 struct ext4_ext_path *path, ext4_lblk_t block)
a86c6181
AT
737{
738 struct ext4_extent_header *eh = path->p_hdr;
739 struct ext4_extent_idx *r, *l, *m;
740
a86c6181 741
bba90743 742 ext_debug("binsearch for %u(idx): ", block);
a86c6181
AT
743
744 l = EXT_FIRST_INDEX(eh) + 1;
e9f410b1 745 r = EXT_LAST_INDEX(eh);
a86c6181
AT
746 while (l <= r) {
747 m = l + (r - l) / 2;
748 if (block < le32_to_cpu(m->ei_block))
749 r = m - 1;
750 else
751 l = m + 1;
26d535ed
DM
752 ext_debug("%p(%u):%p(%u):%p(%u) ", l, le32_to_cpu(l->ei_block),
753 m, le32_to_cpu(m->ei_block),
754 r, le32_to_cpu(r->ei_block));
a86c6181
AT
755 }
756
757 path->p_idx = l - 1;
4a3c3a51 758 ext_debug(" -> %u->%lld ", le32_to_cpu(path->p_idx->ei_block),
bf89d16f 759 ext4_idx_pblock(path->p_idx));
a86c6181
AT
760
761#ifdef CHECK_BINSEARCH
762 {
763 struct ext4_extent_idx *chix, *ix;
764 int k;
765
766 chix = ix = EXT_FIRST_INDEX(eh);
767 for (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ix++) {
768 if (k != 0 &&
769 le32_to_cpu(ix->ei_block) <= le32_to_cpu(ix[-1].ei_block)) {
4776004f
TT
770 printk(KERN_DEBUG "k=%d, ix=0x%p, "
771 "first=0x%p\n", k,
772 ix, EXT_FIRST_INDEX(eh));
773 printk(KERN_DEBUG "%u <= %u\n",
a86c6181
AT
774 le32_to_cpu(ix->ei_block),
775 le32_to_cpu(ix[-1].ei_block));
776 }
777 BUG_ON(k && le32_to_cpu(ix->ei_block)
8c55e204 778 <= le32_to_cpu(ix[-1].ei_block));
a86c6181
AT
779 if (block < le32_to_cpu(ix->ei_block))
780 break;
781 chix = ix;
782 }
783 BUG_ON(chix != path->p_idx);
784 }
785#endif
786
787}
788
789/*
d0d856e8
RD
790 * ext4_ext_binsearch:
791 * binary search for closest extent of the given block
c29c0ae7 792 * the header must be checked before calling this
a86c6181
AT
793 */
794static void
725d26d3
AK
795ext4_ext_binsearch(struct inode *inode,
796 struct ext4_ext_path *path, ext4_lblk_t block)
a86c6181
AT
797{
798 struct ext4_extent_header *eh = path->p_hdr;
799 struct ext4_extent *r, *l, *m;
800
a86c6181
AT
801 if (eh->eh_entries == 0) {
802 /*
d0d856e8
RD
803 * this leaf is empty:
804 * we get such a leaf in split/add case
a86c6181
AT
805 */
806 return;
807 }
808
bba90743 809 ext_debug("binsearch for %u: ", block);
a86c6181
AT
810
811 l = EXT_FIRST_EXTENT(eh) + 1;
e9f410b1 812 r = EXT_LAST_EXTENT(eh);
a86c6181
AT
813
814 while (l <= r) {
815 m = l + (r - l) / 2;
816 if (block < le32_to_cpu(m->ee_block))
817 r = m - 1;
818 else
819 l = m + 1;
26d535ed
DM
820 ext_debug("%p(%u):%p(%u):%p(%u) ", l, le32_to_cpu(l->ee_block),
821 m, le32_to_cpu(m->ee_block),
822 r, le32_to_cpu(r->ee_block));
a86c6181
AT
823 }
824
825 path->p_ext = l - 1;
553f9008 826 ext_debug(" -> %d:%llu:[%d]%d ",
8c55e204 827 le32_to_cpu(path->p_ext->ee_block),
bf89d16f 828 ext4_ext_pblock(path->p_ext),
556615dc 829 ext4_ext_is_unwritten(path->p_ext),
a2df2a63 830 ext4_ext_get_actual_len(path->p_ext));
a86c6181
AT
831
832#ifdef CHECK_BINSEARCH
833 {
834 struct ext4_extent *chex, *ex;
835 int k;
836
837 chex = ex = EXT_FIRST_EXTENT(eh);
838 for (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ex++) {
839 BUG_ON(k && le32_to_cpu(ex->ee_block)
8c55e204 840 <= le32_to_cpu(ex[-1].ee_block));
a86c6181
AT
841 if (block < le32_to_cpu(ex->ee_block))
842 break;
843 chex = ex;
844 }
845 BUG_ON(chex != path->p_ext);
846 }
847#endif
848
849}
850
851int ext4_ext_tree_init(handle_t *handle, struct inode *inode)
852{
853 struct ext4_extent_header *eh;
854
855 eh = ext_inode_hdr(inode);
856 eh->eh_depth = 0;
857 eh->eh_entries = 0;
858 eh->eh_magic = EXT4_EXT_MAGIC;
55ad63bf 859 eh->eh_max = cpu_to_le16(ext4_ext_space_root(inode, 0));
a86c6181 860 ext4_mark_inode_dirty(handle, inode);
a86c6181
AT
861 return 0;
862}
863
864struct ext4_ext_path *
ed8a1a76
TT
865ext4_find_extent(struct inode *inode, ext4_lblk_t block,
866 struct ext4_ext_path **orig_path, int flags)
a86c6181
AT
867{
868 struct ext4_extent_header *eh;
869 struct buffer_head *bh;
705912ca
TT
870 struct ext4_ext_path *path = orig_path ? *orig_path : NULL;
871 short int depth, i, ppos = 0;
860d21e2 872 int ret;
a86c6181
AT
873
874 eh = ext_inode_hdr(inode);
c29c0ae7 875 depth = ext_depth(inode);
a86c6181 876
10809df8 877 if (path) {
523f431c 878 ext4_ext_drop_refs(path);
10809df8
TT
879 if (depth > path[0].p_maxdepth) {
880 kfree(path);
881 *orig_path = path = NULL;
882 }
883 }
884 if (!path) {
523f431c 885 /* account possible depth increase */
5d4958f9 886 path = kzalloc(sizeof(struct ext4_ext_path) * (depth + 2),
a86c6181 887 GFP_NOFS);
19008f6d 888 if (unlikely(!path))
a86c6181 889 return ERR_PTR(-ENOMEM);
10809df8 890 path[0].p_maxdepth = depth + 1;
a86c6181 891 }
a86c6181 892 path[0].p_hdr = eh;
1973adcb 893 path[0].p_bh = NULL;
a86c6181 894
c29c0ae7 895 i = depth;
a86c6181
AT
896 /* walk through the tree */
897 while (i) {
898 ext_debug("depth %d: num %d, max %d\n",
899 ppos, le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
c29c0ae7 900
a86c6181 901 ext4_ext_binsearch_idx(inode, path + ppos, block);
bf89d16f 902 path[ppos].p_block = ext4_idx_pblock(path[ppos].p_idx);
a86c6181
AT
903 path[ppos].p_depth = i;
904 path[ppos].p_ext = NULL;
905
107a7bd3
TT
906 bh = read_extent_tree_block(inode, path[ppos].p_block, --i,
907 flags);
a1c83681 908 if (IS_ERR(bh)) {
7d7ea89e 909 ret = PTR_ERR(bh);
a86c6181 910 goto err;
860d21e2 911 }
7d7ea89e 912
a86c6181
AT
913 eh = ext_block_hdr(bh);
914 ppos++;
273df556
FM
915 if (unlikely(ppos > depth)) {
916 put_bh(bh);
917 EXT4_ERROR_INODE(inode,
918 "ppos %d > depth %d", ppos, depth);
6a797d27 919 ret = -EFSCORRUPTED;
273df556
FM
920 goto err;
921 }
a86c6181
AT
922 path[ppos].p_bh = bh;
923 path[ppos].p_hdr = eh;
a86c6181
AT
924 }
925
926 path[ppos].p_depth = i;
a86c6181
AT
927 path[ppos].p_ext = NULL;
928 path[ppos].p_idx = NULL;
929
a86c6181
AT
930 /* find extent */
931 ext4_ext_binsearch(inode, path + ppos, block);
1973adcb
SF
932 /* if not an empty leaf */
933 if (path[ppos].p_ext)
bf89d16f 934 path[ppos].p_block = ext4_ext_pblock(path[ppos].p_ext);
a86c6181
AT
935
936 ext4_ext_show_path(inode, path);
937
938 return path;
939
940err:
941 ext4_ext_drop_refs(path);
dfe50809
TT
942 kfree(path);
943 if (orig_path)
944 *orig_path = NULL;
860d21e2 945 return ERR_PTR(ret);
a86c6181
AT
946}
947
948/*
d0d856e8
RD
949 * ext4_ext_insert_index:
950 * insert new index [@logical;@ptr] into the block at @curp;
951 * check where to insert: before @curp or after @curp
a86c6181 952 */
1f109d5a
TT
953static int ext4_ext_insert_index(handle_t *handle, struct inode *inode,
954 struct ext4_ext_path *curp,
955 int logical, ext4_fsblk_t ptr)
a86c6181
AT
956{
957 struct ext4_extent_idx *ix;
958 int len, err;
959
7e028976
AM
960 err = ext4_ext_get_access(handle, inode, curp);
961 if (err)
a86c6181
AT
962 return err;
963
273df556
FM
964 if (unlikely(logical == le32_to_cpu(curp->p_idx->ei_block))) {
965 EXT4_ERROR_INODE(inode,
966 "logical %d == ei_block %d!",
967 logical, le32_to_cpu(curp->p_idx->ei_block));
6a797d27 968 return -EFSCORRUPTED;
273df556 969 }
d4620315
RD
970
971 if (unlikely(le16_to_cpu(curp->p_hdr->eh_entries)
972 >= le16_to_cpu(curp->p_hdr->eh_max))) {
973 EXT4_ERROR_INODE(inode,
974 "eh_entries %d >= eh_max %d!",
975 le16_to_cpu(curp->p_hdr->eh_entries),
976 le16_to_cpu(curp->p_hdr->eh_max));
6a797d27 977 return -EFSCORRUPTED;
d4620315
RD
978 }
979
a86c6181
AT
980 if (logical > le32_to_cpu(curp->p_idx->ei_block)) {
981 /* insert after */
80e675f9 982 ext_debug("insert new index %d after: %llu\n", logical, ptr);
a86c6181
AT
983 ix = curp->p_idx + 1;
984 } else {
985 /* insert before */
80e675f9 986 ext_debug("insert new index %d before: %llu\n", logical, ptr);
a86c6181
AT
987 ix = curp->p_idx;
988 }
989
80e675f9
EG
990 len = EXT_LAST_INDEX(curp->p_hdr) - ix + 1;
991 BUG_ON(len < 0);
992 if (len > 0) {
993 ext_debug("insert new index %d: "
994 "move %d indices from 0x%p to 0x%p\n",
995 logical, len, ix, ix + 1);
996 memmove(ix + 1, ix, len * sizeof(struct ext4_extent_idx));
997 }
998
f472e026
TM
999 if (unlikely(ix > EXT_MAX_INDEX(curp->p_hdr))) {
1000 EXT4_ERROR_INODE(inode, "ix > EXT_MAX_INDEX!");
6a797d27 1001 return -EFSCORRUPTED;
f472e026
TM
1002 }
1003
a86c6181 1004 ix->ei_block = cpu_to_le32(logical);
f65e6fba 1005 ext4_idx_store_pblock(ix, ptr);
e8546d06 1006 le16_add_cpu(&curp->p_hdr->eh_entries, 1);
a86c6181 1007
273df556
FM
1008 if (unlikely(ix > EXT_LAST_INDEX(curp->p_hdr))) {
1009 EXT4_ERROR_INODE(inode, "ix > EXT_LAST_INDEX!");
6a797d27 1010 return -EFSCORRUPTED;
273df556 1011 }
a86c6181
AT
1012
1013 err = ext4_ext_dirty(handle, inode, curp);
1014 ext4_std_error(inode->i_sb, err);
1015
1016 return err;
1017}
1018
1019/*
d0d856e8
RD
1020 * ext4_ext_split:
1021 * inserts new subtree into the path, using free index entry
1022 * at depth @at:
1023 * - allocates all needed blocks (new leaf and all intermediate index blocks)
1024 * - makes decision where to split
1025 * - moves remaining extents and index entries (right to the split point)
1026 * into the newly allocated blocks
1027 * - initializes subtree
a86c6181
AT
1028 */
1029static int ext4_ext_split(handle_t *handle, struct inode *inode,
55f020db
AH
1030 unsigned int flags,
1031 struct ext4_ext_path *path,
1032 struct ext4_extent *newext, int at)
a86c6181
AT
1033{
1034 struct buffer_head *bh = NULL;
1035 int depth = ext_depth(inode);
1036 struct ext4_extent_header *neh;
1037 struct ext4_extent_idx *fidx;
a86c6181 1038 int i = at, k, m, a;
f65e6fba 1039 ext4_fsblk_t newblock, oldblock;
a86c6181 1040 __le32 border;
f65e6fba 1041 ext4_fsblk_t *ablocks = NULL; /* array of allocated blocks */
a86c6181
AT
1042 int err = 0;
1043
1044 /* make decision: where to split? */
d0d856e8 1045 /* FIXME: now decision is simplest: at current extent */
a86c6181 1046
d0d856e8 1047 /* if current leaf will be split, then we should use
a86c6181 1048 * border from split point */
273df556
FM
1049 if (unlikely(path[depth].p_ext > EXT_MAX_EXTENT(path[depth].p_hdr))) {
1050 EXT4_ERROR_INODE(inode, "p_ext > EXT_MAX_EXTENT!");
6a797d27 1051 return -EFSCORRUPTED;
273df556 1052 }
a86c6181
AT
1053 if (path[depth].p_ext != EXT_MAX_EXTENT(path[depth].p_hdr)) {
1054 border = path[depth].p_ext[1].ee_block;
d0d856e8 1055 ext_debug("leaf will be split."
a86c6181 1056 " next leaf starts at %d\n",
8c55e204 1057 le32_to_cpu(border));
a86c6181
AT
1058 } else {
1059 border = newext->ee_block;
1060 ext_debug("leaf will be added."
1061 " next leaf starts at %d\n",
8c55e204 1062 le32_to_cpu(border));
a86c6181
AT
1063 }
1064
1065 /*
d0d856e8
RD
1066 * If error occurs, then we break processing
1067 * and mark filesystem read-only. index won't
a86c6181 1068 * be inserted and tree will be in consistent
d0d856e8 1069 * state. Next mount will repair buffers too.
a86c6181
AT
1070 */
1071
1072 /*
d0d856e8
RD
1073 * Get array to track all allocated blocks.
1074 * We need this to handle errors and free blocks
1075 * upon them.
a86c6181 1076 */
5d4958f9 1077 ablocks = kzalloc(sizeof(ext4_fsblk_t) * depth, GFP_NOFS);
a86c6181
AT
1078 if (!ablocks)
1079 return -ENOMEM;
a86c6181
AT
1080
1081 /* allocate all needed blocks */
1082 ext_debug("allocate %d blocks for indexes/leaf\n", depth - at);
1083 for (a = 0; a < depth - at; a++) {
654b4908 1084 newblock = ext4_ext_new_meta_block(handle, inode, path,
55f020db 1085 newext, &err, flags);
a86c6181
AT
1086 if (newblock == 0)
1087 goto cleanup;
1088 ablocks[a] = newblock;
1089 }
1090
1091 /* initialize new leaf */
1092 newblock = ablocks[--a];
273df556
FM
1093 if (unlikely(newblock == 0)) {
1094 EXT4_ERROR_INODE(inode, "newblock == 0!");
6a797d27 1095 err = -EFSCORRUPTED;
273df556
FM
1096 goto cleanup;
1097 }
c45653c3 1098 bh = sb_getblk_gfp(inode->i_sb, newblock, __GFP_MOVABLE | GFP_NOFS);
aebf0243 1099 if (unlikely(!bh)) {
860d21e2 1100 err = -ENOMEM;
a86c6181
AT
1101 goto cleanup;
1102 }
1103 lock_buffer(bh);
1104
7e028976
AM
1105 err = ext4_journal_get_create_access(handle, bh);
1106 if (err)
a86c6181
AT
1107 goto cleanup;
1108
1109 neh = ext_block_hdr(bh);
1110 neh->eh_entries = 0;
55ad63bf 1111 neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0));
a86c6181
AT
1112 neh->eh_magic = EXT4_EXT_MAGIC;
1113 neh->eh_depth = 0;
a86c6181 1114
d0d856e8 1115 /* move remainder of path[depth] to the new leaf */
273df556
FM
1116 if (unlikely(path[depth].p_hdr->eh_entries !=
1117 path[depth].p_hdr->eh_max)) {
1118 EXT4_ERROR_INODE(inode, "eh_entries %d != eh_max %d!",
1119 path[depth].p_hdr->eh_entries,
1120 path[depth].p_hdr->eh_max);
6a797d27 1121 err = -EFSCORRUPTED;
273df556
FM
1122 goto cleanup;
1123 }
a86c6181 1124 /* start copy from next extent */
1b16da77
YY
1125 m = EXT_MAX_EXTENT(path[depth].p_hdr) - path[depth].p_ext++;
1126 ext4_ext_show_move(inode, path, newblock, depth);
a86c6181 1127 if (m) {
1b16da77
YY
1128 struct ext4_extent *ex;
1129 ex = EXT_FIRST_EXTENT(neh);
1130 memmove(ex, path[depth].p_ext, sizeof(struct ext4_extent) * m);
e8546d06 1131 le16_add_cpu(&neh->eh_entries, m);
a86c6181
AT
1132 }
1133
7ac5990d 1134 ext4_extent_block_csum_set(inode, neh);
a86c6181
AT
1135 set_buffer_uptodate(bh);
1136 unlock_buffer(bh);
1137
0390131b 1138 err = ext4_handle_dirty_metadata(handle, inode, bh);
7e028976 1139 if (err)
a86c6181
AT
1140 goto cleanup;
1141 brelse(bh);
1142 bh = NULL;
1143
1144 /* correct old leaf */
1145 if (m) {
7e028976
AM
1146 err = ext4_ext_get_access(handle, inode, path + depth);
1147 if (err)
a86c6181 1148 goto cleanup;
e8546d06 1149 le16_add_cpu(&path[depth].p_hdr->eh_entries, -m);
7e028976
AM
1150 err = ext4_ext_dirty(handle, inode, path + depth);
1151 if (err)
a86c6181
AT
1152 goto cleanup;
1153
1154 }
1155
1156 /* create intermediate indexes */
1157 k = depth - at - 1;
273df556
FM
1158 if (unlikely(k < 0)) {
1159 EXT4_ERROR_INODE(inode, "k %d < 0!", k);
6a797d27 1160 err = -EFSCORRUPTED;
273df556
FM
1161 goto cleanup;
1162 }
a86c6181
AT
1163 if (k)
1164 ext_debug("create %d intermediate indices\n", k);
1165 /* insert new index into current index block */
1166 /* current depth stored in i var */
1167 i = depth - 1;
1168 while (k--) {
1169 oldblock = newblock;
1170 newblock = ablocks[--a];
bba90743 1171 bh = sb_getblk(inode->i_sb, newblock);
aebf0243 1172 if (unlikely(!bh)) {
860d21e2 1173 err = -ENOMEM;
a86c6181
AT
1174 goto cleanup;
1175 }
1176 lock_buffer(bh);
1177
7e028976
AM
1178 err = ext4_journal_get_create_access(handle, bh);
1179 if (err)
a86c6181
AT
1180 goto cleanup;
1181
1182 neh = ext_block_hdr(bh);
1183 neh->eh_entries = cpu_to_le16(1);
1184 neh->eh_magic = EXT4_EXT_MAGIC;
55ad63bf 1185 neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0));
a86c6181
AT
1186 neh->eh_depth = cpu_to_le16(depth - i);
1187 fidx = EXT_FIRST_INDEX(neh);
1188 fidx->ei_block = border;
f65e6fba 1189 ext4_idx_store_pblock(fidx, oldblock);
a86c6181 1190
bba90743
ES
1191 ext_debug("int.index at %d (block %llu): %u -> %llu\n",
1192 i, newblock, le32_to_cpu(border), oldblock);
a86c6181 1193
1b16da77 1194 /* move remainder of path[i] to the new index block */
273df556
FM
1195 if (unlikely(EXT_MAX_INDEX(path[i].p_hdr) !=
1196 EXT_LAST_INDEX(path[i].p_hdr))) {
1197 EXT4_ERROR_INODE(inode,
1198 "EXT_MAX_INDEX != EXT_LAST_INDEX ee_block %d!",
1199 le32_to_cpu(path[i].p_ext->ee_block));
6a797d27 1200 err = -EFSCORRUPTED;
273df556
FM
1201 goto cleanup;
1202 }
1b16da77
YY
1203 /* start copy indexes */
1204 m = EXT_MAX_INDEX(path[i].p_hdr) - path[i].p_idx++;
1205 ext_debug("cur 0x%p, last 0x%p\n", path[i].p_idx,
1206 EXT_MAX_INDEX(path[i].p_hdr));
1207 ext4_ext_show_move(inode, path, newblock, i);
a86c6181 1208 if (m) {
1b16da77 1209 memmove(++fidx, path[i].p_idx,
a86c6181 1210 sizeof(struct ext4_extent_idx) * m);
e8546d06 1211 le16_add_cpu(&neh->eh_entries, m);
a86c6181 1212 }
7ac5990d 1213 ext4_extent_block_csum_set(inode, neh);
a86c6181
AT
1214 set_buffer_uptodate(bh);
1215 unlock_buffer(bh);
1216
0390131b 1217 err = ext4_handle_dirty_metadata(handle, inode, bh);
7e028976 1218 if (err)
a86c6181
AT
1219 goto cleanup;
1220 brelse(bh);
1221 bh = NULL;
1222
1223 /* correct old index */
1224 if (m) {
1225 err = ext4_ext_get_access(handle, inode, path + i);
1226 if (err)
1227 goto cleanup;
e8546d06 1228 le16_add_cpu(&path[i].p_hdr->eh_entries, -m);
a86c6181
AT
1229 err = ext4_ext_dirty(handle, inode, path + i);
1230 if (err)
1231 goto cleanup;
1232 }
1233
1234 i--;
1235 }
1236
1237 /* insert new index */
a86c6181
AT
1238 err = ext4_ext_insert_index(handle, inode, path + at,
1239 le32_to_cpu(border), newblock);
1240
1241cleanup:
1242 if (bh) {
1243 if (buffer_locked(bh))
1244 unlock_buffer(bh);
1245 brelse(bh);
1246 }
1247
1248 if (err) {
1249 /* free all allocated blocks in error case */
1250 for (i = 0; i < depth; i++) {
1251 if (!ablocks[i])
1252 continue;
7dc57615 1253 ext4_free_blocks(handle, inode, NULL, ablocks[i], 1,
e6362609 1254 EXT4_FREE_BLOCKS_METADATA);
a86c6181
AT
1255 }
1256 }
1257 kfree(ablocks);
1258
1259 return err;
1260}
1261
1262/*
d0d856e8
RD
1263 * ext4_ext_grow_indepth:
1264 * implements tree growing procedure:
1265 * - allocates new block
1266 * - moves top-level data (index block or leaf) into the new block
1267 * - initializes new top-level, creating index that points to the
1268 * just created block
a86c6181
AT
1269 */
1270static int ext4_ext_grow_indepth(handle_t *handle, struct inode *inode,
be5cd90d 1271 unsigned int flags)
a86c6181 1272{
a86c6181 1273 struct ext4_extent_header *neh;
a86c6181 1274 struct buffer_head *bh;
be5cd90d
DM
1275 ext4_fsblk_t newblock, goal = 0;
1276 struct ext4_super_block *es = EXT4_SB(inode->i_sb)->s_es;
a86c6181
AT
1277 int err = 0;
1278
be5cd90d
DM
1279 /* Try to prepend new index to old one */
1280 if (ext_depth(inode))
1281 goal = ext4_idx_pblock(EXT_FIRST_INDEX(ext_inode_hdr(inode)));
1282 if (goal > le32_to_cpu(es->s_first_data_block)) {
1283 flags |= EXT4_MB_HINT_TRY_GOAL;
1284 goal--;
1285 } else
1286 goal = ext4_inode_to_goal_block(inode);
1287 newblock = ext4_new_meta_blocks(handle, inode, goal, flags,
1288 NULL, &err);
a86c6181
AT
1289 if (newblock == 0)
1290 return err;
1291
c45653c3 1292 bh = sb_getblk_gfp(inode->i_sb, newblock, __GFP_MOVABLE | GFP_NOFS);
aebf0243 1293 if (unlikely(!bh))
860d21e2 1294 return -ENOMEM;
a86c6181
AT
1295 lock_buffer(bh);
1296
7e028976
AM
1297 err = ext4_journal_get_create_access(handle, bh);
1298 if (err) {
a86c6181
AT
1299 unlock_buffer(bh);
1300 goto out;
1301 }
1302
1303 /* move top-level index/leaf into new block */
1939dd84
DM
1304 memmove(bh->b_data, EXT4_I(inode)->i_data,
1305 sizeof(EXT4_I(inode)->i_data));
a86c6181
AT
1306
1307 /* set size of new block */
1308 neh = ext_block_hdr(bh);
1309 /* old root could have indexes or leaves
1310 * so calculate e_max right way */
1311 if (ext_depth(inode))
55ad63bf 1312 neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0));
a86c6181 1313 else
55ad63bf 1314 neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0));
a86c6181 1315 neh->eh_magic = EXT4_EXT_MAGIC;
7ac5990d 1316 ext4_extent_block_csum_set(inode, neh);
a86c6181
AT
1317 set_buffer_uptodate(bh);
1318 unlock_buffer(bh);
1319
0390131b 1320 err = ext4_handle_dirty_metadata(handle, inode, bh);
7e028976 1321 if (err)
a86c6181
AT
1322 goto out;
1323
1939dd84 1324 /* Update top-level index: num,max,pointer */
a86c6181 1325 neh = ext_inode_hdr(inode);
1939dd84
DM
1326 neh->eh_entries = cpu_to_le16(1);
1327 ext4_idx_store_pblock(EXT_FIRST_INDEX(neh), newblock);
1328 if (neh->eh_depth == 0) {
1329 /* Root extent block becomes index block */
1330 neh->eh_max = cpu_to_le16(ext4_ext_space_root_idx(inode, 0));
1331 EXT_FIRST_INDEX(neh)->ei_block =
1332 EXT_FIRST_EXTENT(neh)->ee_block;
1333 }
2ae02107 1334 ext_debug("new root: num %d(%d), lblock %d, ptr %llu\n",
a86c6181 1335 le16_to_cpu(neh->eh_entries), le16_to_cpu(neh->eh_max),
5a0790c2 1336 le32_to_cpu(EXT_FIRST_INDEX(neh)->ei_block),
bf89d16f 1337 ext4_idx_pblock(EXT_FIRST_INDEX(neh)));
a86c6181 1338
ba39ebb6 1339 le16_add_cpu(&neh->eh_depth, 1);
1939dd84 1340 ext4_mark_inode_dirty(handle, inode);
a86c6181
AT
1341out:
1342 brelse(bh);
1343
1344 return err;
1345}
1346
1347/*
d0d856e8
RD
1348 * ext4_ext_create_new_leaf:
1349 * finds empty index and adds new leaf.
1350 * if no free index is found, then it requests in-depth growing.
a86c6181
AT
1351 */
1352static int ext4_ext_create_new_leaf(handle_t *handle, struct inode *inode,
107a7bd3
TT
1353 unsigned int mb_flags,
1354 unsigned int gb_flags,
dfe50809 1355 struct ext4_ext_path **ppath,
55f020db 1356 struct ext4_extent *newext)
a86c6181 1357{
dfe50809 1358 struct ext4_ext_path *path = *ppath;
a86c6181
AT
1359 struct ext4_ext_path *curp;
1360 int depth, i, err = 0;
1361
1362repeat:
1363 i = depth = ext_depth(inode);
1364
1365 /* walk up to the tree and look for free index entry */
1366 curp = path + depth;
1367 while (i > 0 && !EXT_HAS_FREE_INDEX(curp)) {
1368 i--;
1369 curp--;
1370 }
1371
d0d856e8
RD
1372 /* we use already allocated block for index block,
1373 * so subsequent data blocks should be contiguous */
a86c6181
AT
1374 if (EXT_HAS_FREE_INDEX(curp)) {
1375 /* if we found index with free entry, then use that
1376 * entry: create all needed subtree and add new leaf */
107a7bd3 1377 err = ext4_ext_split(handle, inode, mb_flags, path, newext, i);
787e0981
SF
1378 if (err)
1379 goto out;
a86c6181
AT
1380
1381 /* refill path */
ed8a1a76 1382 path = ext4_find_extent(inode,
725d26d3 1383 (ext4_lblk_t)le32_to_cpu(newext->ee_block),
dfe50809 1384 ppath, gb_flags);
a86c6181
AT
1385 if (IS_ERR(path))
1386 err = PTR_ERR(path);
1387 } else {
1388 /* tree is full, time to grow in depth */
be5cd90d 1389 err = ext4_ext_grow_indepth(handle, inode, mb_flags);
a86c6181
AT
1390 if (err)
1391 goto out;
1392
1393 /* refill path */
ed8a1a76 1394 path = ext4_find_extent(inode,
725d26d3 1395 (ext4_lblk_t)le32_to_cpu(newext->ee_block),
dfe50809 1396 ppath, gb_flags);
a86c6181
AT
1397 if (IS_ERR(path)) {
1398 err = PTR_ERR(path);
1399 goto out;
1400 }
1401
1402 /*
d0d856e8
RD
1403 * only first (depth 0 -> 1) produces free space;
1404 * in all other cases we have to split the grown tree
a86c6181
AT
1405 */
1406 depth = ext_depth(inode);
1407 if (path[depth].p_hdr->eh_entries == path[depth].p_hdr->eh_max) {
d0d856e8 1408 /* now we need to split */
a86c6181
AT
1409 goto repeat;
1410 }
1411 }
1412
1413out:
1414 return err;
1415}
1416
1988b51e
AT
1417/*
1418 * search the closest allocated block to the left for *logical
1419 * and returns it at @logical + it's physical address at @phys
1420 * if *logical is the smallest allocated block, the function
1421 * returns 0 at @phys
1422 * return value contains 0 (success) or error code
1423 */
1f109d5a
TT
1424static int ext4_ext_search_left(struct inode *inode,
1425 struct ext4_ext_path *path,
1426 ext4_lblk_t *logical, ext4_fsblk_t *phys)
1988b51e
AT
1427{
1428 struct ext4_extent_idx *ix;
1429 struct ext4_extent *ex;
b939e376 1430 int depth, ee_len;
1988b51e 1431
273df556
FM
1432 if (unlikely(path == NULL)) {
1433 EXT4_ERROR_INODE(inode, "path == NULL *logical %d!", *logical);
6a797d27 1434 return -EFSCORRUPTED;
273df556 1435 }
1988b51e
AT
1436 depth = path->p_depth;
1437 *phys = 0;
1438
1439 if (depth == 0 && path->p_ext == NULL)
1440 return 0;
1441
1442 /* usually extent in the path covers blocks smaller
1443 * then *logical, but it can be that extent is the
1444 * first one in the file */
1445
1446 ex = path[depth].p_ext;
b939e376 1447 ee_len = ext4_ext_get_actual_len(ex);
1988b51e 1448 if (*logical < le32_to_cpu(ex->ee_block)) {
273df556
FM
1449 if (unlikely(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex)) {
1450 EXT4_ERROR_INODE(inode,
1451 "EXT_FIRST_EXTENT != ex *logical %d ee_block %d!",
1452 *logical, le32_to_cpu(ex->ee_block));
6a797d27 1453 return -EFSCORRUPTED;
273df556 1454 }
1988b51e
AT
1455 while (--depth >= 0) {
1456 ix = path[depth].p_idx;
273df556
FM
1457 if (unlikely(ix != EXT_FIRST_INDEX(path[depth].p_hdr))) {
1458 EXT4_ERROR_INODE(inode,
1459 "ix (%d) != EXT_FIRST_INDEX (%d) (depth %d)!",
6ee3b212 1460 ix != NULL ? le32_to_cpu(ix->ei_block) : 0,
273df556 1461 EXT_FIRST_INDEX(path[depth].p_hdr) != NULL ?
6ee3b212 1462 le32_to_cpu(EXT_FIRST_INDEX(path[depth].p_hdr)->ei_block) : 0,
273df556 1463 depth);
6a797d27 1464 return -EFSCORRUPTED;
273df556 1465 }
1988b51e
AT
1466 }
1467 return 0;
1468 }
1469
273df556
FM
1470 if (unlikely(*logical < (le32_to_cpu(ex->ee_block) + ee_len))) {
1471 EXT4_ERROR_INODE(inode,
1472 "logical %d < ee_block %d + ee_len %d!",
1473 *logical, le32_to_cpu(ex->ee_block), ee_len);
6a797d27 1474 return -EFSCORRUPTED;
273df556 1475 }
1988b51e 1476
b939e376 1477 *logical = le32_to_cpu(ex->ee_block) + ee_len - 1;
bf89d16f 1478 *phys = ext4_ext_pblock(ex) + ee_len - 1;
1988b51e
AT
1479 return 0;
1480}
1481
1482/*
1483 * search the closest allocated block to the right for *logical
1484 * and returns it at @logical + it's physical address at @phys
df3ab170 1485 * if *logical is the largest allocated block, the function
1988b51e
AT
1486 * returns 0 at @phys
1487 * return value contains 0 (success) or error code
1488 */
1f109d5a
TT
1489static int ext4_ext_search_right(struct inode *inode,
1490 struct ext4_ext_path *path,
4d33b1ef
TT
1491 ext4_lblk_t *logical, ext4_fsblk_t *phys,
1492 struct ext4_extent **ret_ex)
1988b51e
AT
1493{
1494 struct buffer_head *bh = NULL;
1495 struct ext4_extent_header *eh;
1496 struct ext4_extent_idx *ix;
1497 struct ext4_extent *ex;
1498 ext4_fsblk_t block;
395a87bf
ES
1499 int depth; /* Note, NOT eh_depth; depth from top of tree */
1500 int ee_len;
1988b51e 1501
273df556
FM
1502 if (unlikely(path == NULL)) {
1503 EXT4_ERROR_INODE(inode, "path == NULL *logical %d!", *logical);
6a797d27 1504 return -EFSCORRUPTED;
273df556 1505 }
1988b51e
AT
1506 depth = path->p_depth;
1507 *phys = 0;
1508
1509 if (depth == 0 && path->p_ext == NULL)
1510 return 0;
1511
1512 /* usually extent in the path covers blocks smaller
1513 * then *logical, but it can be that extent is the
1514 * first one in the file */
1515
1516 ex = path[depth].p_ext;
b939e376 1517 ee_len = ext4_ext_get_actual_len(ex);
1988b51e 1518 if (*logical < le32_to_cpu(ex->ee_block)) {
273df556
FM
1519 if (unlikely(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex)) {
1520 EXT4_ERROR_INODE(inode,
1521 "first_extent(path[%d].p_hdr) != ex",
1522 depth);
6a797d27 1523 return -EFSCORRUPTED;
273df556 1524 }
1988b51e
AT
1525 while (--depth >= 0) {
1526 ix = path[depth].p_idx;
273df556
FM
1527 if (unlikely(ix != EXT_FIRST_INDEX(path[depth].p_hdr))) {
1528 EXT4_ERROR_INODE(inode,
1529 "ix != EXT_FIRST_INDEX *logical %d!",
1530 *logical);
6a797d27 1531 return -EFSCORRUPTED;
273df556 1532 }
1988b51e 1533 }
4d33b1ef 1534 goto found_extent;
1988b51e
AT
1535 }
1536
273df556
FM
1537 if (unlikely(*logical < (le32_to_cpu(ex->ee_block) + ee_len))) {
1538 EXT4_ERROR_INODE(inode,
1539 "logical %d < ee_block %d + ee_len %d!",
1540 *logical, le32_to_cpu(ex->ee_block), ee_len);
6a797d27 1541 return -EFSCORRUPTED;
273df556 1542 }
1988b51e
AT
1543
1544 if (ex != EXT_LAST_EXTENT(path[depth].p_hdr)) {
1545 /* next allocated block in this leaf */
1546 ex++;
4d33b1ef 1547 goto found_extent;
1988b51e
AT
1548 }
1549
1550 /* go up and search for index to the right */
1551 while (--depth >= 0) {
1552 ix = path[depth].p_idx;
1553 if (ix != EXT_LAST_INDEX(path[depth].p_hdr))
25f1ee3a 1554 goto got_index;
1988b51e
AT
1555 }
1556
25f1ee3a
WF
1557 /* we've gone up to the root and found no index to the right */
1558 return 0;
1988b51e 1559
25f1ee3a 1560got_index:
1988b51e
AT
1561 /* we've found index to the right, let's
1562 * follow it and find the closest allocated
1563 * block to the right */
1564 ix++;
bf89d16f 1565 block = ext4_idx_pblock(ix);
1988b51e 1566 while (++depth < path->p_depth) {
395a87bf 1567 /* subtract from p_depth to get proper eh_depth */
7d7ea89e 1568 bh = read_extent_tree_block(inode, block,
107a7bd3 1569 path->p_depth - depth, 0);
7d7ea89e
TT
1570 if (IS_ERR(bh))
1571 return PTR_ERR(bh);
1572 eh = ext_block_hdr(bh);
1988b51e 1573 ix = EXT_FIRST_INDEX(eh);
bf89d16f 1574 block = ext4_idx_pblock(ix);
1988b51e
AT
1575 put_bh(bh);
1576 }
1577
107a7bd3 1578 bh = read_extent_tree_block(inode, block, path->p_depth - depth, 0);
7d7ea89e
TT
1579 if (IS_ERR(bh))
1580 return PTR_ERR(bh);
1988b51e 1581 eh = ext_block_hdr(bh);
1988b51e 1582 ex = EXT_FIRST_EXTENT(eh);
4d33b1ef 1583found_extent:
1988b51e 1584 *logical = le32_to_cpu(ex->ee_block);
bf89d16f 1585 *phys = ext4_ext_pblock(ex);
4d33b1ef
TT
1586 *ret_ex = ex;
1587 if (bh)
1588 put_bh(bh);
1988b51e 1589 return 0;
1988b51e
AT
1590}
1591
a86c6181 1592/*
d0d856e8 1593 * ext4_ext_next_allocated_block:
f17722f9 1594 * returns allocated block in subsequent extent or EXT_MAX_BLOCKS.
d0d856e8
RD
1595 * NOTE: it considers block number from index entry as
1596 * allocated block. Thus, index entries have to be consistent
1597 * with leaves.
a86c6181 1598 */
fcf6b1b7 1599ext4_lblk_t
a86c6181
AT
1600ext4_ext_next_allocated_block(struct ext4_ext_path *path)
1601{
1602 int depth;
1603
1604 BUG_ON(path == NULL);
1605 depth = path->p_depth;
1606
1607 if (depth == 0 && path->p_ext == NULL)
f17722f9 1608 return EXT_MAX_BLOCKS;
a86c6181
AT
1609
1610 while (depth >= 0) {
1611 if (depth == path->p_depth) {
1612 /* leaf */
6f8ff537
CW
1613 if (path[depth].p_ext &&
1614 path[depth].p_ext !=
a86c6181
AT
1615 EXT_LAST_EXTENT(path[depth].p_hdr))
1616 return le32_to_cpu(path[depth].p_ext[1].ee_block);
1617 } else {
1618 /* index */
1619 if (path[depth].p_idx !=
1620 EXT_LAST_INDEX(path[depth].p_hdr))
1621 return le32_to_cpu(path[depth].p_idx[1].ei_block);
1622 }
1623 depth--;
1624 }
1625
f17722f9 1626 return EXT_MAX_BLOCKS;
a86c6181
AT
1627}
1628
1629/*
d0d856e8 1630 * ext4_ext_next_leaf_block:
f17722f9 1631 * returns first allocated block from next leaf or EXT_MAX_BLOCKS
a86c6181 1632 */
5718789d 1633static ext4_lblk_t ext4_ext_next_leaf_block(struct ext4_ext_path *path)
a86c6181
AT
1634{
1635 int depth;
1636
1637 BUG_ON(path == NULL);
1638 depth = path->p_depth;
1639
1640 /* zero-tree has no leaf blocks at all */
1641 if (depth == 0)
f17722f9 1642 return EXT_MAX_BLOCKS;
a86c6181
AT
1643
1644 /* go to index block */
1645 depth--;
1646
1647 while (depth >= 0) {
1648 if (path[depth].p_idx !=
1649 EXT_LAST_INDEX(path[depth].p_hdr))
725d26d3
AK
1650 return (ext4_lblk_t)
1651 le32_to_cpu(path[depth].p_idx[1].ei_block);
a86c6181
AT
1652 depth--;
1653 }
1654
f17722f9 1655 return EXT_MAX_BLOCKS;
a86c6181
AT
1656}
1657
1658/*
d0d856e8
RD
1659 * ext4_ext_correct_indexes:
1660 * if leaf gets modified and modified extent is first in the leaf,
1661 * then we have to correct all indexes above.
a86c6181
AT
1662 * TODO: do we need to correct tree in all cases?
1663 */
1d03ec98 1664static int ext4_ext_correct_indexes(handle_t *handle, struct inode *inode,
a86c6181
AT
1665 struct ext4_ext_path *path)
1666{
1667 struct ext4_extent_header *eh;
1668 int depth = ext_depth(inode);
1669 struct ext4_extent *ex;
1670 __le32 border;
1671 int k, err = 0;
1672
1673 eh = path[depth].p_hdr;
1674 ex = path[depth].p_ext;
273df556
FM
1675
1676 if (unlikely(ex == NULL || eh == NULL)) {
1677 EXT4_ERROR_INODE(inode,
1678 "ex %p == NULL or eh %p == NULL", ex, eh);
6a797d27 1679 return -EFSCORRUPTED;
273df556 1680 }
a86c6181
AT
1681
1682 if (depth == 0) {
1683 /* there is no tree at all */
1684 return 0;
1685 }
1686
1687 if (ex != EXT_FIRST_EXTENT(eh)) {
1688 /* we correct tree if first leaf got modified only */
1689 return 0;
1690 }
1691
1692 /*
d0d856e8 1693 * TODO: we need correction if border is smaller than current one
a86c6181
AT
1694 */
1695 k = depth - 1;
1696 border = path[depth].p_ext->ee_block;
7e028976
AM
1697 err = ext4_ext_get_access(handle, inode, path + k);
1698 if (err)
a86c6181
AT
1699 return err;
1700 path[k].p_idx->ei_block = border;
7e028976
AM
1701 err = ext4_ext_dirty(handle, inode, path + k);
1702 if (err)
a86c6181
AT
1703 return err;
1704
1705 while (k--) {
1706 /* change all left-side indexes */
1707 if (path[k+1].p_idx != EXT_FIRST_INDEX(path[k+1].p_hdr))
1708 break;
7e028976
AM
1709 err = ext4_ext_get_access(handle, inode, path + k);
1710 if (err)
a86c6181
AT
1711 break;
1712 path[k].p_idx->ei_block = border;
7e028976
AM
1713 err = ext4_ext_dirty(handle, inode, path + k);
1714 if (err)
a86c6181
AT
1715 break;
1716 }
1717
1718 return err;
1719}
1720
748de673 1721int
a86c6181
AT
1722ext4_can_extents_be_merged(struct inode *inode, struct ext4_extent *ex1,
1723 struct ext4_extent *ex2)
1724{
da0169b3 1725 unsigned short ext1_ee_len, ext2_ee_len;
a2df2a63 1726
556615dc 1727 if (ext4_ext_is_unwritten(ex1) != ext4_ext_is_unwritten(ex2))
a2df2a63
AA
1728 return 0;
1729
1730 ext1_ee_len = ext4_ext_get_actual_len(ex1);
1731 ext2_ee_len = ext4_ext_get_actual_len(ex2);
1732
1733 if (le32_to_cpu(ex1->ee_block) + ext1_ee_len !=
63f57933 1734 le32_to_cpu(ex2->ee_block))
a86c6181
AT
1735 return 0;
1736
471d4011
SB
1737 /*
1738 * To allow future support for preallocated extents to be added
1739 * as an RO_COMPAT feature, refuse to merge to extents if
d0d856e8 1740 * this can result in the top bit of ee_len being set.
471d4011 1741 */
da0169b3 1742 if (ext1_ee_len + ext2_ee_len > EXT_INIT_MAX_LEN)
471d4011 1743 return 0;
109811c2
JK
1744 /*
1745 * The check for IO to unwritten extent is somewhat racy as we
1746 * increment i_unwritten / set EXT4_STATE_DIO_UNWRITTEN only after
1747 * dropping i_data_sem. But reserved blocks should save us in that
1748 * case.
1749 */
556615dc 1750 if (ext4_ext_is_unwritten(ex1) &&
a9b82415
DW
1751 (ext4_test_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN) ||
1752 atomic_read(&EXT4_I(inode)->i_unwritten) ||
556615dc 1753 (ext1_ee_len + ext2_ee_len > EXT_UNWRITTEN_MAX_LEN)))
a9b82415 1754 return 0;
bbf2f9fb 1755#ifdef AGGRESSIVE_TEST
b939e376 1756 if (ext1_ee_len >= 4)
a86c6181
AT
1757 return 0;
1758#endif
1759
bf89d16f 1760 if (ext4_ext_pblock(ex1) + ext1_ee_len == ext4_ext_pblock(ex2))
a86c6181
AT
1761 return 1;
1762 return 0;
1763}
1764
56055d3a
AA
1765/*
1766 * This function tries to merge the "ex" extent to the next extent in the tree.
1767 * It always tries to merge towards right. If you want to merge towards
1768 * left, pass "ex - 1" as argument instead of "ex".
1769 * Returns 0 if the extents (ex and ex+1) were _not_ merged and returns
1770 * 1 if they got merged.
1771 */
197217a5 1772static int ext4_ext_try_to_merge_right(struct inode *inode,
1f109d5a
TT
1773 struct ext4_ext_path *path,
1774 struct ext4_extent *ex)
56055d3a
AA
1775{
1776 struct ext4_extent_header *eh;
1777 unsigned int depth, len;
556615dc 1778 int merge_done = 0, unwritten;
56055d3a
AA
1779
1780 depth = ext_depth(inode);
1781 BUG_ON(path[depth].p_hdr == NULL);
1782 eh = path[depth].p_hdr;
1783
1784 while (ex < EXT_LAST_EXTENT(eh)) {
1785 if (!ext4_can_extents_be_merged(inode, ex, ex + 1))
1786 break;
1787 /* merge with next extent! */
556615dc 1788 unwritten = ext4_ext_is_unwritten(ex);
56055d3a
AA
1789 ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
1790 + ext4_ext_get_actual_len(ex + 1));
556615dc
LC
1791 if (unwritten)
1792 ext4_ext_mark_unwritten(ex);
56055d3a
AA
1793
1794 if (ex + 1 < EXT_LAST_EXTENT(eh)) {
1795 len = (EXT_LAST_EXTENT(eh) - ex - 1)
1796 * sizeof(struct ext4_extent);
1797 memmove(ex + 1, ex + 2, len);
1798 }
e8546d06 1799 le16_add_cpu(&eh->eh_entries, -1);
56055d3a
AA
1800 merge_done = 1;
1801 WARN_ON(eh->eh_entries == 0);
1802 if (!eh->eh_entries)
24676da4 1803 EXT4_ERROR_INODE(inode, "eh->eh_entries = 0!");
56055d3a
AA
1804 }
1805
1806 return merge_done;
1807}
1808
ecb94f5f
TT
1809/*
1810 * This function does a very simple check to see if we can collapse
1811 * an extent tree with a single extent tree leaf block into the inode.
1812 */
1813static void ext4_ext_try_to_merge_up(handle_t *handle,
1814 struct inode *inode,
1815 struct ext4_ext_path *path)
1816{
1817 size_t s;
1818 unsigned max_root = ext4_ext_space_root(inode, 0);
1819 ext4_fsblk_t blk;
1820
1821 if ((path[0].p_depth != 1) ||
1822 (le16_to_cpu(path[0].p_hdr->eh_entries) != 1) ||
1823 (le16_to_cpu(path[1].p_hdr->eh_entries) > max_root))
1824 return;
1825
1826 /*
1827 * We need to modify the block allocation bitmap and the block
1828 * group descriptor to release the extent tree block. If we
1829 * can't get the journal credits, give up.
1830 */
1831 if (ext4_journal_extend(handle, 2))
1832 return;
1833
1834 /*
1835 * Copy the extent data up to the inode
1836 */
1837 blk = ext4_idx_pblock(path[0].p_idx);
1838 s = le16_to_cpu(path[1].p_hdr->eh_entries) *
1839 sizeof(struct ext4_extent_idx);
1840 s += sizeof(struct ext4_extent_header);
1841
10809df8 1842 path[1].p_maxdepth = path[0].p_maxdepth;
ecb94f5f
TT
1843 memcpy(path[0].p_hdr, path[1].p_hdr, s);
1844 path[0].p_depth = 0;
1845 path[0].p_ext = EXT_FIRST_EXTENT(path[0].p_hdr) +
1846 (path[1].p_ext - EXT_FIRST_EXTENT(path[1].p_hdr));
1847 path[0].p_hdr->eh_max = cpu_to_le16(max_root);
1848
1849 brelse(path[1].p_bh);
1850 ext4_free_blocks(handle, inode, NULL, blk, 1,
71d4f7d0 1851 EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET);
ecb94f5f
TT
1852}
1853
197217a5
YY
1854/*
1855 * This function tries to merge the @ex extent to neighbours in the tree.
1856 * return 1 if merge left else 0.
1857 */
ecb94f5f
TT
1858static void ext4_ext_try_to_merge(handle_t *handle,
1859 struct inode *inode,
197217a5
YY
1860 struct ext4_ext_path *path,
1861 struct ext4_extent *ex) {
1862 struct ext4_extent_header *eh;
1863 unsigned int depth;
1864 int merge_done = 0;
197217a5
YY
1865
1866 depth = ext_depth(inode);
1867 BUG_ON(path[depth].p_hdr == NULL);
1868 eh = path[depth].p_hdr;
1869
1870 if (ex > EXT_FIRST_EXTENT(eh))
1871 merge_done = ext4_ext_try_to_merge_right(inode, path, ex - 1);
1872
1873 if (!merge_done)
ecb94f5f 1874 (void) ext4_ext_try_to_merge_right(inode, path, ex);
197217a5 1875
ecb94f5f 1876 ext4_ext_try_to_merge_up(handle, inode, path);
197217a5
YY
1877}
1878
25d14f98
AA
1879/*
1880 * check if a portion of the "newext" extent overlaps with an
1881 * existing extent.
1882 *
1883 * If there is an overlap discovered, it updates the length of the newext
1884 * such that there will be no overlap, and then returns 1.
1885 * If there is no overlap found, it returns 0.
1886 */
4d33b1ef
TT
1887static unsigned int ext4_ext_check_overlap(struct ext4_sb_info *sbi,
1888 struct inode *inode,
1f109d5a
TT
1889 struct ext4_extent *newext,
1890 struct ext4_ext_path *path)
25d14f98 1891{
725d26d3 1892 ext4_lblk_t b1, b2;
25d14f98
AA
1893 unsigned int depth, len1;
1894 unsigned int ret = 0;
1895
1896 b1 = le32_to_cpu(newext->ee_block);
a2df2a63 1897 len1 = ext4_ext_get_actual_len(newext);
25d14f98
AA
1898 depth = ext_depth(inode);
1899 if (!path[depth].p_ext)
1900 goto out;
f5a44db5 1901 b2 = EXT4_LBLK_CMASK(sbi, le32_to_cpu(path[depth].p_ext->ee_block));
25d14f98
AA
1902
1903 /*
1904 * get the next allocated block if the extent in the path
2b2d6d01 1905 * is before the requested block(s)
25d14f98
AA
1906 */
1907 if (b2 < b1) {
1908 b2 = ext4_ext_next_allocated_block(path);
f17722f9 1909 if (b2 == EXT_MAX_BLOCKS)
25d14f98 1910 goto out;
f5a44db5 1911 b2 = EXT4_LBLK_CMASK(sbi, b2);
25d14f98
AA
1912 }
1913
725d26d3 1914 /* check for wrap through zero on extent logical start block*/
25d14f98 1915 if (b1 + len1 < b1) {
f17722f9 1916 len1 = EXT_MAX_BLOCKS - b1;
25d14f98
AA
1917 newext->ee_len = cpu_to_le16(len1);
1918 ret = 1;
1919 }
1920
1921 /* check for overlap */
1922 if (b1 + len1 > b2) {
1923 newext->ee_len = cpu_to_le16(b2 - b1);
1924 ret = 1;
1925 }
1926out:
1927 return ret;
1928}
1929
a86c6181 1930/*
d0d856e8
RD
1931 * ext4_ext_insert_extent:
1932 * tries to merge requsted extent into the existing extent or
1933 * inserts requested extent as new one into the tree,
1934 * creating new leaf in the no-space case.
a86c6181
AT
1935 */
1936int ext4_ext_insert_extent(handle_t *handle, struct inode *inode,
dfe50809 1937 struct ext4_ext_path **ppath,
107a7bd3 1938 struct ext4_extent *newext, int gb_flags)
a86c6181 1939{
dfe50809 1940 struct ext4_ext_path *path = *ppath;
af5bc92d 1941 struct ext4_extent_header *eh;
a86c6181
AT
1942 struct ext4_extent *ex, *fex;
1943 struct ext4_extent *nearex; /* nearest extent */
1944 struct ext4_ext_path *npath = NULL;
725d26d3
AK
1945 int depth, len, err;
1946 ext4_lblk_t next;
556615dc 1947 int mb_flags = 0, unwritten;
a86c6181 1948
e3cf5d5d
TT
1949 if (gb_flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
1950 mb_flags |= EXT4_MB_DELALLOC_RESERVED;
273df556
FM
1951 if (unlikely(ext4_ext_get_actual_len(newext) == 0)) {
1952 EXT4_ERROR_INODE(inode, "ext4_ext_get_actual_len(newext) == 0");
6a797d27 1953 return -EFSCORRUPTED;
273df556 1954 }
a86c6181
AT
1955 depth = ext_depth(inode);
1956 ex = path[depth].p_ext;
be8981be 1957 eh = path[depth].p_hdr;
273df556
FM
1958 if (unlikely(path[depth].p_hdr == NULL)) {
1959 EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
6a797d27 1960 return -EFSCORRUPTED;
273df556 1961 }
a86c6181
AT
1962
1963 /* try to insert block into found extent and return */
107a7bd3 1964 if (ex && !(gb_flags & EXT4_GET_BLOCKS_PRE_IO)) {
a2df2a63
AA
1965
1966 /*
be8981be
LC
1967 * Try to see whether we should rather test the extent on
1968 * right from ex, or from the left of ex. This is because
ed8a1a76 1969 * ext4_find_extent() can return either extent on the
be8981be
LC
1970 * left, or on the right from the searched position. This
1971 * will make merging more effective.
a2df2a63 1972 */
be8981be
LC
1973 if (ex < EXT_LAST_EXTENT(eh) &&
1974 (le32_to_cpu(ex->ee_block) +
1975 ext4_ext_get_actual_len(ex) <
1976 le32_to_cpu(newext->ee_block))) {
1977 ex += 1;
1978 goto prepend;
1979 } else if ((ex > EXT_FIRST_EXTENT(eh)) &&
1980 (le32_to_cpu(newext->ee_block) +
1981 ext4_ext_get_actual_len(newext) <
1982 le32_to_cpu(ex->ee_block)))
1983 ex -= 1;
1984
1985 /* Try to append newex to the ex */
1986 if (ext4_can_extents_be_merged(inode, ex, newext)) {
1987 ext_debug("append [%d]%d block to %u:[%d]%d"
1988 "(from %llu)\n",
556615dc 1989 ext4_ext_is_unwritten(newext),
be8981be
LC
1990 ext4_ext_get_actual_len(newext),
1991 le32_to_cpu(ex->ee_block),
556615dc 1992 ext4_ext_is_unwritten(ex),
be8981be
LC
1993 ext4_ext_get_actual_len(ex),
1994 ext4_ext_pblock(ex));
1995 err = ext4_ext_get_access(handle, inode,
1996 path + depth);
1997 if (err)
1998 return err;
556615dc 1999 unwritten = ext4_ext_is_unwritten(ex);
be8981be 2000 ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
a2df2a63 2001 + ext4_ext_get_actual_len(newext));
556615dc
LC
2002 if (unwritten)
2003 ext4_ext_mark_unwritten(ex);
be8981be
LC
2004 eh = path[depth].p_hdr;
2005 nearex = ex;
2006 goto merge;
2007 }
2008
2009prepend:
2010 /* Try to prepend newex to the ex */
2011 if (ext4_can_extents_be_merged(inode, newext, ex)) {
2012 ext_debug("prepend %u[%d]%d block to %u:[%d]%d"
2013 "(from %llu)\n",
2014 le32_to_cpu(newext->ee_block),
556615dc 2015 ext4_ext_is_unwritten(newext),
be8981be
LC
2016 ext4_ext_get_actual_len(newext),
2017 le32_to_cpu(ex->ee_block),
556615dc 2018 ext4_ext_is_unwritten(ex),
be8981be
LC
2019 ext4_ext_get_actual_len(ex),
2020 ext4_ext_pblock(ex));
2021 err = ext4_ext_get_access(handle, inode,
2022 path + depth);
2023 if (err)
2024 return err;
2025
556615dc 2026 unwritten = ext4_ext_is_unwritten(ex);
be8981be
LC
2027 ex->ee_block = newext->ee_block;
2028 ext4_ext_store_pblock(ex, ext4_ext_pblock(newext));
2029 ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
2030 + ext4_ext_get_actual_len(newext));
556615dc
LC
2031 if (unwritten)
2032 ext4_ext_mark_unwritten(ex);
be8981be
LC
2033 eh = path[depth].p_hdr;
2034 nearex = ex;
2035 goto merge;
2036 }
a86c6181
AT
2037 }
2038
a86c6181
AT
2039 depth = ext_depth(inode);
2040 eh = path[depth].p_hdr;
2041 if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max))
2042 goto has_space;
2043
2044 /* probably next leaf has space for us? */
2045 fex = EXT_LAST_EXTENT(eh);
598dbdf2
RD
2046 next = EXT_MAX_BLOCKS;
2047 if (le32_to_cpu(newext->ee_block) > le32_to_cpu(fex->ee_block))
5718789d 2048 next = ext4_ext_next_leaf_block(path);
598dbdf2 2049 if (next != EXT_MAX_BLOCKS) {
32de6756 2050 ext_debug("next leaf block - %u\n", next);
a86c6181 2051 BUG_ON(npath != NULL);
ed8a1a76 2052 npath = ext4_find_extent(inode, next, NULL, 0);
a86c6181
AT
2053 if (IS_ERR(npath))
2054 return PTR_ERR(npath);
2055 BUG_ON(npath->p_depth != path->p_depth);
2056 eh = npath[depth].p_hdr;
2057 if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max)) {
25985edc 2058 ext_debug("next leaf isn't full(%d)\n",
a86c6181
AT
2059 le16_to_cpu(eh->eh_entries));
2060 path = npath;
ffb505ff 2061 goto has_space;
a86c6181
AT
2062 }
2063 ext_debug("next leaf has no free space(%d,%d)\n",
2064 le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
2065 }
2066
2067 /*
d0d856e8
RD
2068 * There is no free space in the found leaf.
2069 * We're gonna add a new leaf in the tree.
a86c6181 2070 */
107a7bd3 2071 if (gb_flags & EXT4_GET_BLOCKS_METADATA_NOFAIL)
e3cf5d5d 2072 mb_flags |= EXT4_MB_USE_RESERVED;
107a7bd3 2073 err = ext4_ext_create_new_leaf(handle, inode, mb_flags, gb_flags,
dfe50809 2074 ppath, newext);
a86c6181
AT
2075 if (err)
2076 goto cleanup;
2077 depth = ext_depth(inode);
2078 eh = path[depth].p_hdr;
2079
2080has_space:
2081 nearex = path[depth].p_ext;
2082
7e028976
AM
2083 err = ext4_ext_get_access(handle, inode, path + depth);
2084 if (err)
a86c6181
AT
2085 goto cleanup;
2086
2087 if (!nearex) {
2088 /* there is no extent in this leaf, create first one */
32de6756 2089 ext_debug("first extent in the leaf: %u:%llu:[%d]%d\n",
8c55e204 2090 le32_to_cpu(newext->ee_block),
bf89d16f 2091 ext4_ext_pblock(newext),
556615dc 2092 ext4_ext_is_unwritten(newext),
a2df2a63 2093 ext4_ext_get_actual_len(newext));
80e675f9
EG
2094 nearex = EXT_FIRST_EXTENT(eh);
2095 } else {
2096 if (le32_to_cpu(newext->ee_block)
8c55e204 2097 > le32_to_cpu(nearex->ee_block)) {
80e675f9 2098 /* Insert after */
32de6756
YY
2099 ext_debug("insert %u:%llu:[%d]%d before: "
2100 "nearest %p\n",
80e675f9
EG
2101 le32_to_cpu(newext->ee_block),
2102 ext4_ext_pblock(newext),
556615dc 2103 ext4_ext_is_unwritten(newext),
80e675f9
EG
2104 ext4_ext_get_actual_len(newext),
2105 nearex);
2106 nearex++;
2107 } else {
2108 /* Insert before */
2109 BUG_ON(newext->ee_block == nearex->ee_block);
32de6756
YY
2110 ext_debug("insert %u:%llu:[%d]%d after: "
2111 "nearest %p\n",
8c55e204 2112 le32_to_cpu(newext->ee_block),
bf89d16f 2113 ext4_ext_pblock(newext),
556615dc 2114 ext4_ext_is_unwritten(newext),
a2df2a63 2115 ext4_ext_get_actual_len(newext),
80e675f9
EG
2116 nearex);
2117 }
2118 len = EXT_LAST_EXTENT(eh) - nearex + 1;
2119 if (len > 0) {
32de6756 2120 ext_debug("insert %u:%llu:[%d]%d: "
80e675f9
EG
2121 "move %d extents from 0x%p to 0x%p\n",
2122 le32_to_cpu(newext->ee_block),
2123 ext4_ext_pblock(newext),
556615dc 2124 ext4_ext_is_unwritten(newext),
80e675f9
EG
2125 ext4_ext_get_actual_len(newext),
2126 len, nearex, nearex + 1);
2127 memmove(nearex + 1, nearex,
2128 len * sizeof(struct ext4_extent));
a86c6181 2129 }
a86c6181
AT
2130 }
2131
e8546d06 2132 le16_add_cpu(&eh->eh_entries, 1);
80e675f9 2133 path[depth].p_ext = nearex;
a86c6181 2134 nearex->ee_block = newext->ee_block;
bf89d16f 2135 ext4_ext_store_pblock(nearex, ext4_ext_pblock(newext));
a86c6181 2136 nearex->ee_len = newext->ee_len;
a86c6181
AT
2137
2138merge:
e7bcf823 2139 /* try to merge extents */
107a7bd3 2140 if (!(gb_flags & EXT4_GET_BLOCKS_PRE_IO))
ecb94f5f 2141 ext4_ext_try_to_merge(handle, inode, path, nearex);
a86c6181 2142
a86c6181
AT
2143
2144 /* time to correct all indexes above */
2145 err = ext4_ext_correct_indexes(handle, inode, path);
2146 if (err)
2147 goto cleanup;
2148
ecb94f5f 2149 err = ext4_ext_dirty(handle, inode, path + path->p_depth);
a86c6181
AT
2150
2151cleanup:
b7ea89ad
TT
2152 ext4_ext_drop_refs(npath);
2153 kfree(npath);
a86c6181
AT
2154 return err;
2155}
2156
91dd8c11
LC
2157static int ext4_fill_fiemap_extents(struct inode *inode,
2158 ext4_lblk_t block, ext4_lblk_t num,
2159 struct fiemap_extent_info *fieinfo)
6873fa0d
ES
2160{
2161 struct ext4_ext_path *path = NULL;
6873fa0d 2162 struct ext4_extent *ex;
69eb33dc 2163 struct extent_status es;
91dd8c11 2164 ext4_lblk_t next, next_del, start = 0, end = 0;
6873fa0d 2165 ext4_lblk_t last = block + num;
91dd8c11
LC
2166 int exists, depth = 0, err = 0;
2167 unsigned int flags = 0;
2168 unsigned char blksize_bits = inode->i_sb->s_blocksize_bits;
6873fa0d 2169
f17722f9 2170 while (block < last && block != EXT_MAX_BLOCKS) {
6873fa0d
ES
2171 num = last - block;
2172 /* find extent for this block */
fab3a549 2173 down_read(&EXT4_I(inode)->i_data_sem);
91dd8c11 2174
ed8a1a76 2175 path = ext4_find_extent(inode, block, &path, 0);
6873fa0d 2176 if (IS_ERR(path)) {
91dd8c11 2177 up_read(&EXT4_I(inode)->i_data_sem);
6873fa0d
ES
2178 err = PTR_ERR(path);
2179 path = NULL;
2180 break;
2181 }
2182
2183 depth = ext_depth(inode);
273df556 2184 if (unlikely(path[depth].p_hdr == NULL)) {
91dd8c11 2185 up_read(&EXT4_I(inode)->i_data_sem);
273df556 2186 EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
6a797d27 2187 err = -EFSCORRUPTED;
273df556
FM
2188 break;
2189 }
6873fa0d
ES
2190 ex = path[depth].p_ext;
2191 next = ext4_ext_next_allocated_block(path);
2192
91dd8c11 2193 flags = 0;
6873fa0d
ES
2194 exists = 0;
2195 if (!ex) {
2196 /* there is no extent yet, so try to allocate
2197 * all requested space */
2198 start = block;
2199 end = block + num;
2200 } else if (le32_to_cpu(ex->ee_block) > block) {
2201 /* need to allocate space before found extent */
2202 start = block;
2203 end = le32_to_cpu(ex->ee_block);
2204 if (block + num < end)
2205 end = block + num;
2206 } else if (block >= le32_to_cpu(ex->ee_block)
2207 + ext4_ext_get_actual_len(ex)) {
2208 /* need to allocate space after found extent */
2209 start = block;
2210 end = block + num;
2211 if (end >= next)
2212 end = next;
2213 } else if (block >= le32_to_cpu(ex->ee_block)) {
2214 /*
2215 * some part of requested space is covered
2216 * by found extent
2217 */
2218 start = block;
2219 end = le32_to_cpu(ex->ee_block)
2220 + ext4_ext_get_actual_len(ex);
2221 if (block + num < end)
2222 end = block + num;
2223 exists = 1;
2224 } else {
2225 BUG();
2226 }
2227 BUG_ON(end <= start);
2228
2229 if (!exists) {
69eb33dc
ZL
2230 es.es_lblk = start;
2231 es.es_len = end - start;
2232 es.es_pblk = 0;
6873fa0d 2233 } else {
69eb33dc
ZL
2234 es.es_lblk = le32_to_cpu(ex->ee_block);
2235 es.es_len = ext4_ext_get_actual_len(ex);
2236 es.es_pblk = ext4_ext_pblock(ex);
556615dc 2237 if (ext4_ext_is_unwritten(ex))
91dd8c11 2238 flags |= FIEMAP_EXTENT_UNWRITTEN;
6873fa0d
ES
2239 }
2240
91dd8c11 2241 /*
69eb33dc
ZL
2242 * Find delayed extent and update es accordingly. We call
2243 * it even in !exists case to find out whether es is the
91dd8c11
LC
2244 * last existing extent or not.
2245 */
69eb33dc 2246 next_del = ext4_find_delayed_extent(inode, &es);
91dd8c11
LC
2247 if (!exists && next_del) {
2248 exists = 1;
72dac95d
JL
2249 flags |= (FIEMAP_EXTENT_DELALLOC |
2250 FIEMAP_EXTENT_UNKNOWN);
91dd8c11
LC
2251 }
2252 up_read(&EXT4_I(inode)->i_data_sem);
2253
69eb33dc
ZL
2254 if (unlikely(es.es_len == 0)) {
2255 EXT4_ERROR_INODE(inode, "es.es_len == 0");
6a797d27 2256 err = -EFSCORRUPTED;
273df556
FM
2257 break;
2258 }
6873fa0d 2259
f7fec032
ZL
2260 /*
2261 * This is possible iff next == next_del == EXT_MAX_BLOCKS.
2262 * we need to check next == EXT_MAX_BLOCKS because it is
2263 * possible that an extent is with unwritten and delayed
2264 * status due to when an extent is delayed allocated and
2265 * is allocated by fallocate status tree will track both of
2266 * them in a extent.
2267 *
2268 * So we could return a unwritten and delayed extent, and
2269 * its block is equal to 'next'.
2270 */
2271 if (next == next_del && next == EXT_MAX_BLOCKS) {
91dd8c11
LC
2272 flags |= FIEMAP_EXTENT_LAST;
2273 if (unlikely(next_del != EXT_MAX_BLOCKS ||
2274 next != EXT_MAX_BLOCKS)) {
2275 EXT4_ERROR_INODE(inode,
2276 "next extent == %u, next "
2277 "delalloc extent = %u",
2278 next, next_del);
6a797d27 2279 err = -EFSCORRUPTED;
91dd8c11
LC
2280 break;
2281 }
6873fa0d
ES
2282 }
2283
91dd8c11
LC
2284 if (exists) {
2285 err = fiemap_fill_next_extent(fieinfo,
69eb33dc
ZL
2286 (__u64)es.es_lblk << blksize_bits,
2287 (__u64)es.es_pblk << blksize_bits,
2288 (__u64)es.es_len << blksize_bits,
91dd8c11
LC
2289 flags);
2290 if (err < 0)
2291 break;
2292 if (err == 1) {
2293 err = 0;
2294 break;
2295 }
6873fa0d
ES
2296 }
2297
69eb33dc 2298 block = es.es_lblk + es.es_len;
6873fa0d
ES
2299 }
2300
b7ea89ad
TT
2301 ext4_ext_drop_refs(path);
2302 kfree(path);
6873fa0d
ES
2303 return err;
2304}
2305
a86c6181 2306/*
140a5250
JK
2307 * ext4_ext_determine_hole - determine hole around given block
2308 * @inode: inode we lookup in
2309 * @path: path in extent tree to @lblk
2310 * @lblk: pointer to logical block around which we want to determine hole
2311 *
2312 * Determine hole length (and start if easily possible) around given logical
2313 * block. We don't try too hard to find the beginning of the hole but @path
2314 * actually points to extent before @lblk, we provide it.
2315 *
2316 * The function returns the length of a hole starting at @lblk. We update @lblk
2317 * to the beginning of the hole if we managed to find it.
a86c6181 2318 */
140a5250
JK
2319static ext4_lblk_t ext4_ext_determine_hole(struct inode *inode,
2320 struct ext4_ext_path *path,
2321 ext4_lblk_t *lblk)
a86c6181
AT
2322{
2323 int depth = ext_depth(inode);
a86c6181 2324 struct ext4_extent *ex;
140a5250 2325 ext4_lblk_t len;
a86c6181
AT
2326
2327 ex = path[depth].p_ext;
2328 if (ex == NULL) {
2f8e0a7c 2329 /* there is no extent yet, so gap is [0;-] */
140a5250 2330 *lblk = 0;
2f8e0a7c 2331 len = EXT_MAX_BLOCKS;
140a5250
JK
2332 } else if (*lblk < le32_to_cpu(ex->ee_block)) {
2333 len = le32_to_cpu(ex->ee_block) - *lblk;
2334 } else if (*lblk >= le32_to_cpu(ex->ee_block)
a2df2a63 2335 + ext4_ext_get_actual_len(ex)) {
725d26d3 2336 ext4_lblk_t next;
725d26d3 2337
140a5250 2338 *lblk = le32_to_cpu(ex->ee_block) + ext4_ext_get_actual_len(ex);
725d26d3 2339 next = ext4_ext_next_allocated_block(path);
140a5250
JK
2340 BUG_ON(next == *lblk);
2341 len = next - *lblk;
a86c6181 2342 } else {
a86c6181
AT
2343 BUG();
2344 }
140a5250
JK
2345 return len;
2346}
a86c6181 2347
140a5250
JK
2348/*
2349 * ext4_ext_put_gap_in_cache:
2350 * calculate boundaries of the gap that the requested block fits into
2351 * and cache this gap
2352 */
2353static void
2354ext4_ext_put_gap_in_cache(struct inode *inode, ext4_lblk_t hole_start,
2355 ext4_lblk_t hole_len)
2356{
2357 struct extent_status es;
2358
2359 ext4_es_find_delayed_extent_range(inode, hole_start,
2360 hole_start + hole_len - 1, &es);
2f8e0a7c
ZL
2361 if (es.es_len) {
2362 /* There's delayed extent containing lblock? */
140a5250 2363 if (es.es_lblk <= hole_start)
2f8e0a7c 2364 return;
140a5250 2365 hole_len = min(es.es_lblk - hole_start, hole_len);
2f8e0a7c 2366 }
140a5250
JK
2367 ext_debug(" -> %u:%u\n", hole_start, hole_len);
2368 ext4_es_insert_extent(inode, hole_start, hole_len, ~0,
2369 EXTENT_STATUS_HOLE);
a86c6181
AT
2370}
2371
2372/*
d0d856e8
RD
2373 * ext4_ext_rm_idx:
2374 * removes index from the index block.
a86c6181 2375 */
1d03ec98 2376static int ext4_ext_rm_idx(handle_t *handle, struct inode *inode,
c36575e6 2377 struct ext4_ext_path *path, int depth)
a86c6181 2378{
a86c6181 2379 int err;
f65e6fba 2380 ext4_fsblk_t leaf;
a86c6181
AT
2381
2382 /* free index block */
c36575e6
FL
2383 depth--;
2384 path = path + depth;
bf89d16f 2385 leaf = ext4_idx_pblock(path->p_idx);
273df556
FM
2386 if (unlikely(path->p_hdr->eh_entries == 0)) {
2387 EXT4_ERROR_INODE(inode, "path->p_hdr->eh_entries == 0");
6a797d27 2388 return -EFSCORRUPTED;
273df556 2389 }
7e028976
AM
2390 err = ext4_ext_get_access(handle, inode, path);
2391 if (err)
a86c6181 2392 return err;
0e1147b0
RD
2393
2394 if (path->p_idx != EXT_LAST_INDEX(path->p_hdr)) {
2395 int len = EXT_LAST_INDEX(path->p_hdr) - path->p_idx;
2396 len *= sizeof(struct ext4_extent_idx);
2397 memmove(path->p_idx, path->p_idx + 1, len);
2398 }
2399
e8546d06 2400 le16_add_cpu(&path->p_hdr->eh_entries, -1);
7e028976
AM
2401 err = ext4_ext_dirty(handle, inode, path);
2402 if (err)
a86c6181 2403 return err;
2ae02107 2404 ext_debug("index is empty, remove it, free block %llu\n", leaf);
d8990240
AK
2405 trace_ext4_ext_rm_idx(inode, leaf);
2406
7dc57615 2407 ext4_free_blocks(handle, inode, NULL, leaf, 1,
e6362609 2408 EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET);
c36575e6
FL
2409
2410 while (--depth >= 0) {
2411 if (path->p_idx != EXT_FIRST_INDEX(path->p_hdr))
2412 break;
2413 path--;
2414 err = ext4_ext_get_access(handle, inode, path);
2415 if (err)
2416 break;
2417 path->p_idx->ei_block = (path+1)->p_idx->ei_block;
2418 err = ext4_ext_dirty(handle, inode, path);
2419 if (err)
2420 break;
2421 }
a86c6181
AT
2422 return err;
2423}
2424
2425/*
ee12b630
MC
2426 * ext4_ext_calc_credits_for_single_extent:
2427 * This routine returns max. credits that needed to insert an extent
2428 * to the extent tree.
2429 * When pass the actual path, the caller should calculate credits
2430 * under i_data_sem.
a86c6181 2431 */
525f4ed8 2432int ext4_ext_calc_credits_for_single_extent(struct inode *inode, int nrblocks,
a86c6181
AT
2433 struct ext4_ext_path *path)
2434{
a86c6181 2435 if (path) {
ee12b630 2436 int depth = ext_depth(inode);
f3bd1f3f 2437 int ret = 0;
ee12b630 2438
a86c6181 2439 /* probably there is space in leaf? */
a86c6181 2440 if (le16_to_cpu(path[depth].p_hdr->eh_entries)
ee12b630 2441 < le16_to_cpu(path[depth].p_hdr->eh_max)) {
a86c6181 2442
ee12b630
MC
2443 /*
2444 * There are some space in the leaf tree, no
2445 * need to account for leaf block credit
2446 *
2447 * bitmaps and block group descriptor blocks
df3ab170 2448 * and other metadata blocks still need to be
ee12b630
MC
2449 * accounted.
2450 */
525f4ed8 2451 /* 1 bitmap, 1 block group descriptor */
ee12b630 2452 ret = 2 + EXT4_META_TRANS_BLOCKS(inode->i_sb);
5887e98b 2453 return ret;
ee12b630
MC
2454 }
2455 }
a86c6181 2456
525f4ed8 2457 return ext4_chunk_trans_blocks(inode, nrblocks);
ee12b630 2458}
a86c6181 2459
ee12b630 2460/*
fffb2739 2461 * How many index/leaf blocks need to change/allocate to add @extents extents?
ee12b630 2462 *
fffb2739
JK
2463 * If we add a single extent, then in the worse case, each tree level
2464 * index/leaf need to be changed in case of the tree split.
ee12b630 2465 *
fffb2739
JK
2466 * If more extents are inserted, they could cause the whole tree split more
2467 * than once, but this is really rare.
ee12b630 2468 */
fffb2739 2469int ext4_ext_index_trans_blocks(struct inode *inode, int extents)
ee12b630
MC
2470{
2471 int index;
f19d5870
TM
2472 int depth;
2473
2474 /* If we are converting the inline data, only one is needed here. */
2475 if (ext4_has_inline_data(inode))
2476 return 1;
2477
2478 depth = ext_depth(inode);
a86c6181 2479
fffb2739 2480 if (extents <= 1)
ee12b630
MC
2481 index = depth * 2;
2482 else
2483 index = depth * 3;
a86c6181 2484
ee12b630 2485 return index;
a86c6181
AT
2486}
2487
981250ca
TT
2488static inline int get_default_free_blocks_flags(struct inode *inode)
2489{
2490 if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode))
2491 return EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET;
2492 else if (ext4_should_journal_data(inode))
2493 return EXT4_FREE_BLOCKS_FORGET;
2494 return 0;
2495}
2496
a86c6181 2497static int ext4_remove_blocks(handle_t *handle, struct inode *inode,
0aa06000 2498 struct ext4_extent *ex,
d23142c6 2499 long long *partial_cluster,
0aa06000 2500 ext4_lblk_t from, ext4_lblk_t to)
a86c6181 2501{
0aa06000 2502 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
345ee947 2503 unsigned short ee_len = ext4_ext_get_actual_len(ex);
0aa06000 2504 ext4_fsblk_t pblk;
981250ca 2505 int flags = get_default_free_blocks_flags(inode);
18888cf0 2506
0aa06000
TT
2507 /*
2508 * For bigalloc file systems, we never free a partial cluster
2509 * at the beginning of the extent. Instead, we make a note
2510 * that we tried freeing the cluster, and check to see if we
2511 * need to free it on a subsequent call to ext4_remove_blocks,
345ee947 2512 * or at the end of ext4_ext_rm_leaf or ext4_ext_remove_space.
0aa06000
TT
2513 */
2514 flags |= EXT4_FREE_BLOCKS_NOFREE_FIRST_CLUSTER;
2515
d8990240 2516 trace_ext4_remove_blocks(inode, ex, from, to, *partial_cluster);
0aa06000
TT
2517 /*
2518 * If we have a partial cluster, and it's different from the
2519 * cluster of the last block, we need to explicitly free the
2520 * partial cluster here.
2521 */
2522 pblk = ext4_ext_pblock(ex) + ee_len - 1;
345ee947
EW
2523 if (*partial_cluster > 0 &&
2524 *partial_cluster != (long long) EXT4_B2C(sbi, pblk)) {
0aa06000
TT
2525 ext4_free_blocks(handle, inode, NULL,
2526 EXT4_C2B(sbi, *partial_cluster),
2527 sbi->s_cluster_ratio, flags);
2528 *partial_cluster = 0;
2529 }
2530
a86c6181
AT
2531#ifdef EXTENTS_STATS
2532 {
2533 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
a86c6181
AT
2534 spin_lock(&sbi->s_ext_stats_lock);
2535 sbi->s_ext_blocks += ee_len;
2536 sbi->s_ext_extents++;
2537 if (ee_len < sbi->s_ext_min)
2538 sbi->s_ext_min = ee_len;
2539 if (ee_len > sbi->s_ext_max)
2540 sbi->s_ext_max = ee_len;
2541 if (ext_depth(inode) > sbi->s_depth_max)
2542 sbi->s_depth_max = ext_depth(inode);
2543 spin_unlock(&sbi->s_ext_stats_lock);
2544 }
2545#endif
2546 if (from >= le32_to_cpu(ex->ee_block)
a2df2a63 2547 && to == le32_to_cpu(ex->ee_block) + ee_len - 1) {
a86c6181 2548 /* tail removal */
725d26d3 2549 ext4_lblk_t num;
345ee947 2550 long long first_cluster;
725d26d3 2551
a2df2a63 2552 num = le32_to_cpu(ex->ee_block) + ee_len - from;
0aa06000 2553 pblk = ext4_ext_pblock(ex) + ee_len - num;
d23142c6
LC
2554 /*
2555 * Usually we want to free partial cluster at the end of the
2556 * extent, except for the situation when the cluster is still
2557 * used by any other extent (partial_cluster is negative).
2558 */
2559 if (*partial_cluster < 0 &&
345ee947 2560 *partial_cluster == -(long long) EXT4_B2C(sbi, pblk+num-1))
d23142c6
LC
2561 flags |= EXT4_FREE_BLOCKS_NOFREE_LAST_CLUSTER;
2562
2563 ext_debug("free last %u blocks starting %llu partial %lld\n",
2564 num, pblk, *partial_cluster);
0aa06000
TT
2565 ext4_free_blocks(handle, inode, NULL, pblk, num, flags);
2566 /*
2567 * If the block range to be freed didn't start at the
2568 * beginning of a cluster, and we removed the entire
d23142c6
LC
2569 * extent and the cluster is not used by any other extent,
2570 * save the partial cluster here, since we might need to
345ee947
EW
2571 * delete if we determine that the truncate or punch hole
2572 * operation has removed all of the blocks in the cluster.
2573 * If that cluster is used by another extent, preserve its
2574 * negative value so it isn't freed later on.
d23142c6 2575 *
345ee947
EW
2576 * If the whole extent wasn't freed, we've reached the
2577 * start of the truncated/punched region and have finished
2578 * removing blocks. If there's a partial cluster here it's
2579 * shared with the remainder of the extent and is no longer
2580 * a candidate for removal.
0aa06000 2581 */
345ee947
EW
2582 if (EXT4_PBLK_COFF(sbi, pblk) && ee_len == num) {
2583 first_cluster = (long long) EXT4_B2C(sbi, pblk);
2584 if (first_cluster != -*partial_cluster)
2585 *partial_cluster = first_cluster;
2586 } else {
0aa06000 2587 *partial_cluster = 0;
345ee947 2588 }
78fb9cdf
LC
2589 } else
2590 ext4_error(sbi->s_sb, "strange request: removal(2) "
2591 "%u-%u from %u:%u\n",
2592 from, to, le32_to_cpu(ex->ee_block), ee_len);
a86c6181
AT
2593 return 0;
2594}
2595
d583fb87
AH
2596
2597/*
2598 * ext4_ext_rm_leaf() Removes the extents associated with the
5bf43760
EW
2599 * blocks appearing between "start" and "end". Both "start"
2600 * and "end" must appear in the same extent or EIO is returned.
d583fb87
AH
2601 *
2602 * @handle: The journal handle
2603 * @inode: The files inode
2604 * @path: The path to the leaf
d23142c6 2605 * @partial_cluster: The cluster which we'll have to free if all extents
5bf43760
EW
2606 * has been released from it. However, if this value is
2607 * negative, it's a cluster just to the right of the
2608 * punched region and it must not be freed.
d583fb87
AH
2609 * @start: The first block to remove
2610 * @end: The last block to remove
2611 */
a86c6181
AT
2612static int
2613ext4_ext_rm_leaf(handle_t *handle, struct inode *inode,
d23142c6
LC
2614 struct ext4_ext_path *path,
2615 long long *partial_cluster,
0aa06000 2616 ext4_lblk_t start, ext4_lblk_t end)
a86c6181 2617{
0aa06000 2618 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
a86c6181
AT
2619 int err = 0, correct_index = 0;
2620 int depth = ext_depth(inode), credits;
2621 struct ext4_extent_header *eh;
750c9c47 2622 ext4_lblk_t a, b;
725d26d3
AK
2623 unsigned num;
2624 ext4_lblk_t ex_ee_block;
a86c6181 2625 unsigned short ex_ee_len;
556615dc 2626 unsigned unwritten = 0;
a86c6181 2627 struct ext4_extent *ex;
d23142c6 2628 ext4_fsblk_t pblk;
a86c6181 2629
c29c0ae7 2630 /* the header must be checked already in ext4_ext_remove_space() */
5f95d21f 2631 ext_debug("truncate since %u in leaf to %u\n", start, end);
a86c6181
AT
2632 if (!path[depth].p_hdr)
2633 path[depth].p_hdr = ext_block_hdr(path[depth].p_bh);
2634 eh = path[depth].p_hdr;
273df556
FM
2635 if (unlikely(path[depth].p_hdr == NULL)) {
2636 EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
6a797d27 2637 return -EFSCORRUPTED;
273df556 2638 }
a86c6181 2639 /* find where to start removing */
6ae06ff5
AS
2640 ex = path[depth].p_ext;
2641 if (!ex)
2642 ex = EXT_LAST_EXTENT(eh);
a86c6181
AT
2643
2644 ex_ee_block = le32_to_cpu(ex->ee_block);
a2df2a63 2645 ex_ee_len = ext4_ext_get_actual_len(ex);
a86c6181 2646
d8990240
AK
2647 trace_ext4_ext_rm_leaf(inode, start, ex, *partial_cluster);
2648
a86c6181
AT
2649 while (ex >= EXT_FIRST_EXTENT(eh) &&
2650 ex_ee_block + ex_ee_len > start) {
a41f2071 2651
556615dc
LC
2652 if (ext4_ext_is_unwritten(ex))
2653 unwritten = 1;
a41f2071 2654 else
556615dc 2655 unwritten = 0;
a41f2071 2656
553f9008 2657 ext_debug("remove ext %u:[%d]%d\n", ex_ee_block,
556615dc 2658 unwritten, ex_ee_len);
a86c6181
AT
2659 path[depth].p_ext = ex;
2660
2661 a = ex_ee_block > start ? ex_ee_block : start;
d583fb87
AH
2662 b = ex_ee_block+ex_ee_len - 1 < end ?
2663 ex_ee_block+ex_ee_len - 1 : end;
a86c6181
AT
2664
2665 ext_debug(" border %u:%u\n", a, b);
2666
d583fb87 2667 /* If this extent is beyond the end of the hole, skip it */
5f95d21f 2668 if (end < ex_ee_block) {
d23142c6
LC
2669 /*
2670 * We're going to skip this extent and move to another,
f4226d9e
EW
2671 * so note that its first cluster is in use to avoid
2672 * freeing it when removing blocks. Eventually, the
2673 * right edge of the truncated/punched region will
2674 * be just to the left.
d23142c6 2675 */
f4226d9e
EW
2676 if (sbi->s_cluster_ratio > 1) {
2677 pblk = ext4_ext_pblock(ex);
d23142c6 2678 *partial_cluster =
f4226d9e
EW
2679 -(long long) EXT4_B2C(sbi, pblk);
2680 }
d583fb87
AH
2681 ex--;
2682 ex_ee_block = le32_to_cpu(ex->ee_block);
2683 ex_ee_len = ext4_ext_get_actual_len(ex);
2684 continue;
750c9c47 2685 } else if (b != ex_ee_block + ex_ee_len - 1) {
dc1841d6
LC
2686 EXT4_ERROR_INODE(inode,
2687 "can not handle truncate %u:%u "
2688 "on extent %u:%u",
2689 start, end, ex_ee_block,
2690 ex_ee_block + ex_ee_len - 1);
6a797d27 2691 err = -EFSCORRUPTED;
750c9c47 2692 goto out;
a86c6181
AT
2693 } else if (a != ex_ee_block) {
2694 /* remove tail of the extent */
750c9c47 2695 num = a - ex_ee_block;
a86c6181
AT
2696 } else {
2697 /* remove whole extent: excellent! */
a86c6181 2698 num = 0;
a86c6181 2699 }
34071da7
TT
2700 /*
2701 * 3 for leaf, sb, and inode plus 2 (bmap and group
2702 * descriptor) for each block group; assume two block
2703 * groups plus ex_ee_len/blocks_per_block_group for
2704 * the worst case
2705 */
2706 credits = 7 + 2*(ex_ee_len/EXT4_BLOCKS_PER_GROUP(inode->i_sb));
a86c6181
AT
2707 if (ex == EXT_FIRST_EXTENT(eh)) {
2708 correct_index = 1;
2709 credits += (ext_depth(inode)) + 1;
2710 }
5aca07eb 2711 credits += EXT4_MAXQUOTAS_TRANS_BLOCKS(inode->i_sb);
a86c6181 2712
487caeef 2713 err = ext4_ext_truncate_extend_restart(handle, inode, credits);
9102e4fa 2714 if (err)
a86c6181 2715 goto out;
a86c6181
AT
2716
2717 err = ext4_ext_get_access(handle, inode, path + depth);
2718 if (err)
2719 goto out;
2720
0aa06000
TT
2721 err = ext4_remove_blocks(handle, inode, ex, partial_cluster,
2722 a, b);
a86c6181
AT
2723 if (err)
2724 goto out;
2725
750c9c47 2726 if (num == 0)
d0d856e8 2727 /* this extent is removed; mark slot entirely unused */
f65e6fba 2728 ext4_ext_store_pblock(ex, 0);
a86c6181 2729
a86c6181 2730 ex->ee_len = cpu_to_le16(num);
749269fa 2731 /*
556615dc 2732 * Do not mark unwritten if all the blocks in the
749269fa
AA
2733 * extent have been removed.
2734 */
556615dc
LC
2735 if (unwritten && num)
2736 ext4_ext_mark_unwritten(ex);
d583fb87
AH
2737 /*
2738 * If the extent was completely released,
2739 * we need to remove it from the leaf
2740 */
2741 if (num == 0) {
f17722f9 2742 if (end != EXT_MAX_BLOCKS - 1) {
d583fb87
AH
2743 /*
2744 * For hole punching, we need to scoot all the
2745 * extents up when an extent is removed so that
2746 * we dont have blank extents in the middle
2747 */
2748 memmove(ex, ex+1, (EXT_LAST_EXTENT(eh) - ex) *
2749 sizeof(struct ext4_extent));
2750
2751 /* Now get rid of the one at the end */
2752 memset(EXT_LAST_EXTENT(eh), 0,
2753 sizeof(struct ext4_extent));
2754 }
2755 le16_add_cpu(&eh->eh_entries, -1);
5bf43760 2756 }
d583fb87 2757
750c9c47
DM
2758 err = ext4_ext_dirty(handle, inode, path + depth);
2759 if (err)
2760 goto out;
2761
bf52c6f7 2762 ext_debug("new extent: %u:%u:%llu\n", ex_ee_block, num,
bf89d16f 2763 ext4_ext_pblock(ex));
a86c6181
AT
2764 ex--;
2765 ex_ee_block = le32_to_cpu(ex->ee_block);
a2df2a63 2766 ex_ee_len = ext4_ext_get_actual_len(ex);
a86c6181
AT
2767 }
2768
2769 if (correct_index && eh->eh_entries)
2770 err = ext4_ext_correct_indexes(handle, inode, path);
2771
0aa06000 2772 /*
ad6599ab
EW
2773 * If there's a partial cluster and at least one extent remains in
2774 * the leaf, free the partial cluster if it isn't shared with the
5bf43760
EW
2775 * current extent. If it is shared with the current extent
2776 * we zero partial_cluster because we've reached the start of the
2777 * truncated/punched region and we're done removing blocks.
0aa06000 2778 */
5bf43760
EW
2779 if (*partial_cluster > 0 && ex >= EXT_FIRST_EXTENT(eh)) {
2780 pblk = ext4_ext_pblock(ex) + ex_ee_len - 1;
2781 if (*partial_cluster != (long long) EXT4_B2C(sbi, pblk)) {
2782 ext4_free_blocks(handle, inode, NULL,
2783 EXT4_C2B(sbi, *partial_cluster),
2784 sbi->s_cluster_ratio,
2785 get_default_free_blocks_flags(inode));
2786 }
0aa06000
TT
2787 *partial_cluster = 0;
2788 }
2789
a86c6181
AT
2790 /* if this leaf is free, then we should
2791 * remove it from index block above */
2792 if (err == 0 && eh->eh_entries == 0 && path[depth].p_bh != NULL)
c36575e6 2793 err = ext4_ext_rm_idx(handle, inode, path, depth);
a86c6181
AT
2794
2795out:
2796 return err;
2797}
2798
2799/*
d0d856e8
RD
2800 * ext4_ext_more_to_rm:
2801 * returns 1 if current index has to be freed (even partial)
a86c6181 2802 */
09b88252 2803static int
a86c6181
AT
2804ext4_ext_more_to_rm(struct ext4_ext_path *path)
2805{
2806 BUG_ON(path->p_idx == NULL);
2807
2808 if (path->p_idx < EXT_FIRST_INDEX(path->p_hdr))
2809 return 0;
2810
2811 /*
d0d856e8 2812 * if truncate on deeper level happened, it wasn't partial,
a86c6181
AT
2813 * so we have to consider current index for truncation
2814 */
2815 if (le16_to_cpu(path->p_hdr->eh_entries) == path->p_block)
2816 return 0;
2817 return 1;
2818}
2819
26a4c0c6
TT
2820int ext4_ext_remove_space(struct inode *inode, ext4_lblk_t start,
2821 ext4_lblk_t end)
a86c6181 2822{
f4226d9e 2823 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
a86c6181 2824 int depth = ext_depth(inode);
968dee77 2825 struct ext4_ext_path *path = NULL;
d23142c6 2826 long long partial_cluster = 0;
a86c6181 2827 handle_t *handle;
6f2080e6 2828 int i = 0, err = 0;
a86c6181 2829
5f95d21f 2830 ext_debug("truncate since %u to %u\n", start, end);
a86c6181
AT
2831
2832 /* probably first extent we're gonna free will be last in block */
9924a92a 2833 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, depth + 1);
a86c6181
AT
2834 if (IS_ERR(handle))
2835 return PTR_ERR(handle);
2836
0617b83f 2837again:
61801325 2838 trace_ext4_ext_remove_space(inode, start, end, depth);
d8990240 2839
5f95d21f
LC
2840 /*
2841 * Check if we are removing extents inside the extent tree. If that
2842 * is the case, we are going to punch a hole inside the extent tree
2843 * so we have to check whether we need to split the extent covering
2844 * the last block to remove so we can easily remove the part of it
2845 * in ext4_ext_rm_leaf().
2846 */
2847 if (end < EXT_MAX_BLOCKS - 1) {
2848 struct ext4_extent *ex;
f4226d9e
EW
2849 ext4_lblk_t ee_block, ex_end, lblk;
2850 ext4_fsblk_t pblk;
5f95d21f 2851
f4226d9e 2852 /* find extent for or closest extent to this block */
ed8a1a76 2853 path = ext4_find_extent(inode, end, NULL, EXT4_EX_NOCACHE);
5f95d21f
LC
2854 if (IS_ERR(path)) {
2855 ext4_journal_stop(handle);
2856 return PTR_ERR(path);
2857 }
2858 depth = ext_depth(inode);
6f2080e6 2859 /* Leaf not may not exist only if inode has no blocks at all */
5f95d21f 2860 ex = path[depth].p_ext;
968dee77 2861 if (!ex) {
6f2080e6
DM
2862 if (depth) {
2863 EXT4_ERROR_INODE(inode,
2864 "path[%d].p_hdr == NULL",
2865 depth);
6a797d27 2866 err = -EFSCORRUPTED;
6f2080e6
DM
2867 }
2868 goto out;
968dee77 2869 }
5f95d21f
LC
2870
2871 ee_block = le32_to_cpu(ex->ee_block);
f4226d9e 2872 ex_end = ee_block + ext4_ext_get_actual_len(ex) - 1;
5f95d21f
LC
2873
2874 /*
2875 * See if the last block is inside the extent, if so split
2876 * the extent at 'end' block so we can easily remove the
2877 * tail of the first part of the split extent in
2878 * ext4_ext_rm_leaf().
2879 */
f4226d9e
EW
2880 if (end >= ee_block && end < ex_end) {
2881
2882 /*
2883 * If we're going to split the extent, note that
2884 * the cluster containing the block after 'end' is
2885 * in use to avoid freeing it when removing blocks.
2886 */
2887 if (sbi->s_cluster_ratio > 1) {
2888 pblk = ext4_ext_pblock(ex) + end - ee_block + 2;
2889 partial_cluster =
2890 -(long long) EXT4_B2C(sbi, pblk);
2891 }
2892
5f95d21f
LC
2893 /*
2894 * Split the extent in two so that 'end' is the last
27dd4385
LC
2895 * block in the first new extent. Also we should not
2896 * fail removing space due to ENOSPC so try to use
2897 * reserved block if that happens.
5f95d21f 2898 */
dfe50809 2899 err = ext4_force_split_extent_at(handle, inode, &path,
fcf6b1b7 2900 end + 1, 1);
5f95d21f
LC
2901 if (err < 0)
2902 goto out;
f4226d9e
EW
2903
2904 } else if (sbi->s_cluster_ratio > 1 && end >= ex_end) {
2905 /*
2906 * If there's an extent to the right its first cluster
2907 * contains the immediate right boundary of the
2908 * truncated/punched region. Set partial_cluster to
2909 * its negative value so it won't be freed if shared
2910 * with the current extent. The end < ee_block case
2911 * is handled in ext4_ext_rm_leaf().
2912 */
2913 lblk = ex_end + 1;
2914 err = ext4_ext_search_right(inode, path, &lblk, &pblk,
2915 &ex);
2916 if (err)
2917 goto out;
2918 if (pblk)
2919 partial_cluster =
2920 -(long long) EXT4_B2C(sbi, pblk);
5f95d21f 2921 }
5f95d21f 2922 }
a86c6181 2923 /*
d0d856e8
RD
2924 * We start scanning from right side, freeing all the blocks
2925 * after i_size and walking into the tree depth-wise.
a86c6181 2926 */
0617b83f 2927 depth = ext_depth(inode);
968dee77
AS
2928 if (path) {
2929 int k = i = depth;
2930 while (--k > 0)
2931 path[k].p_block =
2932 le16_to_cpu(path[k].p_hdr->eh_entries)+1;
2933 } else {
2934 path = kzalloc(sizeof(struct ext4_ext_path) * (depth + 1),
2935 GFP_NOFS);
2936 if (path == NULL) {
2937 ext4_journal_stop(handle);
2938 return -ENOMEM;
2939 }
10809df8 2940 path[0].p_maxdepth = path[0].p_depth = depth;
968dee77 2941 path[0].p_hdr = ext_inode_hdr(inode);
89a4e48f 2942 i = 0;
5f95d21f 2943
c349179b 2944 if (ext4_ext_check(inode, path[0].p_hdr, depth, 0)) {
6a797d27 2945 err = -EFSCORRUPTED;
968dee77
AS
2946 goto out;
2947 }
a86c6181 2948 }
968dee77 2949 err = 0;
a86c6181
AT
2950
2951 while (i >= 0 && err == 0) {
2952 if (i == depth) {
2953 /* this is leaf block */
d583fb87 2954 err = ext4_ext_rm_leaf(handle, inode, path,
0aa06000 2955 &partial_cluster, start,
5f95d21f 2956 end);
d0d856e8 2957 /* root level has p_bh == NULL, brelse() eats this */
a86c6181
AT
2958 brelse(path[i].p_bh);
2959 path[i].p_bh = NULL;
2960 i--;
2961 continue;
2962 }
2963
2964 /* this is index block */
2965 if (!path[i].p_hdr) {
2966 ext_debug("initialize header\n");
2967 path[i].p_hdr = ext_block_hdr(path[i].p_bh);
a86c6181
AT
2968 }
2969
a86c6181 2970 if (!path[i].p_idx) {
d0d856e8 2971 /* this level hasn't been touched yet */
a86c6181
AT
2972 path[i].p_idx = EXT_LAST_INDEX(path[i].p_hdr);
2973 path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries)+1;
2974 ext_debug("init index ptr: hdr 0x%p, num %d\n",
2975 path[i].p_hdr,
2976 le16_to_cpu(path[i].p_hdr->eh_entries));
2977 } else {
d0d856e8 2978 /* we were already here, see at next index */
a86c6181
AT
2979 path[i].p_idx--;
2980 }
2981
2982 ext_debug("level %d - index, first 0x%p, cur 0x%p\n",
2983 i, EXT_FIRST_INDEX(path[i].p_hdr),
2984 path[i].p_idx);
2985 if (ext4_ext_more_to_rm(path + i)) {
c29c0ae7 2986 struct buffer_head *bh;
a86c6181 2987 /* go to the next level */
2ae02107 2988 ext_debug("move to level %d (block %llu)\n",
bf89d16f 2989 i + 1, ext4_idx_pblock(path[i].p_idx));
a86c6181 2990 memset(path + i + 1, 0, sizeof(*path));
7d7ea89e 2991 bh = read_extent_tree_block(inode,
107a7bd3
TT
2992 ext4_idx_pblock(path[i].p_idx), depth - i - 1,
2993 EXT4_EX_NOCACHE);
7d7ea89e 2994 if (IS_ERR(bh)) {
a86c6181 2995 /* should we reset i_size? */
7d7ea89e 2996 err = PTR_ERR(bh);
a86c6181
AT
2997 break;
2998 }
76828c88
TT
2999 /* Yield here to deal with large extent trees.
3000 * Should be a no-op if we did IO above. */
3001 cond_resched();
c29c0ae7 3002 if (WARN_ON(i + 1 > depth)) {
6a797d27 3003 err = -EFSCORRUPTED;
c29c0ae7
AT
3004 break;
3005 }
3006 path[i + 1].p_bh = bh;
a86c6181 3007
d0d856e8
RD
3008 /* save actual number of indexes since this
3009 * number is changed at the next iteration */
a86c6181
AT
3010 path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries);
3011 i++;
3012 } else {
d0d856e8 3013 /* we finished processing this index, go up */
a86c6181 3014 if (path[i].p_hdr->eh_entries == 0 && i > 0) {
d0d856e8 3015 /* index is empty, remove it;
a86c6181
AT
3016 * handle must be already prepared by the
3017 * truncatei_leaf() */
c36575e6 3018 err = ext4_ext_rm_idx(handle, inode, path, i);
a86c6181 3019 }
d0d856e8 3020 /* root level has p_bh == NULL, brelse() eats this */
a86c6181
AT
3021 brelse(path[i].p_bh);
3022 path[i].p_bh = NULL;
3023 i--;
3024 ext_debug("return to level %d\n", i);
3025 }
3026 }
3027
61801325
LC
3028 trace_ext4_ext_remove_space_done(inode, start, end, depth,
3029 partial_cluster, path->p_hdr->eh_entries);
d8990240 3030
0756b908
EW
3031 /*
3032 * If we still have something in the partial cluster and we have removed
7b415bf6 3033 * even the first extent, then we should free the blocks in the partial
0756b908
EW
3034 * cluster as well. (This code will only run when there are no leaves
3035 * to the immediate left of the truncated/punched region.)
3036 */
3037 if (partial_cluster > 0 && err == 0) {
3038 /* don't zero partial_cluster since it's not used afterwards */
7b415bf6 3039 ext4_free_blocks(handle, inode, NULL,
f4226d9e 3040 EXT4_C2B(sbi, partial_cluster),
0756b908
EW
3041 sbi->s_cluster_ratio,
3042 get_default_free_blocks_flags(inode));
7b415bf6
AK
3043 }
3044
a86c6181
AT
3045 /* TODO: flexible tree reduction should be here */
3046 if (path->p_hdr->eh_entries == 0) {
3047 /*
d0d856e8
RD
3048 * truncate to zero freed all the tree,
3049 * so we need to correct eh_depth
a86c6181
AT
3050 */
3051 err = ext4_ext_get_access(handle, inode, path);
3052 if (err == 0) {
3053 ext_inode_hdr(inode)->eh_depth = 0;
3054 ext_inode_hdr(inode)->eh_max =
55ad63bf 3055 cpu_to_le16(ext4_ext_space_root(inode, 0));
a86c6181
AT
3056 err = ext4_ext_dirty(handle, inode, path);
3057 }
3058 }
3059out:
b7ea89ad
TT
3060 ext4_ext_drop_refs(path);
3061 kfree(path);
3062 path = NULL;
dfe50809
TT
3063 if (err == -EAGAIN)
3064 goto again;
a86c6181
AT
3065 ext4_journal_stop(handle);
3066
3067 return err;
3068}
3069
3070/*
3071 * called at mount time
3072 */
3073void ext4_ext_init(struct super_block *sb)
3074{
3075 /*
3076 * possible initialization would be here
3077 */
3078
e2b911c5 3079 if (ext4_has_feature_extents(sb)) {
90576c0b 3080#if defined(AGGRESSIVE_TEST) || defined(CHECK_BINSEARCH) || defined(EXTENTS_STATS)
92b97816 3081 printk(KERN_INFO "EXT4-fs: file extents enabled"
bbf2f9fb 3082#ifdef AGGRESSIVE_TEST
92b97816 3083 ", aggressive tests"
a86c6181
AT
3084#endif
3085#ifdef CHECK_BINSEARCH
92b97816 3086 ", check binsearch"
a86c6181
AT
3087#endif
3088#ifdef EXTENTS_STATS
92b97816 3089 ", stats"
a86c6181 3090#endif
92b97816 3091 "\n");
90576c0b 3092#endif
a86c6181
AT
3093#ifdef EXTENTS_STATS
3094 spin_lock_init(&EXT4_SB(sb)->s_ext_stats_lock);
3095 EXT4_SB(sb)->s_ext_min = 1 << 30;
3096 EXT4_SB(sb)->s_ext_max = 0;
3097#endif
3098 }
3099}
3100
3101/*
3102 * called at umount time
3103 */
3104void ext4_ext_release(struct super_block *sb)
3105{
e2b911c5 3106 if (!ext4_has_feature_extents(sb))
a86c6181
AT
3107 return;
3108
3109#ifdef EXTENTS_STATS
3110 if (EXT4_SB(sb)->s_ext_blocks && EXT4_SB(sb)->s_ext_extents) {
3111 struct ext4_sb_info *sbi = EXT4_SB(sb);
3112 printk(KERN_ERR "EXT4-fs: %lu blocks in %lu extents (%lu ave)\n",
3113 sbi->s_ext_blocks, sbi->s_ext_extents,
3114 sbi->s_ext_blocks / sbi->s_ext_extents);
3115 printk(KERN_ERR "EXT4-fs: extents: %lu min, %lu max, max depth %lu\n",
3116 sbi->s_ext_min, sbi->s_ext_max, sbi->s_depth_max);
3117 }
3118#endif
3119}
3120
d7b2a00c
ZL
3121static int ext4_zeroout_es(struct inode *inode, struct ext4_extent *ex)
3122{
3123 ext4_lblk_t ee_block;
3124 ext4_fsblk_t ee_pblock;
3125 unsigned int ee_len;
3126
3127 ee_block = le32_to_cpu(ex->ee_block);
3128 ee_len = ext4_ext_get_actual_len(ex);
3129 ee_pblock = ext4_ext_pblock(ex);
3130
3131 if (ee_len == 0)
3132 return 0;
3133
3134 return ext4_es_insert_extent(inode, ee_block, ee_len, ee_pblock,
3135 EXTENT_STATUS_WRITTEN);
3136}
3137
093a088b
AK
3138/* FIXME!! we need to try to merge to left or right after zero-out */
3139static int ext4_ext_zeroout(struct inode *inode, struct ext4_extent *ex)
3140{
2407518d
LC
3141 ext4_fsblk_t ee_pblock;
3142 unsigned int ee_len;
093a088b 3143
093a088b 3144 ee_len = ext4_ext_get_actual_len(ex);
bf89d16f 3145 ee_pblock = ext4_ext_pblock(ex);
53085fac
JK
3146 return ext4_issue_zeroout(inode, le32_to_cpu(ex->ee_block), ee_pblock,
3147 ee_len);
093a088b
AK
3148}
3149
47ea3bb5
YY
3150/*
3151 * ext4_split_extent_at() splits an extent at given block.
3152 *
3153 * @handle: the journal handle
3154 * @inode: the file inode
3155 * @path: the path to the extent
3156 * @split: the logical block where the extent is splitted.
3157 * @split_flags: indicates if the extent could be zeroout if split fails, and
556615dc 3158 * the states(init or unwritten) of new extents.
47ea3bb5
YY
3159 * @flags: flags used to insert new extent to extent tree.
3160 *
3161 *
3162 * Splits extent [a, b] into two extents [a, @split) and [@split, b], states
3163 * of which are deterimined by split_flag.
3164 *
3165 * There are two cases:
3166 * a> the extent are splitted into two extent.
3167 * b> split is not needed, and just mark the extent.
3168 *
3169 * return 0 on success.
3170 */
3171static int ext4_split_extent_at(handle_t *handle,
3172 struct inode *inode,
dfe50809 3173 struct ext4_ext_path **ppath,
47ea3bb5
YY
3174 ext4_lblk_t split,
3175 int split_flag,
3176 int flags)
3177{
dfe50809 3178 struct ext4_ext_path *path = *ppath;
47ea3bb5
YY
3179 ext4_fsblk_t newblock;
3180 ext4_lblk_t ee_block;
adb23551 3181 struct ext4_extent *ex, newex, orig_ex, zero_ex;
47ea3bb5
YY
3182 struct ext4_extent *ex2 = NULL;
3183 unsigned int ee_len, depth;
3184 int err = 0;
3185
dee1f973
DM
3186 BUG_ON((split_flag & (EXT4_EXT_DATA_VALID1 | EXT4_EXT_DATA_VALID2)) ==
3187 (EXT4_EXT_DATA_VALID1 | EXT4_EXT_DATA_VALID2));
3188
47ea3bb5
YY
3189 ext_debug("ext4_split_extents_at: inode %lu, logical"
3190 "block %llu\n", inode->i_ino, (unsigned long long)split);
3191
3192 ext4_ext_show_leaf(inode, path);
3193
3194 depth = ext_depth(inode);
3195 ex = path[depth].p_ext;
3196 ee_block = le32_to_cpu(ex->ee_block);
3197 ee_len = ext4_ext_get_actual_len(ex);
3198 newblock = split - ee_block + ext4_ext_pblock(ex);
3199
3200 BUG_ON(split < ee_block || split >= (ee_block + ee_len));
556615dc 3201 BUG_ON(!ext4_ext_is_unwritten(ex) &&
357b66fd 3202 split_flag & (EXT4_EXT_MAY_ZEROOUT |
556615dc
LC
3203 EXT4_EXT_MARK_UNWRIT1 |
3204 EXT4_EXT_MARK_UNWRIT2));
47ea3bb5
YY
3205
3206 err = ext4_ext_get_access(handle, inode, path + depth);
3207 if (err)
3208 goto out;
3209
3210 if (split == ee_block) {
3211 /*
3212 * case b: block @split is the block that the extent begins with
3213 * then we just change the state of the extent, and splitting
3214 * is not needed.
3215 */
556615dc
LC
3216 if (split_flag & EXT4_EXT_MARK_UNWRIT2)
3217 ext4_ext_mark_unwritten(ex);
47ea3bb5
YY
3218 else
3219 ext4_ext_mark_initialized(ex);
3220
3221 if (!(flags & EXT4_GET_BLOCKS_PRE_IO))
ecb94f5f 3222 ext4_ext_try_to_merge(handle, inode, path, ex);
47ea3bb5 3223
ecb94f5f 3224 err = ext4_ext_dirty(handle, inode, path + path->p_depth);
47ea3bb5
YY
3225 goto out;
3226 }
3227
3228 /* case a */
3229 memcpy(&orig_ex, ex, sizeof(orig_ex));
3230 ex->ee_len = cpu_to_le16(split - ee_block);
556615dc
LC
3231 if (split_flag & EXT4_EXT_MARK_UNWRIT1)
3232 ext4_ext_mark_unwritten(ex);
47ea3bb5
YY
3233
3234 /*
3235 * path may lead to new leaf, not to original leaf any more
3236 * after ext4_ext_insert_extent() returns,
3237 */
3238 err = ext4_ext_dirty(handle, inode, path + depth);
3239 if (err)
3240 goto fix_extent_len;
3241
3242 ex2 = &newex;
3243 ex2->ee_block = cpu_to_le32(split);
3244 ex2->ee_len = cpu_to_le16(ee_len - (split - ee_block));
3245 ext4_ext_store_pblock(ex2, newblock);
556615dc
LC
3246 if (split_flag & EXT4_EXT_MARK_UNWRIT2)
3247 ext4_ext_mark_unwritten(ex2);
47ea3bb5 3248
dfe50809 3249 err = ext4_ext_insert_extent(handle, inode, ppath, &newex, flags);
47ea3bb5 3250 if (err == -ENOSPC && (EXT4_EXT_MAY_ZEROOUT & split_flag)) {
dee1f973 3251 if (split_flag & (EXT4_EXT_DATA_VALID1|EXT4_EXT_DATA_VALID2)) {
adb23551 3252 if (split_flag & EXT4_EXT_DATA_VALID1) {
dee1f973 3253 err = ext4_ext_zeroout(inode, ex2);
adb23551 3254 zero_ex.ee_block = ex2->ee_block;
8cde7ad1
ZL
3255 zero_ex.ee_len = cpu_to_le16(
3256 ext4_ext_get_actual_len(ex2));
adb23551
ZL
3257 ext4_ext_store_pblock(&zero_ex,
3258 ext4_ext_pblock(ex2));
3259 } else {
dee1f973 3260 err = ext4_ext_zeroout(inode, ex);
adb23551 3261 zero_ex.ee_block = ex->ee_block;
8cde7ad1
ZL
3262 zero_ex.ee_len = cpu_to_le16(
3263 ext4_ext_get_actual_len(ex));
adb23551
ZL
3264 ext4_ext_store_pblock(&zero_ex,
3265 ext4_ext_pblock(ex));
3266 }
3267 } else {
dee1f973 3268 err = ext4_ext_zeroout(inode, &orig_ex);
adb23551 3269 zero_ex.ee_block = orig_ex.ee_block;
8cde7ad1
ZL
3270 zero_ex.ee_len = cpu_to_le16(
3271 ext4_ext_get_actual_len(&orig_ex));
adb23551
ZL
3272 ext4_ext_store_pblock(&zero_ex,
3273 ext4_ext_pblock(&orig_ex));
3274 }
dee1f973 3275
47ea3bb5
YY
3276 if (err)
3277 goto fix_extent_len;
3278 /* update the extent length and mark as initialized */
af1584f5 3279 ex->ee_len = cpu_to_le16(ee_len);
ecb94f5f
TT
3280 ext4_ext_try_to_merge(handle, inode, path, ex);
3281 err = ext4_ext_dirty(handle, inode, path + path->p_depth);
adb23551
ZL
3282 if (err)
3283 goto fix_extent_len;
3284
3285 /* update extent status tree */
d7b2a00c 3286 err = ext4_zeroout_es(inode, &zero_ex);
adb23551 3287
47ea3bb5
YY
3288 goto out;
3289 } else if (err)
3290 goto fix_extent_len;
3291
3292out:
3293 ext4_ext_show_leaf(inode, path);
3294 return err;
3295
3296fix_extent_len:
3297 ex->ee_len = orig_ex.ee_len;
29faed16 3298 ext4_ext_dirty(handle, inode, path + path->p_depth);
47ea3bb5
YY
3299 return err;
3300}
3301
3302/*
3303 * ext4_split_extents() splits an extent and mark extent which is covered
3304 * by @map as split_flags indicates
3305 *
70261f56 3306 * It may result in splitting the extent into multiple extents (up to three)
47ea3bb5
YY
3307 * There are three possibilities:
3308 * a> There is no split required
3309 * b> Splits in two extents: Split is happening at either end of the extent
3310 * c> Splits in three extents: Somone is splitting in middle of the extent
3311 *
3312 */
3313static int ext4_split_extent(handle_t *handle,
3314 struct inode *inode,
dfe50809 3315 struct ext4_ext_path **ppath,
47ea3bb5
YY
3316 struct ext4_map_blocks *map,
3317 int split_flag,
3318 int flags)
3319{
dfe50809 3320 struct ext4_ext_path *path = *ppath;
47ea3bb5
YY
3321 ext4_lblk_t ee_block;
3322 struct ext4_extent *ex;
3323 unsigned int ee_len, depth;
3324 int err = 0;
556615dc 3325 int unwritten;
47ea3bb5 3326 int split_flag1, flags1;
3a225670 3327 int allocated = map->m_len;
47ea3bb5
YY
3328
3329 depth = ext_depth(inode);
3330 ex = path[depth].p_ext;
3331 ee_block = le32_to_cpu(ex->ee_block);
3332 ee_len = ext4_ext_get_actual_len(ex);
556615dc 3333 unwritten = ext4_ext_is_unwritten(ex);
47ea3bb5
YY
3334
3335 if (map->m_lblk + map->m_len < ee_block + ee_len) {
dee1f973 3336 split_flag1 = split_flag & EXT4_EXT_MAY_ZEROOUT;
47ea3bb5 3337 flags1 = flags | EXT4_GET_BLOCKS_PRE_IO;
556615dc
LC
3338 if (unwritten)
3339 split_flag1 |= EXT4_EXT_MARK_UNWRIT1 |
3340 EXT4_EXT_MARK_UNWRIT2;
dee1f973
DM
3341 if (split_flag & EXT4_EXT_DATA_VALID2)
3342 split_flag1 |= EXT4_EXT_DATA_VALID1;
dfe50809 3343 err = ext4_split_extent_at(handle, inode, ppath,
47ea3bb5 3344 map->m_lblk + map->m_len, split_flag1, flags1);
93917411
YY
3345 if (err)
3346 goto out;
3a225670
ZL
3347 } else {
3348 allocated = ee_len - (map->m_lblk - ee_block);
47ea3bb5 3349 }
357b66fd
DM
3350 /*
3351 * Update path is required because previous ext4_split_extent_at() may
3352 * result in split of original leaf or extent zeroout.
3353 */
ed8a1a76 3354 path = ext4_find_extent(inode, map->m_lblk, ppath, 0);
47ea3bb5
YY
3355 if (IS_ERR(path))
3356 return PTR_ERR(path);
357b66fd
DM
3357 depth = ext_depth(inode);
3358 ex = path[depth].p_ext;
a18ed359
DM
3359 if (!ex) {
3360 EXT4_ERROR_INODE(inode, "unexpected hole at %lu",
3361 (unsigned long) map->m_lblk);
6a797d27 3362 return -EFSCORRUPTED;
a18ed359 3363 }
556615dc 3364 unwritten = ext4_ext_is_unwritten(ex);
357b66fd 3365 split_flag1 = 0;
47ea3bb5
YY
3366
3367 if (map->m_lblk >= ee_block) {
357b66fd 3368 split_flag1 = split_flag & EXT4_EXT_DATA_VALID2;
556615dc
LC
3369 if (unwritten) {
3370 split_flag1 |= EXT4_EXT_MARK_UNWRIT1;
357b66fd 3371 split_flag1 |= split_flag & (EXT4_EXT_MAY_ZEROOUT |
556615dc 3372 EXT4_EXT_MARK_UNWRIT2);
357b66fd 3373 }
dfe50809 3374 err = ext4_split_extent_at(handle, inode, ppath,
47ea3bb5
YY
3375 map->m_lblk, split_flag1, flags);
3376 if (err)
3377 goto out;
3378 }
3379
3380 ext4_ext_show_leaf(inode, path);
3381out:
3a225670 3382 return err ? err : allocated;
47ea3bb5
YY
3383}
3384
56055d3a 3385/*
e35fd660 3386 * This function is called by ext4_ext_map_blocks() if someone tries to write
556615dc 3387 * to an unwritten extent. It may result in splitting the unwritten
25985edc 3388 * extent into multiple extents (up to three - one initialized and two
556615dc 3389 * unwritten).
56055d3a
AA
3390 * There are three possibilities:
3391 * a> There is no split required: Entire extent should be initialized
3392 * b> Splits in two extents: Write is happening at either end of the extent
3393 * c> Splits in three extents: Somone is writing in middle of the extent
6f91bc5f
EG
3394 *
3395 * Pre-conditions:
556615dc 3396 * - The extent pointed to by 'path' is unwritten.
6f91bc5f
EG
3397 * - The extent pointed to by 'path' contains a superset
3398 * of the logical span [map->m_lblk, map->m_lblk + map->m_len).
3399 *
3400 * Post-conditions on success:
3401 * - the returned value is the number of blocks beyond map->l_lblk
3402 * that are allocated and initialized.
3403 * It is guaranteed to be >= map->m_len.
56055d3a 3404 */
725d26d3 3405static int ext4_ext_convert_to_initialized(handle_t *handle,
e35fd660
TT
3406 struct inode *inode,
3407 struct ext4_map_blocks *map,
dfe50809 3408 struct ext4_ext_path **ppath,
27dd4385 3409 int flags)
56055d3a 3410{
dfe50809 3411 struct ext4_ext_path *path = *ppath;
67a5da56 3412 struct ext4_sb_info *sbi;
6f91bc5f 3413 struct ext4_extent_header *eh;
667eff35
YY
3414 struct ext4_map_blocks split_map;
3415 struct ext4_extent zero_ex;
bc2d9db4 3416 struct ext4_extent *ex, *abut_ex;
21ca087a 3417 ext4_lblk_t ee_block, eof_block;
bc2d9db4
LC
3418 unsigned int ee_len, depth, map_len = map->m_len;
3419 int allocated = 0, max_zeroout = 0;
56055d3a 3420 int err = 0;
667eff35 3421 int split_flag = 0;
21ca087a
DM
3422
3423 ext_debug("ext4_ext_convert_to_initialized: inode %lu, logical"
3424 "block %llu, max_blocks %u\n", inode->i_ino,
bc2d9db4 3425 (unsigned long long)map->m_lblk, map_len);
21ca087a 3426
67a5da56 3427 sbi = EXT4_SB(inode->i_sb);
21ca087a
DM
3428 eof_block = (inode->i_size + inode->i_sb->s_blocksize - 1) >>
3429 inode->i_sb->s_blocksize_bits;
bc2d9db4
LC
3430 if (eof_block < map->m_lblk + map_len)
3431 eof_block = map->m_lblk + map_len;
56055d3a
AA
3432
3433 depth = ext_depth(inode);
6f91bc5f 3434 eh = path[depth].p_hdr;
56055d3a
AA
3435 ex = path[depth].p_ext;
3436 ee_block = le32_to_cpu(ex->ee_block);
3437 ee_len = ext4_ext_get_actual_len(ex);
adb23551 3438 zero_ex.ee_len = 0;
56055d3a 3439
6f91bc5f
EG
3440 trace_ext4_ext_convert_to_initialized_enter(inode, map, ex);
3441
3442 /* Pre-conditions */
556615dc 3443 BUG_ON(!ext4_ext_is_unwritten(ex));
6f91bc5f 3444 BUG_ON(!in_range(map->m_lblk, ee_block, ee_len));
6f91bc5f
EG
3445
3446 /*
3447 * Attempt to transfer newly initialized blocks from the currently
556615dc 3448 * unwritten extent to its neighbor. This is much cheaper
6f91bc5f 3449 * than an insertion followed by a merge as those involve costly
bc2d9db4
LC
3450 * memmove() calls. Transferring to the left is the common case in
3451 * steady state for workloads doing fallocate(FALLOC_FL_KEEP_SIZE)
3452 * followed by append writes.
6f91bc5f
EG
3453 *
3454 * Limitations of the current logic:
bc2d9db4 3455 * - L1: we do not deal with writes covering the whole extent.
6f91bc5f
EG
3456 * This would require removing the extent if the transfer
3457 * is possible.
bc2d9db4 3458 * - L2: we only attempt to merge with an extent stored in the
6f91bc5f
EG
3459 * same extent tree node.
3460 */
bc2d9db4
LC
3461 if ((map->m_lblk == ee_block) &&
3462 /* See if we can merge left */
3463 (map_len < ee_len) && /*L1*/
3464 (ex > EXT_FIRST_EXTENT(eh))) { /*L2*/
6f91bc5f
EG
3465 ext4_lblk_t prev_lblk;
3466 ext4_fsblk_t prev_pblk, ee_pblk;
bc2d9db4 3467 unsigned int prev_len;
6f91bc5f 3468
bc2d9db4
LC
3469 abut_ex = ex - 1;
3470 prev_lblk = le32_to_cpu(abut_ex->ee_block);
3471 prev_len = ext4_ext_get_actual_len(abut_ex);
3472 prev_pblk = ext4_ext_pblock(abut_ex);
6f91bc5f 3473 ee_pblk = ext4_ext_pblock(ex);
6f91bc5f
EG
3474
3475 /*
bc2d9db4 3476 * A transfer of blocks from 'ex' to 'abut_ex' is allowed
6f91bc5f 3477 * upon those conditions:
bc2d9db4
LC
3478 * - C1: abut_ex is initialized,
3479 * - C2: abut_ex is logically abutting ex,
3480 * - C3: abut_ex is physically abutting ex,
3481 * - C4: abut_ex can receive the additional blocks without
6f91bc5f
EG
3482 * overflowing the (initialized) length limit.
3483 */
556615dc 3484 if ((!ext4_ext_is_unwritten(abut_ex)) && /*C1*/
6f91bc5f
EG
3485 ((prev_lblk + prev_len) == ee_block) && /*C2*/
3486 ((prev_pblk + prev_len) == ee_pblk) && /*C3*/
bc2d9db4 3487 (prev_len < (EXT_INIT_MAX_LEN - map_len))) { /*C4*/
6f91bc5f
EG
3488 err = ext4_ext_get_access(handle, inode, path + depth);
3489 if (err)
3490 goto out;
3491
3492 trace_ext4_ext_convert_to_initialized_fastpath(inode,
bc2d9db4 3493 map, ex, abut_ex);
6f91bc5f 3494
bc2d9db4
LC
3495 /* Shift the start of ex by 'map_len' blocks */
3496 ex->ee_block = cpu_to_le32(ee_block + map_len);
3497 ext4_ext_store_pblock(ex, ee_pblk + map_len);
3498 ex->ee_len = cpu_to_le16(ee_len - map_len);
556615dc 3499 ext4_ext_mark_unwritten(ex); /* Restore the flag */
6f91bc5f 3500
bc2d9db4
LC
3501 /* Extend abut_ex by 'map_len' blocks */
3502 abut_ex->ee_len = cpu_to_le16(prev_len + map_len);
6f91bc5f 3503
bc2d9db4
LC
3504 /* Result: number of initialized blocks past m_lblk */
3505 allocated = map_len;
3506 }
3507 } else if (((map->m_lblk + map_len) == (ee_block + ee_len)) &&
3508 (map_len < ee_len) && /*L1*/
3509 ex < EXT_LAST_EXTENT(eh)) { /*L2*/
3510 /* See if we can merge right */
3511 ext4_lblk_t next_lblk;
3512 ext4_fsblk_t next_pblk, ee_pblk;
3513 unsigned int next_len;
3514
3515 abut_ex = ex + 1;
3516 next_lblk = le32_to_cpu(abut_ex->ee_block);
3517 next_len = ext4_ext_get_actual_len(abut_ex);
3518 next_pblk = ext4_ext_pblock(abut_ex);
3519 ee_pblk = ext4_ext_pblock(ex);
6f91bc5f 3520
bc2d9db4
LC
3521 /*
3522 * A transfer of blocks from 'ex' to 'abut_ex' is allowed
3523 * upon those conditions:
3524 * - C1: abut_ex is initialized,
3525 * - C2: abut_ex is logically abutting ex,
3526 * - C3: abut_ex is physically abutting ex,
3527 * - C4: abut_ex can receive the additional blocks without
3528 * overflowing the (initialized) length limit.
3529 */
556615dc 3530 if ((!ext4_ext_is_unwritten(abut_ex)) && /*C1*/
bc2d9db4
LC
3531 ((map->m_lblk + map_len) == next_lblk) && /*C2*/
3532 ((ee_pblk + ee_len) == next_pblk) && /*C3*/
3533 (next_len < (EXT_INIT_MAX_LEN - map_len))) { /*C4*/
3534 err = ext4_ext_get_access(handle, inode, path + depth);
3535 if (err)
3536 goto out;
3537
3538 trace_ext4_ext_convert_to_initialized_fastpath(inode,
3539 map, ex, abut_ex);
3540
3541 /* Shift the start of abut_ex by 'map_len' blocks */
3542 abut_ex->ee_block = cpu_to_le32(next_lblk - map_len);
3543 ext4_ext_store_pblock(abut_ex, next_pblk - map_len);
3544 ex->ee_len = cpu_to_le16(ee_len - map_len);
556615dc 3545 ext4_ext_mark_unwritten(ex); /* Restore the flag */
bc2d9db4
LC
3546
3547 /* Extend abut_ex by 'map_len' blocks */
3548 abut_ex->ee_len = cpu_to_le16(next_len + map_len);
6f91bc5f
EG
3549
3550 /* Result: number of initialized blocks past m_lblk */
bc2d9db4 3551 allocated = map_len;
6f91bc5f
EG
3552 }
3553 }
bc2d9db4
LC
3554 if (allocated) {
3555 /* Mark the block containing both extents as dirty */
3556 ext4_ext_dirty(handle, inode, path + depth);
3557
3558 /* Update path to point to the right extent */
3559 path[depth].p_ext = abut_ex;
3560 goto out;
3561 } else
3562 allocated = ee_len - (map->m_lblk - ee_block);
6f91bc5f 3563
667eff35 3564 WARN_ON(map->m_lblk < ee_block);
21ca087a
DM
3565 /*
3566 * It is safe to convert extent to initialized via explicit
9e740568 3567 * zeroout only if extent is fully inside i_size or new_size.
21ca087a 3568 */
667eff35 3569 split_flag |= ee_block + ee_len <= eof_block ? EXT4_EXT_MAY_ZEROOUT : 0;
21ca087a 3570
67a5da56
ZL
3571 if (EXT4_EXT_MAY_ZEROOUT & split_flag)
3572 max_zeroout = sbi->s_extent_max_zeroout_kb >>
4f42f80a 3573 (inode->i_sb->s_blocksize_bits - 10);
67a5da56 3574
36086d43
TT
3575 if (ext4_encrypted_inode(inode))
3576 max_zeroout = 0;
3577
67a5da56
ZL
3578 /* If extent is less than s_max_zeroout_kb, zeroout directly */
3579 if (max_zeroout && (ee_len <= max_zeroout)) {
667eff35 3580 err = ext4_ext_zeroout(inode, ex);
3977c965 3581 if (err)
d03856bd 3582 goto out;
adb23551 3583 zero_ex.ee_block = ex->ee_block;
8cde7ad1 3584 zero_ex.ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex));
adb23551 3585 ext4_ext_store_pblock(&zero_ex, ext4_ext_pblock(ex));
d03856bd
AK
3586
3587 err = ext4_ext_get_access(handle, inode, path + depth);
3588 if (err)
3589 goto out;
667eff35 3590 ext4_ext_mark_initialized(ex);
ecb94f5f
TT
3591 ext4_ext_try_to_merge(handle, inode, path, ex);
3592 err = ext4_ext_dirty(handle, inode, path + path->p_depth);
667eff35 3593 goto out;
56055d3a 3594 }
667eff35 3595
56055d3a 3596 /*
667eff35
YY
3597 * four cases:
3598 * 1. split the extent into three extents.
3599 * 2. split the extent into two extents, zeroout the first half.
3600 * 3. split the extent into two extents, zeroout the second half.
3601 * 4. split the extent into two extents with out zeroout.
56055d3a 3602 */
667eff35
YY
3603 split_map.m_lblk = map->m_lblk;
3604 split_map.m_len = map->m_len;
3605
67a5da56
ZL
3606 if (max_zeroout && (allocated > map->m_len)) {
3607 if (allocated <= max_zeroout) {
667eff35
YY
3608 /* case 3 */
3609 zero_ex.ee_block =
9b940f8e
AH
3610 cpu_to_le32(map->m_lblk);
3611 zero_ex.ee_len = cpu_to_le16(allocated);
667eff35
YY
3612 ext4_ext_store_pblock(&zero_ex,
3613 ext4_ext_pblock(ex) + map->m_lblk - ee_block);
3614 err = ext4_ext_zeroout(inode, &zero_ex);
56055d3a
AA
3615 if (err)
3616 goto out;
667eff35
YY
3617 split_map.m_lblk = map->m_lblk;
3618 split_map.m_len = allocated;
67a5da56 3619 } else if (map->m_lblk - ee_block + map->m_len < max_zeroout) {
667eff35
YY
3620 /* case 2 */
3621 if (map->m_lblk != ee_block) {
3622 zero_ex.ee_block = ex->ee_block;
3623 zero_ex.ee_len = cpu_to_le16(map->m_lblk -
3624 ee_block);
3625 ext4_ext_store_pblock(&zero_ex,
3626 ext4_ext_pblock(ex));
3627 err = ext4_ext_zeroout(inode, &zero_ex);
3628 if (err)
3629 goto out;
3630 }
3631
667eff35 3632 split_map.m_lblk = ee_block;
9b940f8e
AH
3633 split_map.m_len = map->m_lblk - ee_block + map->m_len;
3634 allocated = map->m_len;
56055d3a
AA
3635 }
3636 }
667eff35 3637
ae9e9c6a
JK
3638 err = ext4_split_extent(handle, inode, ppath, &split_map, split_flag,
3639 flags);
3640 if (err > 0)
3641 err = 0;
56055d3a 3642out:
adb23551
ZL
3643 /* If we have gotten a failure, don't zero out status tree */
3644 if (!err)
d7b2a00c 3645 err = ext4_zeroout_es(inode, &zero_ex);
56055d3a
AA
3646 return err ? err : allocated;
3647}
3648
0031462b 3649/*
e35fd660 3650 * This function is called by ext4_ext_map_blocks() from
0031462b 3651 * ext4_get_blocks_dio_write() when DIO to write
556615dc 3652 * to an unwritten extent.
0031462b 3653 *
556615dc
LC
3654 * Writing to an unwritten extent may result in splitting the unwritten
3655 * extent into multiple initialized/unwritten extents (up to three)
0031462b 3656 * There are three possibilities:
556615dc 3657 * a> There is no split required: Entire extent should be unwritten
0031462b
MC
3658 * b> Splits in two extents: Write is happening at either end of the extent
3659 * c> Splits in three extents: Somone is writing in middle of the extent
3660 *
b8a86845
LC
3661 * This works the same way in the case of initialized -> unwritten conversion.
3662 *
0031462b 3663 * One of more index blocks maybe needed if the extent tree grow after
556615dc
LC
3664 * the unwritten extent split. To prevent ENOSPC occur at the IO
3665 * complete, we need to split the unwritten extent before DIO submit
3666 * the IO. The unwritten extent called at this time will be split
3667 * into three unwritten extent(at most). After IO complete, the part
0031462b
MC
3668 * being filled will be convert to initialized by the end_io callback function
3669 * via ext4_convert_unwritten_extents().
ba230c3f 3670 *
556615dc 3671 * Returns the size of unwritten extent to be written on success.
0031462b 3672 */
b8a86845 3673static int ext4_split_convert_extents(handle_t *handle,
0031462b 3674 struct inode *inode,
e35fd660 3675 struct ext4_map_blocks *map,
dfe50809 3676 struct ext4_ext_path **ppath,
0031462b
MC
3677 int flags)
3678{
dfe50809 3679 struct ext4_ext_path *path = *ppath;
667eff35
YY
3680 ext4_lblk_t eof_block;
3681 ext4_lblk_t ee_block;
3682 struct ext4_extent *ex;
3683 unsigned int ee_len;
3684 int split_flag = 0, depth;
21ca087a 3685
b8a86845
LC
3686 ext_debug("%s: inode %lu, logical block %llu, max_blocks %u\n",
3687 __func__, inode->i_ino,
3688 (unsigned long long)map->m_lblk, map->m_len);
21ca087a
DM
3689
3690 eof_block = (inode->i_size + inode->i_sb->s_blocksize - 1) >>
3691 inode->i_sb->s_blocksize_bits;
e35fd660
TT
3692 if (eof_block < map->m_lblk + map->m_len)
3693 eof_block = map->m_lblk + map->m_len;
21ca087a
DM
3694 /*
3695 * It is safe to convert extent to initialized via explicit
3696 * zeroout only if extent is fully insde i_size or new_size.
3697 */
667eff35
YY
3698 depth = ext_depth(inode);
3699 ex = path[depth].p_ext;
3700 ee_block = le32_to_cpu(ex->ee_block);
3701 ee_len = ext4_ext_get_actual_len(ex);
0031462b 3702
b8a86845
LC
3703 /* Convert to unwritten */
3704 if (flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN) {
3705 split_flag |= EXT4_EXT_DATA_VALID1;
3706 /* Convert to initialized */
3707 } else if (flags & EXT4_GET_BLOCKS_CONVERT) {
3708 split_flag |= ee_block + ee_len <= eof_block ?
3709 EXT4_EXT_MAY_ZEROOUT : 0;
556615dc 3710 split_flag |= (EXT4_EXT_MARK_UNWRIT2 | EXT4_EXT_DATA_VALID2);
b8a86845 3711 }
667eff35 3712 flags |= EXT4_GET_BLOCKS_PRE_IO;
dfe50809 3713 return ext4_split_extent(handle, inode, ppath, map, split_flag, flags);
0031462b 3714}
197217a5 3715
c7064ef1 3716static int ext4_convert_unwritten_extents_endio(handle_t *handle,
dee1f973
DM
3717 struct inode *inode,
3718 struct ext4_map_blocks *map,
dfe50809 3719 struct ext4_ext_path **ppath)
0031462b 3720{
dfe50809 3721 struct ext4_ext_path *path = *ppath;
0031462b 3722 struct ext4_extent *ex;
dee1f973
DM
3723 ext4_lblk_t ee_block;
3724 unsigned int ee_len;
0031462b
MC
3725 int depth;
3726 int err = 0;
0031462b
MC
3727
3728 depth = ext_depth(inode);
0031462b 3729 ex = path[depth].p_ext;
dee1f973
DM
3730 ee_block = le32_to_cpu(ex->ee_block);
3731 ee_len = ext4_ext_get_actual_len(ex);
0031462b 3732
197217a5
YY
3733 ext_debug("ext4_convert_unwritten_extents_endio: inode %lu, logical"
3734 "block %llu, max_blocks %u\n", inode->i_ino,
dee1f973
DM
3735 (unsigned long long)ee_block, ee_len);
3736
ff95ec22
DM
3737 /* If extent is larger than requested it is a clear sign that we still
3738 * have some extent state machine issues left. So extent_split is still
3739 * required.
3740 * TODO: Once all related issues will be fixed this situation should be
3741 * illegal.
3742 */
dee1f973 3743 if (ee_block != map->m_lblk || ee_len > map->m_len) {
ff95ec22
DM
3744#ifdef EXT4_DEBUG
3745 ext4_warning("Inode (%ld) finished: extent logical block %llu,"
3746 " len %u; IO logical block %llu, len %u\n",
3747 inode->i_ino, (unsigned long long)ee_block, ee_len,
3748 (unsigned long long)map->m_lblk, map->m_len);
3749#endif
dfe50809 3750 err = ext4_split_convert_extents(handle, inode, map, ppath,
b8a86845 3751 EXT4_GET_BLOCKS_CONVERT);
dee1f973 3752 if (err < 0)
dfe50809 3753 return err;
ed8a1a76 3754 path = ext4_find_extent(inode, map->m_lblk, ppath, 0);
dfe50809
TT
3755 if (IS_ERR(path))
3756 return PTR_ERR(path);
dee1f973
DM
3757 depth = ext_depth(inode);
3758 ex = path[depth].p_ext;
3759 }
197217a5 3760
0031462b
MC
3761 err = ext4_ext_get_access(handle, inode, path + depth);
3762 if (err)
3763 goto out;
3764 /* first mark the extent as initialized */
3765 ext4_ext_mark_initialized(ex);
3766
197217a5
YY
3767 /* note: ext4_ext_correct_indexes() isn't needed here because
3768 * borders are not changed
0031462b 3769 */
ecb94f5f 3770 ext4_ext_try_to_merge(handle, inode, path, ex);
197217a5 3771
0031462b 3772 /* Mark modified extent as dirty */
ecb94f5f 3773 err = ext4_ext_dirty(handle, inode, path + path->p_depth);
0031462b
MC
3774out:
3775 ext4_ext_show_leaf(inode, path);
3776 return err;
3777}
3778
515f41c3
AK
3779static void unmap_underlying_metadata_blocks(struct block_device *bdev,
3780 sector_t block, int count)
3781{
3782 int i;
3783 for (i = 0; i < count; i++)
3784 unmap_underlying_metadata(bdev, block + i);
3785}
3786
58590b06
TT
3787/*
3788 * Handle EOFBLOCKS_FL flag, clearing it if necessary
3789 */
3790static int check_eofblocks_fl(handle_t *handle, struct inode *inode,
d002ebf1 3791 ext4_lblk_t lblk,
58590b06
TT
3792 struct ext4_ext_path *path,
3793 unsigned int len)
3794{
3795 int i, depth;
3796 struct ext4_extent_header *eh;
65922cb5 3797 struct ext4_extent *last_ex;
58590b06
TT
3798
3799 if (!ext4_test_inode_flag(inode, EXT4_INODE_EOFBLOCKS))
3800 return 0;
3801
3802 depth = ext_depth(inode);
3803 eh = path[depth].p_hdr;
58590b06 3804
afcff5d8
LC
3805 /*
3806 * We're going to remove EOFBLOCKS_FL entirely in future so we
3807 * do not care for this case anymore. Simply remove the flag
3808 * if there are no extents.
3809 */
3810 if (unlikely(!eh->eh_entries))
3811 goto out;
58590b06
TT
3812 last_ex = EXT_LAST_EXTENT(eh);
3813 /*
3814 * We should clear the EOFBLOCKS_FL flag if we are writing the
3815 * last block in the last extent in the file. We test this by
3816 * first checking to see if the caller to
3817 * ext4_ext_get_blocks() was interested in the last block (or
3818 * a block beyond the last block) in the current extent. If
3819 * this turns out to be false, we can bail out from this
3820 * function immediately.
3821 */
d002ebf1 3822 if (lblk + len < le32_to_cpu(last_ex->ee_block) +
58590b06
TT
3823 ext4_ext_get_actual_len(last_ex))
3824 return 0;
3825 /*
3826 * If the caller does appear to be planning to write at or
3827 * beyond the end of the current extent, we then test to see
3828 * if the current extent is the last extent in the file, by
3829 * checking to make sure it was reached via the rightmost node
3830 * at each level of the tree.
3831 */
3832 for (i = depth-1; i >= 0; i--)
3833 if (path[i].p_idx != EXT_LAST_INDEX(path[i].p_hdr))
3834 return 0;
afcff5d8 3835out:
58590b06
TT
3836 ext4_clear_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
3837 return ext4_mark_inode_dirty(handle, inode);
3838}
3839
7b415bf6
AK
3840/**
3841 * ext4_find_delalloc_range: find delayed allocated block in the given range.
3842 *
7d1b1fbc 3843 * Return 1 if there is a delalloc block in the range, otherwise 0.
7b415bf6 3844 */
f7fec032
ZL
3845int ext4_find_delalloc_range(struct inode *inode,
3846 ext4_lblk_t lblk_start,
3847 ext4_lblk_t lblk_end)
7b415bf6 3848{
7d1b1fbc 3849 struct extent_status es;
7b415bf6 3850
e30b5dca 3851 ext4_es_find_delayed_extent_range(inode, lblk_start, lblk_end, &es);
06b0c886 3852 if (es.es_len == 0)
7d1b1fbc 3853 return 0; /* there is no delay extent in this tree */
06b0c886
ZL
3854 else if (es.es_lblk <= lblk_start &&
3855 lblk_start < es.es_lblk + es.es_len)
7d1b1fbc 3856 return 1;
06b0c886 3857 else if (lblk_start <= es.es_lblk && es.es_lblk <= lblk_end)
7d1b1fbc 3858 return 1;
7b415bf6 3859 else
7d1b1fbc 3860 return 0;
7b415bf6
AK
3861}
3862
7d1b1fbc 3863int ext4_find_delalloc_cluster(struct inode *inode, ext4_lblk_t lblk)
7b415bf6
AK
3864{
3865 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3866 ext4_lblk_t lblk_start, lblk_end;
f5a44db5 3867 lblk_start = EXT4_LBLK_CMASK(sbi, lblk);
7b415bf6
AK
3868 lblk_end = lblk_start + sbi->s_cluster_ratio - 1;
3869
7d1b1fbc 3870 return ext4_find_delalloc_range(inode, lblk_start, lblk_end);
7b415bf6
AK
3871}
3872
3873/**
3874 * Determines how many complete clusters (out of those specified by the 'map')
3875 * are under delalloc and were reserved quota for.
3876 * This function is called when we are writing out the blocks that were
3877 * originally written with their allocation delayed, but then the space was
3878 * allocated using fallocate() before the delayed allocation could be resolved.
3879 * The cases to look for are:
3880 * ('=' indicated delayed allocated blocks
3881 * '-' indicates non-delayed allocated blocks)
3882 * (a) partial clusters towards beginning and/or end outside of allocated range
3883 * are not delalloc'ed.
3884 * Ex:
3885 * |----c---=|====c====|====c====|===-c----|
3886 * |++++++ allocated ++++++|
3887 * ==> 4 complete clusters in above example
3888 *
3889 * (b) partial cluster (outside of allocated range) towards either end is
3890 * marked for delayed allocation. In this case, we will exclude that
3891 * cluster.
3892 * Ex:
3893 * |----====c========|========c========|
3894 * |++++++ allocated ++++++|
3895 * ==> 1 complete clusters in above example
3896 *
3897 * Ex:
3898 * |================c================|
3899 * |++++++ allocated ++++++|
3900 * ==> 0 complete clusters in above example
3901 *
3902 * The ext4_da_update_reserve_space will be called only if we
3903 * determine here that there were some "entire" clusters that span
3904 * this 'allocated' range.
3905 * In the non-bigalloc case, this function will just end up returning num_blks
3906 * without ever calling ext4_find_delalloc_range.
3907 */
3908static unsigned int
3909get_reserved_cluster_alloc(struct inode *inode, ext4_lblk_t lblk_start,
3910 unsigned int num_blks)
3911{
3912 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3913 ext4_lblk_t alloc_cluster_start, alloc_cluster_end;
3914 ext4_lblk_t lblk_from, lblk_to, c_offset;
3915 unsigned int allocated_clusters = 0;
3916
3917 alloc_cluster_start = EXT4_B2C(sbi, lblk_start);
3918 alloc_cluster_end = EXT4_B2C(sbi, lblk_start + num_blks - 1);
3919
3920 /* max possible clusters for this allocation */
3921 allocated_clusters = alloc_cluster_end - alloc_cluster_start + 1;
3922
d8990240
AK
3923 trace_ext4_get_reserved_cluster_alloc(inode, lblk_start, num_blks);
3924
7b415bf6 3925 /* Check towards left side */
f5a44db5 3926 c_offset = EXT4_LBLK_COFF(sbi, lblk_start);
7b415bf6 3927 if (c_offset) {
f5a44db5 3928 lblk_from = EXT4_LBLK_CMASK(sbi, lblk_start);
7b415bf6
AK
3929 lblk_to = lblk_from + c_offset - 1;
3930
7d1b1fbc 3931 if (ext4_find_delalloc_range(inode, lblk_from, lblk_to))
7b415bf6
AK
3932 allocated_clusters--;
3933 }
3934
3935 /* Now check towards right. */
f5a44db5 3936 c_offset = EXT4_LBLK_COFF(sbi, lblk_start + num_blks);
7b415bf6
AK
3937 if (allocated_clusters && c_offset) {
3938 lblk_from = lblk_start + num_blks;
3939 lblk_to = lblk_from + (sbi->s_cluster_ratio - c_offset) - 1;
3940
7d1b1fbc 3941 if (ext4_find_delalloc_range(inode, lblk_from, lblk_to))
7b415bf6
AK
3942 allocated_clusters--;
3943 }
3944
3945 return allocated_clusters;
3946}
3947
b8a86845 3948static int
e8b83d93
TT
3949convert_initialized_extent(handle_t *handle, struct inode *inode,
3950 struct ext4_map_blocks *map,
29c6eaff 3951 struct ext4_ext_path **ppath,
56263b4c 3952 unsigned int allocated)
b8a86845 3953{
4f224b8b 3954 struct ext4_ext_path *path = *ppath;
e8b83d93
TT
3955 struct ext4_extent *ex;
3956 ext4_lblk_t ee_block;
3957 unsigned int ee_len;
3958 int depth;
b8a86845
LC
3959 int err = 0;
3960
3961 /*
3962 * Make sure that the extent is no bigger than we support with
556615dc 3963 * unwritten extent
b8a86845 3964 */
556615dc
LC
3965 if (map->m_len > EXT_UNWRITTEN_MAX_LEN)
3966 map->m_len = EXT_UNWRITTEN_MAX_LEN / 2;
b8a86845 3967
e8b83d93
TT
3968 depth = ext_depth(inode);
3969 ex = path[depth].p_ext;
3970 ee_block = le32_to_cpu(ex->ee_block);
3971 ee_len = ext4_ext_get_actual_len(ex);
3972
3973 ext_debug("%s: inode %lu, logical"
3974 "block %llu, max_blocks %u\n", __func__, inode->i_ino,
3975 (unsigned long long)ee_block, ee_len);
3976
3977 if (ee_block != map->m_lblk || ee_len > map->m_len) {
dfe50809 3978 err = ext4_split_convert_extents(handle, inode, map, ppath,
e8b83d93
TT
3979 EXT4_GET_BLOCKS_CONVERT_UNWRITTEN);
3980 if (err < 0)
3981 return err;
ed8a1a76 3982 path = ext4_find_extent(inode, map->m_lblk, ppath, 0);
e8b83d93
TT
3983 if (IS_ERR(path))
3984 return PTR_ERR(path);
3985 depth = ext_depth(inode);
3986 ex = path[depth].p_ext;
3987 if (!ex) {
3988 EXT4_ERROR_INODE(inode, "unexpected hole at %lu",
3989 (unsigned long) map->m_lblk);
6a797d27 3990 return -EFSCORRUPTED;
e8b83d93
TT
3991 }
3992 }
3993
3994 err = ext4_ext_get_access(handle, inode, path + depth);
3995 if (err)
3996 return err;
3997 /* first mark the extent as unwritten */
3998 ext4_ext_mark_unwritten(ex);
3999
4000 /* note: ext4_ext_correct_indexes() isn't needed here because
4001 * borders are not changed
4002 */
4003 ext4_ext_try_to_merge(handle, inode, path, ex);
4004
4005 /* Mark modified extent as dirty */
4006 err = ext4_ext_dirty(handle, inode, path + path->p_depth);
4007 if (err)
4008 return err;
4009 ext4_ext_show_leaf(inode, path);
4010
4011 ext4_update_inode_fsync_trans(handle, inode, 1);
4012 err = check_eofblocks_fl(handle, inode, map->m_lblk, path, map->m_len);
4013 if (err)
4014 return err;
b8a86845
LC
4015 map->m_flags |= EXT4_MAP_UNWRITTEN;
4016 if (allocated > map->m_len)
4017 allocated = map->m_len;
4018 map->m_len = allocated;
e8b83d93 4019 return allocated;
b8a86845
LC
4020}
4021
0031462b 4022static int
556615dc 4023ext4_ext_handle_unwritten_extents(handle_t *handle, struct inode *inode,
e35fd660 4024 struct ext4_map_blocks *map,
dfe50809 4025 struct ext4_ext_path **ppath, int flags,
e35fd660 4026 unsigned int allocated, ext4_fsblk_t newblock)
0031462b 4027{
dfe50809 4028 struct ext4_ext_path *path = *ppath;
0031462b
MC
4029 int ret = 0;
4030 int err = 0;
4031
556615dc 4032 ext_debug("ext4_ext_handle_unwritten_extents: inode %lu, logical "
88635ca2 4033 "block %llu, max_blocks %u, flags %x, allocated %u\n",
e35fd660 4034 inode->i_ino, (unsigned long long)map->m_lblk, map->m_len,
0031462b
MC
4035 flags, allocated);
4036 ext4_ext_show_leaf(inode, path);
4037
27dd4385 4038 /*
556615dc 4039 * When writing into unwritten space, we should not fail to
27dd4385
LC
4040 * allocate metadata blocks for the new extent block if needed.
4041 */
4042 flags |= EXT4_GET_BLOCKS_METADATA_NOFAIL;
4043
556615dc 4044 trace_ext4_ext_handle_unwritten_extents(inode, map, flags,
b5645534 4045 allocated, newblock);
d8990240 4046
c7064ef1 4047 /* get_block() before submit the IO, split the extent */
c8b459f4 4048 if (flags & EXT4_GET_BLOCKS_PRE_IO) {
dfe50809
TT
4049 ret = ext4_split_convert_extents(handle, inode, map, ppath,
4050 flags | EXT4_GET_BLOCKS_CONVERT);
82e54229
DM
4051 if (ret <= 0)
4052 goto out;
a25a4e1a 4053 map->m_flags |= EXT4_MAP_UNWRITTEN;
0031462b
MC
4054 goto out;
4055 }
c7064ef1 4056 /* IO end_io complete, convert the filled extent to written */
c8b459f4 4057 if (flags & EXT4_GET_BLOCKS_CONVERT) {
c86d8db3
JK
4058 if (flags & EXT4_GET_BLOCKS_ZERO) {
4059 if (allocated > map->m_len)
4060 allocated = map->m_len;
4061 err = ext4_issue_zeroout(inode, map->m_lblk, newblock,
4062 allocated);
4063 if (err < 0)
4064 goto out2;
4065 }
dee1f973 4066 ret = ext4_convert_unwritten_extents_endio(handle, inode, map,
dfe50809 4067 ppath);
58590b06 4068 if (ret >= 0) {
b436b9be 4069 ext4_update_inode_fsync_trans(handle, inode, 1);
d002ebf1
ES
4070 err = check_eofblocks_fl(handle, inode, map->m_lblk,
4071 path, map->m_len);
58590b06
TT
4072 } else
4073 err = ret;
cdee7843 4074 map->m_flags |= EXT4_MAP_MAPPED;
15cc1767 4075 map->m_pblk = newblock;
cdee7843
ZL
4076 if (allocated > map->m_len)
4077 allocated = map->m_len;
4078 map->m_len = allocated;
0031462b
MC
4079 goto out2;
4080 }
4081 /* buffered IO case */
4082 /*
4083 * repeat fallocate creation request
4084 * we already have an unwritten extent
4085 */
556615dc 4086 if (flags & EXT4_GET_BLOCKS_UNWRIT_EXT) {
a25a4e1a 4087 map->m_flags |= EXT4_MAP_UNWRITTEN;
0031462b 4088 goto map_out;
a25a4e1a 4089 }
0031462b
MC
4090
4091 /* buffered READ or buffered write_begin() lookup */
4092 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
4093 /*
4094 * We have blocks reserved already. We
4095 * return allocated blocks so that delalloc
4096 * won't do block reservation for us. But
4097 * the buffer head will be unmapped so that
4098 * a read from the block returns 0s.
4099 */
e35fd660 4100 map->m_flags |= EXT4_MAP_UNWRITTEN;
0031462b
MC
4101 goto out1;
4102 }
4103
4104 /* buffered write, writepage time, convert*/
dfe50809 4105 ret = ext4_ext_convert_to_initialized(handle, inode, map, ppath, flags);
a4e5d88b 4106 if (ret >= 0)
b436b9be 4107 ext4_update_inode_fsync_trans(handle, inode, 1);
0031462b
MC
4108out:
4109 if (ret <= 0) {
4110 err = ret;
4111 goto out2;
4112 } else
4113 allocated = ret;
e35fd660 4114 map->m_flags |= EXT4_MAP_NEW;
515f41c3
AK
4115 /*
4116 * if we allocated more blocks than requested
4117 * we need to make sure we unmap the extra block
4118 * allocated. The actual needed block will get
4119 * unmapped later when we find the buffer_head marked
4120 * new.
4121 */
e35fd660 4122 if (allocated > map->m_len) {
515f41c3 4123 unmap_underlying_metadata_blocks(inode->i_sb->s_bdev,
e35fd660
TT
4124 newblock + map->m_len,
4125 allocated - map->m_len);
4126 allocated = map->m_len;
515f41c3 4127 }
3a225670 4128 map->m_len = allocated;
5f634d06
AK
4129
4130 /*
4131 * If we have done fallocate with the offset that is already
4132 * delayed allocated, we would have block reservation
4133 * and quota reservation done in the delayed write path.
4134 * But fallocate would have already updated quota and block
4135 * count for this offset. So cancel these reservation
4136 */
7b415bf6
AK
4137 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) {
4138 unsigned int reserved_clusters;
4139 reserved_clusters = get_reserved_cluster_alloc(inode,
4140 map->m_lblk, map->m_len);
4141 if (reserved_clusters)
4142 ext4_da_update_reserve_space(inode,
4143 reserved_clusters,
4144 0);
4145 }
5f634d06 4146
0031462b 4147map_out:
e35fd660 4148 map->m_flags |= EXT4_MAP_MAPPED;
a4e5d88b
DM
4149 if ((flags & EXT4_GET_BLOCKS_KEEP_SIZE) == 0) {
4150 err = check_eofblocks_fl(handle, inode, map->m_lblk, path,
4151 map->m_len);
4152 if (err < 0)
4153 goto out2;
4154 }
0031462b 4155out1:
e35fd660
TT
4156 if (allocated > map->m_len)
4157 allocated = map->m_len;
0031462b 4158 ext4_ext_show_leaf(inode, path);
e35fd660
TT
4159 map->m_pblk = newblock;
4160 map->m_len = allocated;
0031462b 4161out2:
0031462b
MC
4162 return err ? err : allocated;
4163}
58590b06 4164
4d33b1ef
TT
4165/*
4166 * get_implied_cluster_alloc - check to see if the requested
4167 * allocation (in the map structure) overlaps with a cluster already
4168 * allocated in an extent.
d8990240 4169 * @sb The filesystem superblock structure
4d33b1ef
TT
4170 * @map The requested lblk->pblk mapping
4171 * @ex The extent structure which might contain an implied
4172 * cluster allocation
4173 *
4174 * This function is called by ext4_ext_map_blocks() after we failed to
4175 * find blocks that were already in the inode's extent tree. Hence,
4176 * we know that the beginning of the requested region cannot overlap
4177 * the extent from the inode's extent tree. There are three cases we
4178 * want to catch. The first is this case:
4179 *
4180 * |--- cluster # N--|
4181 * |--- extent ---| |---- requested region ---|
4182 * |==========|
4183 *
4184 * The second case that we need to test for is this one:
4185 *
4186 * |--------- cluster # N ----------------|
4187 * |--- requested region --| |------- extent ----|
4188 * |=======================|
4189 *
4190 * The third case is when the requested region lies between two extents
4191 * within the same cluster:
4192 * |------------- cluster # N-------------|
4193 * |----- ex -----| |---- ex_right ----|
4194 * |------ requested region ------|
4195 * |================|
4196 *
4197 * In each of the above cases, we need to set the map->m_pblk and
4198 * map->m_len so it corresponds to the return the extent labelled as
4199 * "|====|" from cluster #N, since it is already in use for data in
4200 * cluster EXT4_B2C(sbi, map->m_lblk). We will then return 1 to
4201 * signal to ext4_ext_map_blocks() that map->m_pblk should be treated
4202 * as a new "allocated" block region. Otherwise, we will return 0 and
4203 * ext4_ext_map_blocks() will then allocate one or more new clusters
4204 * by calling ext4_mb_new_blocks().
4205 */
d8990240 4206static int get_implied_cluster_alloc(struct super_block *sb,
4d33b1ef
TT
4207 struct ext4_map_blocks *map,
4208 struct ext4_extent *ex,
4209 struct ext4_ext_path *path)
4210{
d8990240 4211 struct ext4_sb_info *sbi = EXT4_SB(sb);
f5a44db5 4212 ext4_lblk_t c_offset = EXT4_LBLK_COFF(sbi, map->m_lblk);
4d33b1ef 4213 ext4_lblk_t ex_cluster_start, ex_cluster_end;
14d7f3ef 4214 ext4_lblk_t rr_cluster_start;
4d33b1ef
TT
4215 ext4_lblk_t ee_block = le32_to_cpu(ex->ee_block);
4216 ext4_fsblk_t ee_start = ext4_ext_pblock(ex);
4217 unsigned short ee_len = ext4_ext_get_actual_len(ex);
4218
4219 /* The extent passed in that we are trying to match */
4220 ex_cluster_start = EXT4_B2C(sbi, ee_block);
4221 ex_cluster_end = EXT4_B2C(sbi, ee_block + ee_len - 1);
4222
4223 /* The requested region passed into ext4_map_blocks() */
4224 rr_cluster_start = EXT4_B2C(sbi, map->m_lblk);
4d33b1ef
TT
4225
4226 if ((rr_cluster_start == ex_cluster_end) ||
4227 (rr_cluster_start == ex_cluster_start)) {
4228 if (rr_cluster_start == ex_cluster_end)
4229 ee_start += ee_len - 1;
f5a44db5 4230 map->m_pblk = EXT4_PBLK_CMASK(sbi, ee_start) + c_offset;
4d33b1ef
TT
4231 map->m_len = min(map->m_len,
4232 (unsigned) sbi->s_cluster_ratio - c_offset);
4233 /*
4234 * Check for and handle this case:
4235 *
4236 * |--------- cluster # N-------------|
4237 * |------- extent ----|
4238 * |--- requested region ---|
4239 * |===========|
4240 */
4241
4242 if (map->m_lblk < ee_block)
4243 map->m_len = min(map->m_len, ee_block - map->m_lblk);
4244
4245 /*
4246 * Check for the case where there is already another allocated
4247 * block to the right of 'ex' but before the end of the cluster.
4248 *
4249 * |------------- cluster # N-------------|
4250 * |----- ex -----| |---- ex_right ----|
4251 * |------ requested region ------|
4252 * |================|
4253 */
4254 if (map->m_lblk > ee_block) {
4255 ext4_lblk_t next = ext4_ext_next_allocated_block(path);
4256 map->m_len = min(map->m_len, next - map->m_lblk);
4257 }
d8990240
AK
4258
4259 trace_ext4_get_implied_cluster_alloc_exit(sb, map, 1);
4d33b1ef
TT
4260 return 1;
4261 }
d8990240
AK
4262
4263 trace_ext4_get_implied_cluster_alloc_exit(sb, map, 0);
4d33b1ef
TT
4264 return 0;
4265}
4266
4267
c278bfec 4268/*
f5ab0d1f
MC
4269 * Block allocation/map/preallocation routine for extents based files
4270 *
4271 *
c278bfec 4272 * Need to be called with
0e855ac8
AK
4273 * down_read(&EXT4_I(inode)->i_data_sem) if not allocating file system block
4274 * (ie, create is zero). Otherwise down_write(&EXT4_I(inode)->i_data_sem)
f5ab0d1f
MC
4275 *
4276 * return > 0, number of of blocks already mapped/allocated
4277 * if create == 0 and these are pre-allocated blocks
4278 * buffer head is unmapped
4279 * otherwise blocks are mapped
4280 *
4281 * return = 0, if plain look up failed (blocks have not been allocated)
4282 * buffer head is unmapped
4283 *
4284 * return < 0, error case.
c278bfec 4285 */
e35fd660
TT
4286int ext4_ext_map_blocks(handle_t *handle, struct inode *inode,
4287 struct ext4_map_blocks *map, int flags)
a86c6181
AT
4288{
4289 struct ext4_ext_path *path = NULL;
4d33b1ef
TT
4290 struct ext4_extent newex, *ex, *ex2;
4291 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
0562e0ba 4292 ext4_fsblk_t newblock = 0;
ce37c429 4293 int free_on_err = 0, err = 0, depth, ret;
4d33b1ef 4294 unsigned int allocated = 0, offset = 0;
81fdbb4a 4295 unsigned int allocated_clusters = 0;
c9de560d 4296 struct ext4_allocation_request ar;
4d33b1ef 4297 ext4_lblk_t cluster_offset;
cbd7584e 4298 bool map_from_cluster = false;
a86c6181 4299
84fe3bef 4300 ext_debug("blocks %u/%u requested for inode %lu\n",
e35fd660 4301 map->m_lblk, map->m_len, inode->i_ino);
0562e0ba 4302 trace_ext4_ext_map_blocks_enter(inode, map->m_lblk, map->m_len, flags);
a86c6181 4303
a86c6181 4304 /* find extent for this block */
ed8a1a76 4305 path = ext4_find_extent(inode, map->m_lblk, NULL, 0);
a86c6181
AT
4306 if (IS_ERR(path)) {
4307 err = PTR_ERR(path);
4308 path = NULL;
4309 goto out2;
4310 }
4311
4312 depth = ext_depth(inode);
4313
4314 /*
d0d856e8
RD
4315 * consistent leaf must not be empty;
4316 * this situation is possible, though, _during_ tree modification;
ed8a1a76 4317 * this is why assert can't be put in ext4_find_extent()
a86c6181 4318 */
273df556
FM
4319 if (unlikely(path[depth].p_ext == NULL && depth != 0)) {
4320 EXT4_ERROR_INODE(inode, "bad extent address "
f70f362b
TT
4321 "lblock: %lu, depth: %d pblock %lld",
4322 (unsigned long) map->m_lblk, depth,
4323 path[depth].p_block);
6a797d27 4324 err = -EFSCORRUPTED;
034fb4c9
SP
4325 goto out2;
4326 }
a86c6181 4327
7e028976
AM
4328 ex = path[depth].p_ext;
4329 if (ex) {
725d26d3 4330 ext4_lblk_t ee_block = le32_to_cpu(ex->ee_block);
bf89d16f 4331 ext4_fsblk_t ee_start = ext4_ext_pblock(ex);
a2df2a63 4332 unsigned short ee_len;
471d4011 4333
b8a86845 4334
471d4011 4335 /*
556615dc 4336 * unwritten extents are treated as holes, except that
56055d3a 4337 * we split out initialized portions during a write.
471d4011 4338 */
a2df2a63 4339 ee_len = ext4_ext_get_actual_len(ex);
d8990240
AK
4340
4341 trace_ext4_ext_show_extent(inode, ee_block, ee_start, ee_len);
4342
d0d856e8 4343 /* if found extent covers block, simply return it */
e35fd660
TT
4344 if (in_range(map->m_lblk, ee_block, ee_len)) {
4345 newblock = map->m_lblk - ee_block + ee_start;
d0d856e8 4346 /* number of remaining blocks in the extent */
e35fd660
TT
4347 allocated = ee_len - (map->m_lblk - ee_block);
4348 ext_debug("%u fit into %u:%d -> %llu\n", map->m_lblk,
4349 ee_block, ee_len, newblock);
56055d3a 4350
b8a86845
LC
4351 /*
4352 * If the extent is initialized check whether the
4353 * caller wants to convert it to unwritten.
4354 */
556615dc 4355 if ((!ext4_ext_is_unwritten(ex)) &&
b8a86845 4356 (flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN)) {
e8b83d93 4357 allocated = convert_initialized_extent(
4f224b8b 4358 handle, inode, map, &path,
29c6eaff 4359 allocated);
b8a86845 4360 goto out2;
556615dc 4361 } else if (!ext4_ext_is_unwritten(ex))
7877191c 4362 goto out;
69eb33dc 4363
556615dc 4364 ret = ext4_ext_handle_unwritten_extents(
dfe50809 4365 handle, inode, map, &path, flags,
7877191c 4366 allocated, newblock);
ce37c429
EW
4367 if (ret < 0)
4368 err = ret;
4369 else
4370 allocated = ret;
31cf0f2c 4371 goto out2;
a86c6181
AT
4372 }
4373 }
4374
4375 /*
d0d856e8 4376 * requested block isn't allocated yet;
a86c6181
AT
4377 * we couldn't try to create block if create flag is zero
4378 */
c2177057 4379 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
140a5250
JK
4380 ext4_lblk_t hole_start, hole_len;
4381
facab4d9
JK
4382 hole_start = map->m_lblk;
4383 hole_len = ext4_ext_determine_hole(inode, path, &hole_start);
56055d3a
AA
4384 /*
4385 * put just found gap into cache to speed up
4386 * subsequent requests
4387 */
140a5250 4388 ext4_ext_put_gap_in_cache(inode, hole_start, hole_len);
facab4d9
JK
4389
4390 /* Update hole_len to reflect hole size after map->m_lblk */
4391 if (hole_start != map->m_lblk)
4392 hole_len -= map->m_lblk - hole_start;
4393 map->m_pblk = 0;
4394 map->m_len = min_t(unsigned int, map->m_len, hole_len);
4395
a86c6181
AT
4396 goto out2;
4397 }
4d33b1ef 4398
a86c6181 4399 /*
c2ea3fde 4400 * Okay, we need to do block allocation.
63f57933 4401 */
4d33b1ef 4402 newex.ee_block = cpu_to_le32(map->m_lblk);
d0abafac 4403 cluster_offset = EXT4_LBLK_COFF(sbi, map->m_lblk);
4d33b1ef
TT
4404
4405 /*
4406 * If we are doing bigalloc, check to see if the extent returned
ed8a1a76 4407 * by ext4_find_extent() implies a cluster we can use.
4d33b1ef
TT
4408 */
4409 if (cluster_offset && ex &&
d8990240 4410 get_implied_cluster_alloc(inode->i_sb, map, ex, path)) {
4d33b1ef
TT
4411 ar.len = allocated = map->m_len;
4412 newblock = map->m_pblk;
cbd7584e 4413 map_from_cluster = true;
4d33b1ef
TT
4414 goto got_allocated_blocks;
4415 }
a86c6181 4416
c9de560d 4417 /* find neighbour allocated blocks */
e35fd660 4418 ar.lleft = map->m_lblk;
c9de560d
AT
4419 err = ext4_ext_search_left(inode, path, &ar.lleft, &ar.pleft);
4420 if (err)
4421 goto out2;
e35fd660 4422 ar.lright = map->m_lblk;
4d33b1ef
TT
4423 ex2 = NULL;
4424 err = ext4_ext_search_right(inode, path, &ar.lright, &ar.pright, &ex2);
c9de560d
AT
4425 if (err)
4426 goto out2;
25d14f98 4427
4d33b1ef
TT
4428 /* Check if the extent after searching to the right implies a
4429 * cluster we can use. */
4430 if ((sbi->s_cluster_ratio > 1) && ex2 &&
d8990240 4431 get_implied_cluster_alloc(inode->i_sb, map, ex2, path)) {
4d33b1ef
TT
4432 ar.len = allocated = map->m_len;
4433 newblock = map->m_pblk;
cbd7584e 4434 map_from_cluster = true;
4d33b1ef
TT
4435 goto got_allocated_blocks;
4436 }
4437
749269fa
AA
4438 /*
4439 * See if request is beyond maximum number of blocks we can have in
4440 * a single extent. For an initialized extent this limit is
556615dc
LC
4441 * EXT_INIT_MAX_LEN and for an unwritten extent this limit is
4442 * EXT_UNWRITTEN_MAX_LEN.
749269fa 4443 */
e35fd660 4444 if (map->m_len > EXT_INIT_MAX_LEN &&
556615dc 4445 !(flags & EXT4_GET_BLOCKS_UNWRIT_EXT))
e35fd660 4446 map->m_len = EXT_INIT_MAX_LEN;
556615dc
LC
4447 else if (map->m_len > EXT_UNWRITTEN_MAX_LEN &&
4448 (flags & EXT4_GET_BLOCKS_UNWRIT_EXT))
4449 map->m_len = EXT_UNWRITTEN_MAX_LEN;
749269fa 4450
e35fd660 4451 /* Check if we can really insert (m_lblk)::(m_lblk + m_len) extent */
e35fd660 4452 newex.ee_len = cpu_to_le16(map->m_len);
4d33b1ef 4453 err = ext4_ext_check_overlap(sbi, inode, &newex, path);
25d14f98 4454 if (err)
b939e376 4455 allocated = ext4_ext_get_actual_len(&newex);
25d14f98 4456 else
e35fd660 4457 allocated = map->m_len;
c9de560d
AT
4458
4459 /* allocate new block */
4460 ar.inode = inode;
e35fd660
TT
4461 ar.goal = ext4_ext_find_goal(inode, path, map->m_lblk);
4462 ar.logical = map->m_lblk;
4d33b1ef
TT
4463 /*
4464 * We calculate the offset from the beginning of the cluster
4465 * for the logical block number, since when we allocate a
4466 * physical cluster, the physical block should start at the
4467 * same offset from the beginning of the cluster. This is
4468 * needed so that future calls to get_implied_cluster_alloc()
4469 * work correctly.
4470 */
f5a44db5 4471 offset = EXT4_LBLK_COFF(sbi, map->m_lblk);
4d33b1ef
TT
4472 ar.len = EXT4_NUM_B2C(sbi, offset+allocated);
4473 ar.goal -= offset;
4474 ar.logical -= offset;
c9de560d
AT
4475 if (S_ISREG(inode->i_mode))
4476 ar.flags = EXT4_MB_HINT_DATA;
4477 else
4478 /* disable in-core preallocation for non-regular files */
4479 ar.flags = 0;
556b27ab
VH
4480 if (flags & EXT4_GET_BLOCKS_NO_NORMALIZE)
4481 ar.flags |= EXT4_MB_HINT_NOPREALLOC;
e3cf5d5d
TT
4482 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
4483 ar.flags |= EXT4_MB_DELALLOC_RESERVED;
c5e298ae
TT
4484 if (flags & EXT4_GET_BLOCKS_METADATA_NOFAIL)
4485 ar.flags |= EXT4_MB_USE_RESERVED;
c9de560d 4486 newblock = ext4_mb_new_blocks(handle, &ar, &err);
a86c6181
AT
4487 if (!newblock)
4488 goto out2;
84fe3bef 4489 ext_debug("allocate new block: goal %llu, found %llu/%u\n",
498e5f24 4490 ar.goal, newblock, allocated);
4d33b1ef 4491 free_on_err = 1;
7b415bf6 4492 allocated_clusters = ar.len;
4d33b1ef
TT
4493 ar.len = EXT4_C2B(sbi, ar.len) - offset;
4494 if (ar.len > allocated)
4495 ar.len = allocated;
a86c6181 4496
4d33b1ef 4497got_allocated_blocks:
a86c6181 4498 /* try to insert new extent into found leaf and return */
4d33b1ef 4499 ext4_ext_store_pblock(&newex, newblock + offset);
c9de560d 4500 newex.ee_len = cpu_to_le16(ar.len);
556615dc
LC
4501 /* Mark unwritten */
4502 if (flags & EXT4_GET_BLOCKS_UNWRIT_EXT){
4503 ext4_ext_mark_unwritten(&newex);
a25a4e1a 4504 map->m_flags |= EXT4_MAP_UNWRITTEN;
8d5d02e6 4505 }
c8d46e41 4506
a4e5d88b
DM
4507 err = 0;
4508 if ((flags & EXT4_GET_BLOCKS_KEEP_SIZE) == 0)
4509 err = check_eofblocks_fl(handle, inode, map->m_lblk,
4510 path, ar.len);
575a1d4b 4511 if (!err)
dfe50809 4512 err = ext4_ext_insert_extent(handle, inode, &path,
575a1d4b 4513 &newex, flags);
82e54229 4514
4d33b1ef 4515 if (err && free_on_err) {
7132de74
MP
4516 int fb_flags = flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE ?
4517 EXT4_FREE_BLOCKS_NO_QUOT_UPDATE : 0;
315054f0 4518 /* free data blocks we just allocated */
c9de560d
AT
4519 /* not a good idea to call discard here directly,
4520 * but otherwise we'd need to call it every free() */
c2ea3fde 4521 ext4_discard_preallocations(inode);
c8e15130
TT
4522 ext4_free_blocks(handle, inode, NULL, newblock,
4523 EXT4_C2B(sbi, allocated_clusters), fb_flags);
a86c6181 4524 goto out2;
315054f0 4525 }
a86c6181 4526
a86c6181 4527 /* previous routine could use block we allocated */
bf89d16f 4528 newblock = ext4_ext_pblock(&newex);
b939e376 4529 allocated = ext4_ext_get_actual_len(&newex);
e35fd660
TT
4530 if (allocated > map->m_len)
4531 allocated = map->m_len;
4532 map->m_flags |= EXT4_MAP_NEW;
a86c6181 4533
5f634d06
AK
4534 /*
4535 * Update reserved blocks/metadata blocks after successful
4536 * block allocation which had been deferred till now.
4537 */
7b415bf6 4538 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) {
81fdbb4a 4539 unsigned int reserved_clusters;
7b415bf6 4540 /*
81fdbb4a 4541 * Check how many clusters we had reserved this allocated range
7b415bf6
AK
4542 */
4543 reserved_clusters = get_reserved_cluster_alloc(inode,
4544 map->m_lblk, allocated);
9d21c9fa 4545 if (!map_from_cluster) {
7b415bf6 4546 BUG_ON(allocated_clusters < reserved_clusters);
7b415bf6 4547 if (reserved_clusters < allocated_clusters) {
5356f261 4548 struct ext4_inode_info *ei = EXT4_I(inode);
7b415bf6
AK
4549 int reservation = allocated_clusters -
4550 reserved_clusters;
4551 /*
4552 * It seems we claimed few clusters outside of
4553 * the range of this allocation. We should give
4554 * it back to the reservation pool. This can
4555 * happen in the following case:
4556 *
4557 * * Suppose s_cluster_ratio is 4 (i.e., each
4558 * cluster has 4 blocks. Thus, the clusters
4559 * are [0-3],[4-7],[8-11]...
4560 * * First comes delayed allocation write for
4561 * logical blocks 10 & 11. Since there were no
4562 * previous delayed allocated blocks in the
4563 * range [8-11], we would reserve 1 cluster
4564 * for this write.
4565 * * Next comes write for logical blocks 3 to 8.
4566 * In this case, we will reserve 2 clusters
4567 * (for [0-3] and [4-7]; and not for [8-11] as
4568 * that range has a delayed allocated blocks.
4569 * Thus total reserved clusters now becomes 3.
4570 * * Now, during the delayed allocation writeout
4571 * time, we will first write blocks [3-8] and
4572 * allocate 3 clusters for writing these
4573 * blocks. Also, we would claim all these
4574 * three clusters above.
4575 * * Now when we come here to writeout the
4576 * blocks [10-11], we would expect to claim
4577 * the reservation of 1 cluster we had made
4578 * (and we would claim it since there are no
4579 * more delayed allocated blocks in the range
4580 * [8-11]. But our reserved cluster count had
4581 * already gone to 0.
4582 *
4583 * Thus, at the step 4 above when we determine
4584 * that there are still some unwritten delayed
4585 * allocated blocks outside of our current
4586 * block range, we should increment the
4587 * reserved clusters count so that when the
4588 * remaining blocks finally gets written, we
4589 * could claim them.
4590 */
5356f261
AK
4591 dquot_reserve_block(inode,
4592 EXT4_C2B(sbi, reservation));
4593 spin_lock(&ei->i_block_reservation_lock);
4594 ei->i_reserved_data_blocks += reservation;
4595 spin_unlock(&ei->i_block_reservation_lock);
7b415bf6 4596 }
232ec872
LC
4597 /*
4598 * We will claim quota for all newly allocated blocks.
4599 * We're updating the reserved space *after* the
4600 * correction above so we do not accidentally free
4601 * all the metadata reservation because we might
4602 * actually need it later on.
4603 */
4604 ext4_da_update_reserve_space(inode, allocated_clusters,
4605 1);
7b415bf6
AK
4606 }
4607 }
5f634d06 4608
b436b9be
JK
4609 /*
4610 * Cache the extent and update transaction to commit on fdatasync only
556615dc 4611 * when it is _not_ an unwritten extent.
b436b9be 4612 */
556615dc 4613 if ((flags & EXT4_GET_BLOCKS_UNWRIT_EXT) == 0)
b436b9be 4614 ext4_update_inode_fsync_trans(handle, inode, 1);
69eb33dc 4615 else
b436b9be 4616 ext4_update_inode_fsync_trans(handle, inode, 0);
a86c6181 4617out:
e35fd660
TT
4618 if (allocated > map->m_len)
4619 allocated = map->m_len;
a86c6181 4620 ext4_ext_show_leaf(inode, path);
e35fd660
TT
4621 map->m_flags |= EXT4_MAP_MAPPED;
4622 map->m_pblk = newblock;
4623 map->m_len = allocated;
a86c6181 4624out2:
b7ea89ad
TT
4625 ext4_ext_drop_refs(path);
4626 kfree(path);
e861304b 4627
63b99968
TT
4628 trace_ext4_ext_map_blocks_exit(inode, flags, map,
4629 err ? err : allocated);
7877191c 4630 return err ? err : allocated;
a86c6181
AT
4631}
4632
819c4920 4633void ext4_ext_truncate(handle_t *handle, struct inode *inode)
a86c6181 4634{
a86c6181 4635 struct super_block *sb = inode->i_sb;
725d26d3 4636 ext4_lblk_t last_block;
a86c6181
AT
4637 int err = 0;
4638
a86c6181 4639 /*
d0d856e8
RD
4640 * TODO: optimization is possible here.
4641 * Probably we need not scan at all,
4642 * because page truncation is enough.
a86c6181 4643 */
a86c6181
AT
4644
4645 /* we have to know where to truncate from in crash case */
4646 EXT4_I(inode)->i_disksize = inode->i_size;
4647 ext4_mark_inode_dirty(handle, inode);
4648
4649 last_block = (inode->i_size + sb->s_blocksize - 1)
4650 >> EXT4_BLOCK_SIZE_BITS(sb);
8acd5e9b 4651retry:
51865fda
ZL
4652 err = ext4_es_remove_extent(inode, last_block,
4653 EXT_MAX_BLOCKS - last_block);
94eec0fc 4654 if (err == -ENOMEM) {
8acd5e9b
TT
4655 cond_resched();
4656 congestion_wait(BLK_RW_ASYNC, HZ/50);
4657 goto retry;
4658 }
4659 if (err) {
4660 ext4_std_error(inode->i_sb, err);
4661 return;
4662 }
5f95d21f 4663 err = ext4_ext_remove_space(inode, last_block, EXT_MAX_BLOCKS - 1);
8acd5e9b 4664 ext4_std_error(inode->i_sb, err);
a86c6181
AT
4665}
4666
0e8b6879 4667static int ext4_alloc_file_blocks(struct file *file, ext4_lblk_t offset,
c174e6d6
DM
4668 ext4_lblk_t len, loff_t new_size,
4669 int flags, int mode)
0e8b6879
LC
4670{
4671 struct inode *inode = file_inode(file);
4672 handle_t *handle;
4673 int ret = 0;
4674 int ret2 = 0;
4675 int retries = 0;
4134f5c8 4676 int depth = 0;
0e8b6879
LC
4677 struct ext4_map_blocks map;
4678 unsigned int credits;
c174e6d6 4679 loff_t epos;
0e8b6879
LC
4680
4681 map.m_lblk = offset;
c174e6d6 4682 map.m_len = len;
0e8b6879
LC
4683 /*
4684 * Don't normalize the request if it can fit in one extent so
4685 * that it doesn't get unnecessarily split into multiple
4686 * extents.
4687 */
556615dc 4688 if (len <= EXT_UNWRITTEN_MAX_LEN)
0e8b6879
LC
4689 flags |= EXT4_GET_BLOCKS_NO_NORMALIZE;
4690
4691 /*
4692 * credits to insert 1 extent into extent tree
4693 */
4694 credits = ext4_chunk_trans_blocks(inode, len);
4134f5c8
LC
4695 /*
4696 * We can only call ext_depth() on extent based inodes
4697 */
4698 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4699 depth = ext_depth(inode);
4700 else
4701 depth = -1;
0e8b6879
LC
4702
4703retry:
c174e6d6 4704 while (ret >= 0 && len) {
4134f5c8
LC
4705 /*
4706 * Recalculate credits when extent tree depth changes.
4707 */
4708 if (depth >= 0 && depth != ext_depth(inode)) {
4709 credits = ext4_chunk_trans_blocks(inode, len);
4710 depth = ext_depth(inode);
4711 }
4712
0e8b6879
LC
4713 handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS,
4714 credits);
4715 if (IS_ERR(handle)) {
4716 ret = PTR_ERR(handle);
4717 break;
4718 }
4719 ret = ext4_map_blocks(handle, inode, &map, flags);
4720 if (ret <= 0) {
4721 ext4_debug("inode #%lu: block %u: len %u: "
4722 "ext4_ext_map_blocks returned %d",
4723 inode->i_ino, map.m_lblk,
4724 map.m_len, ret);
4725 ext4_mark_inode_dirty(handle, inode);
4726 ret2 = ext4_journal_stop(handle);
4727 break;
4728 }
c174e6d6
DM
4729 map.m_lblk += ret;
4730 map.m_len = len = len - ret;
4731 epos = (loff_t)map.m_lblk << inode->i_blkbits;
4732 inode->i_ctime = ext4_current_time(inode);
4733 if (new_size) {
4734 if (epos > new_size)
4735 epos = new_size;
4736 if (ext4_update_inode_size(inode, epos) & 0x1)
4737 inode->i_mtime = inode->i_ctime;
4738 } else {
4739 if (epos > inode->i_size)
4740 ext4_set_inode_flag(inode,
4741 EXT4_INODE_EOFBLOCKS);
4742 }
4743 ext4_mark_inode_dirty(handle, inode);
0e8b6879
LC
4744 ret2 = ext4_journal_stop(handle);
4745 if (ret2)
4746 break;
4747 }
4748 if (ret == -ENOSPC &&
4749 ext4_should_retry_alloc(inode->i_sb, &retries)) {
4750 ret = 0;
4751 goto retry;
4752 }
4753
4754 return ret > 0 ? ret2 : ret;
4755}
4756
b8a86845
LC
4757static long ext4_zero_range(struct file *file, loff_t offset,
4758 loff_t len, int mode)
4759{
4760 struct inode *inode = file_inode(file);
4761 handle_t *handle = NULL;
4762 unsigned int max_blocks;
4763 loff_t new_size = 0;
4764 int ret = 0;
4765 int flags;
69dc9536 4766 int credits;
c174e6d6 4767 int partial_begin, partial_end;
b8a86845
LC
4768 loff_t start, end;
4769 ext4_lblk_t lblk;
b8a86845
LC
4770 unsigned int blkbits = inode->i_blkbits;
4771
4772 trace_ext4_zero_range(inode, offset, len, mode);
4773
6c5e73d3 4774 if (!S_ISREG(inode->i_mode))
4775 return -EINVAL;
4776
e1ee60fd
NJ
4777 /* Call ext4_force_commit to flush all data in case of data=journal. */
4778 if (ext4_should_journal_data(inode)) {
4779 ret = ext4_force_commit(inode->i_sb);
4780 if (ret)
4781 return ret;
4782 }
4783
b8a86845
LC
4784 /*
4785 * Round up offset. This is not fallocate, we neet to zero out
4786 * blocks, so convert interior block aligned part of the range to
4787 * unwritten and possibly manually zero out unaligned parts of the
4788 * range.
4789 */
4790 start = round_up(offset, 1 << blkbits);
4791 end = round_down((offset + len), 1 << blkbits);
4792
4793 if (start < offset || end > offset + len)
4794 return -EINVAL;
c174e6d6
DM
4795 partial_begin = offset & ((1 << blkbits) - 1);
4796 partial_end = (offset + len) & ((1 << blkbits) - 1);
b8a86845
LC
4797
4798 lblk = start >> blkbits;
4799 max_blocks = (end >> blkbits);
4800 if (max_blocks < lblk)
4801 max_blocks = 0;
4802 else
4803 max_blocks -= lblk;
4804
5955102c 4805 inode_lock(inode);
b8a86845
LC
4806
4807 /*
4808 * Indirect files do not support unwritten extnets
4809 */
4810 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
4811 ret = -EOPNOTSUPP;
4812 goto out_mutex;
4813 }
4814
4815 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
4816 offset + len > i_size_read(inode)) {
4817 new_size = offset + len;
4818 ret = inode_newsize_ok(inode, new_size);
4819 if (ret)
4820 goto out_mutex;
b8a86845
LC
4821 }
4822
0f2af21a
LC
4823 flags = EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT;
4824 if (mode & FALLOC_FL_KEEP_SIZE)
4825 flags |= EXT4_GET_BLOCKS_KEEP_SIZE;
4826
17048e8a
JK
4827 /* Wait all existing dio workers, newcomers will block on i_mutex */
4828 ext4_inode_block_unlocked_dio(inode);
4829 inode_dio_wait(inode);
4830
0f2af21a
LC
4831 /* Preallocate the range including the unaligned edges */
4832 if (partial_begin || partial_end) {
4833 ret = ext4_alloc_file_blocks(file,
4834 round_down(offset, 1 << blkbits) >> blkbits,
4835 (round_up((offset + len), 1 << blkbits) -
4836 round_down(offset, 1 << blkbits)) >> blkbits,
4837 new_size, flags, mode);
4838 if (ret)
17048e8a 4839 goto out_dio;
0f2af21a
LC
4840
4841 }
4842
4843 /* Zero range excluding the unaligned edges */
b8a86845 4844 if (max_blocks > 0) {
0f2af21a
LC
4845 flags |= (EXT4_GET_BLOCKS_CONVERT_UNWRITTEN |
4846 EXT4_EX_NOCACHE);
b8a86845 4847
ea3d7209
JK
4848 /*
4849 * Prevent page faults from reinstantiating pages we have
4850 * released from page cache.
4851 */
4852 down_write(&EXT4_I(inode)->i_mmap_sem);
01127848
JK
4853 ret = ext4_update_disksize_before_punch(inode, offset, len);
4854 if (ret) {
4855 up_write(&EXT4_I(inode)->i_mmap_sem);
4856 goto out_dio;
4857 }
ea3d7209
JK
4858 /* Now release the pages and zero block aligned part of pages */
4859 truncate_pagecache_range(inode, start, end - 1);
4860 inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
4861
713e8dde
TT
4862 ret = ext4_alloc_file_blocks(file, lblk, max_blocks, new_size,
4863 flags, mode);
ea3d7209 4864 up_write(&EXT4_I(inode)->i_mmap_sem);
713e8dde
TT
4865 if (ret)
4866 goto out_dio;
b8a86845 4867 }
c174e6d6
DM
4868 if (!partial_begin && !partial_end)
4869 goto out_dio;
4870
69dc9536
DM
4871 /*
4872 * In worst case we have to writeout two nonadjacent unwritten
4873 * blocks and update the inode
4874 */
4875 credits = (2 * ext4_ext_index_trans_blocks(inode, 2)) + 1;
4876 if (ext4_should_journal_data(inode))
4877 credits += 2;
4878 handle = ext4_journal_start(inode, EXT4_HT_MISC, credits);
b8a86845
LC
4879 if (IS_ERR(handle)) {
4880 ret = PTR_ERR(handle);
4881 ext4_std_error(inode->i_sb, ret);
4882 goto out_dio;
4883 }
4884
4885 inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
e5b30416 4886 if (new_size) {
4631dbf6 4887 ext4_update_inode_size(inode, new_size);
e5b30416 4888 } else {
b8a86845
LC
4889 /*
4890 * Mark that we allocate beyond EOF so the subsequent truncate
4891 * can proceed even if the new size is the same as i_size.
4892 */
4893 if ((offset + len) > i_size_read(inode))
4894 ext4_set_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
4895 }
b8a86845
LC
4896 ext4_mark_inode_dirty(handle, inode);
4897
4898 /* Zero out partial block at the edges of the range */
4899 ret = ext4_zero_partial_blocks(handle, inode, offset, len);
4900
4901 if (file->f_flags & O_SYNC)
4902 ext4_handle_sync(handle);
4903
4904 ext4_journal_stop(handle);
4905out_dio:
4906 ext4_inode_resume_unlocked_dio(inode);
4907out_mutex:
5955102c 4908 inode_unlock(inode);
b8a86845
LC
4909 return ret;
4910}
4911
a2df2a63 4912/*
2fe17c10 4913 * preallocate space for a file. This implements ext4's fallocate file
a2df2a63
AA
4914 * operation, which gets called from sys_fallocate system call.
4915 * For block-mapped files, posix_fallocate should fall back to the method
4916 * of writing zeroes to the required new blocks (the same behavior which is
4917 * expected for file systems which do not support fallocate() system call).
4918 */
2fe17c10 4919long ext4_fallocate(struct file *file, int mode, loff_t offset, loff_t len)
a2df2a63 4920{
496ad9aa 4921 struct inode *inode = file_inode(file);
f282ac19 4922 loff_t new_size = 0;
498e5f24 4923 unsigned int max_blocks;
a2df2a63 4924 int ret = 0;
a4e5d88b 4925 int flags;
0e8b6879 4926 ext4_lblk_t lblk;
0e8b6879 4927 unsigned int blkbits = inode->i_blkbits;
a2df2a63 4928
2058f83a
MH
4929 /*
4930 * Encrypted inodes can't handle collapse range or insert
4931 * range since we would need to re-encrypt blocks with a
4932 * different IV or XTS tweak (which are based on the logical
4933 * block number).
4934 *
4935 * XXX It's not clear why zero range isn't working, but we'll
4936 * leave it disabled for encrypted inodes for now. This is a
4937 * bug we should fix....
4938 */
4939 if (ext4_encrypted_inode(inode) &&
331573fe
NJ
4940 (mode & (FALLOC_FL_COLLAPSE_RANGE | FALLOC_FL_INSERT_RANGE |
4941 FALLOC_FL_ZERO_RANGE)))
2058f83a
MH
4942 return -EOPNOTSUPP;
4943
a4bb6b64 4944 /* Return error if mode is not supported */
9eb79482 4945 if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE |
331573fe
NJ
4946 FALLOC_FL_COLLAPSE_RANGE | FALLOC_FL_ZERO_RANGE |
4947 FALLOC_FL_INSERT_RANGE))
a4bb6b64
AH
4948 return -EOPNOTSUPP;
4949
4950 if (mode & FALLOC_FL_PUNCH_HOLE)
aeb2817a 4951 return ext4_punch_hole(inode, offset, len);
a4bb6b64 4952
0c8d414f
TM
4953 ret = ext4_convert_inline_data(inode);
4954 if (ret)
4955 return ret;
4956
40c406c7
TT
4957 if (mode & FALLOC_FL_COLLAPSE_RANGE)
4958 return ext4_collapse_range(inode, offset, len);
4959
331573fe
NJ
4960 if (mode & FALLOC_FL_INSERT_RANGE)
4961 return ext4_insert_range(inode, offset, len);
4962
b8a86845
LC
4963 if (mode & FALLOC_FL_ZERO_RANGE)
4964 return ext4_zero_range(file, offset, len, mode);
4965
0562e0ba 4966 trace_ext4_fallocate_enter(inode, offset, len, mode);
0e8b6879 4967 lblk = offset >> blkbits;
fd28784a
AK
4968 /*
4969 * We can't just convert len to max_blocks because
4970 * If blocksize = 4096 offset = 3072 and len = 2048
4971 */
a2df2a63 4972 max_blocks = (EXT4_BLOCK_ALIGN(len + offset, blkbits) >> blkbits)
0e8b6879
LC
4973 - lblk;
4974
556615dc 4975 flags = EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT;
0e8b6879
LC
4976 if (mode & FALLOC_FL_KEEP_SIZE)
4977 flags |= EXT4_GET_BLOCKS_KEEP_SIZE;
4978
5955102c 4979 inode_lock(inode);
f282ac19 4980
280227a7
DI
4981 /*
4982 * We only support preallocation for extent-based files only
4983 */
4984 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
4985 ret = -EOPNOTSUPP;
4986 goto out;
4987 }
4988
f282ac19
LC
4989 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
4990 offset + len > i_size_read(inode)) {
4991 new_size = offset + len;
4992 ret = inode_newsize_ok(inode, new_size);
4993 if (ret)
4994 goto out;
6d19c42b 4995 }
f282ac19 4996
17048e8a
JK
4997 /* Wait all existing dio workers, newcomers will block on i_mutex */
4998 ext4_inode_block_unlocked_dio(inode);
4999 inode_dio_wait(inode);
5000
c174e6d6
DM
5001 ret = ext4_alloc_file_blocks(file, lblk, max_blocks, new_size,
5002 flags, mode);
17048e8a 5003 ext4_inode_resume_unlocked_dio(inode);
0e8b6879
LC
5004 if (ret)
5005 goto out;
f282ac19 5006
c174e6d6
DM
5007 if (file->f_flags & O_SYNC && EXT4_SB(inode->i_sb)->s_journal) {
5008 ret = jbd2_complete_transaction(EXT4_SB(inode->i_sb)->s_journal,
5009 EXT4_I(inode)->i_sync_tid);
f282ac19 5010 }
f282ac19 5011out:
5955102c 5012 inode_unlock(inode);
0e8b6879
LC
5013 trace_ext4_fallocate_exit(inode, offset, max_blocks, ret);
5014 return ret;
a2df2a63 5015}
6873fa0d 5016
0031462b
MC
5017/*
5018 * This function convert a range of blocks to written extents
5019 * The caller of this function will pass the start offset and the size.
5020 * all unwritten extents within this range will be converted to
5021 * written extents.
5022 *
5023 * This function is called from the direct IO end io call back
5024 * function, to convert the fallocated extents after IO is completed.
109f5565 5025 * Returns 0 on success.
0031462b 5026 */
6b523df4
JK
5027int ext4_convert_unwritten_extents(handle_t *handle, struct inode *inode,
5028 loff_t offset, ssize_t len)
0031462b 5029{
0031462b
MC
5030 unsigned int max_blocks;
5031 int ret = 0;
5032 int ret2 = 0;
2ed88685 5033 struct ext4_map_blocks map;
0031462b
MC
5034 unsigned int credits, blkbits = inode->i_blkbits;
5035
2ed88685 5036 map.m_lblk = offset >> blkbits;
0031462b
MC
5037 /*
5038 * We can't just convert len to max_blocks because
5039 * If blocksize = 4096 offset = 3072 and len = 2048
5040 */
2ed88685
TT
5041 max_blocks = ((EXT4_BLOCK_ALIGN(len + offset, blkbits) >> blkbits) -
5042 map.m_lblk);
0031462b 5043 /*
6b523df4
JK
5044 * This is somewhat ugly but the idea is clear: When transaction is
5045 * reserved, everything goes into it. Otherwise we rather start several
5046 * smaller transactions for conversion of each extent separately.
0031462b 5047 */
6b523df4
JK
5048 if (handle) {
5049 handle = ext4_journal_start_reserved(handle,
5050 EXT4_HT_EXT_CONVERT);
5051 if (IS_ERR(handle))
5052 return PTR_ERR(handle);
5053 credits = 0;
5054 } else {
5055 /*
5056 * credits to insert 1 extent into extent tree
5057 */
5058 credits = ext4_chunk_trans_blocks(inode, max_blocks);
5059 }
0031462b 5060 while (ret >= 0 && ret < max_blocks) {
2ed88685
TT
5061 map.m_lblk += ret;
5062 map.m_len = (max_blocks -= ret);
6b523df4
JK
5063 if (credits) {
5064 handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS,
5065 credits);
5066 if (IS_ERR(handle)) {
5067 ret = PTR_ERR(handle);
5068 break;
5069 }
0031462b 5070 }
2ed88685 5071 ret = ext4_map_blocks(handle, inode, &map,
c7064ef1 5072 EXT4_GET_BLOCKS_IO_CONVERT_EXT);
b06acd38
LC
5073 if (ret <= 0)
5074 ext4_warning(inode->i_sb,
5075 "inode #%lu: block %u: len %u: "
5076 "ext4_ext_map_blocks returned %d",
5077 inode->i_ino, map.m_lblk,
5078 map.m_len, ret);
0031462b 5079 ext4_mark_inode_dirty(handle, inode);
6b523df4
JK
5080 if (credits)
5081 ret2 = ext4_journal_stop(handle);
5082 if (ret <= 0 || ret2)
0031462b
MC
5083 break;
5084 }
6b523df4
JK
5085 if (!credits)
5086 ret2 = ext4_journal_stop(handle);
0031462b
MC
5087 return ret > 0 ? ret2 : ret;
5088}
6d9c85eb 5089
6873fa0d 5090/*
69eb33dc
ZL
5091 * If newes is not existing extent (newes->ec_pblk equals zero) find
5092 * delayed extent at start of newes and update newes accordingly and
91dd8c11
LC
5093 * return start of the next delayed extent.
5094 *
69eb33dc 5095 * If newes is existing extent (newes->ec_pblk is not equal zero)
91dd8c11 5096 * return start of next delayed extent or EXT_MAX_BLOCKS if no delayed
69eb33dc 5097 * extent found. Leave newes unmodified.
6873fa0d 5098 */
91dd8c11 5099static int ext4_find_delayed_extent(struct inode *inode,
69eb33dc 5100 struct extent_status *newes)
6873fa0d 5101{
b3aff3e3 5102 struct extent_status es;
be401363 5103 ext4_lblk_t block, next_del;
6873fa0d 5104
69eb33dc 5105 if (newes->es_pblk == 0) {
e30b5dca
YZ
5106 ext4_es_find_delayed_extent_range(inode, newes->es_lblk,
5107 newes->es_lblk + newes->es_len - 1, &es);
5108
6d9c85eb 5109 /*
69eb33dc 5110 * No extent in extent-tree contains block @newes->es_pblk,
6d9c85eb 5111 * then the block may stay in 1)a hole or 2)delayed-extent.
6d9c85eb 5112 */
06b0c886 5113 if (es.es_len == 0)
b3aff3e3 5114 /* A hole found. */
91dd8c11 5115 return 0;
b3aff3e3 5116
69eb33dc 5117 if (es.es_lblk > newes->es_lblk) {
b3aff3e3 5118 /* A hole found. */
69eb33dc
ZL
5119 newes->es_len = min(es.es_lblk - newes->es_lblk,
5120 newes->es_len);
91dd8c11 5121 return 0;
6873fa0d 5122 }
6d9c85eb 5123
69eb33dc 5124 newes->es_len = es.es_lblk + es.es_len - newes->es_lblk;
6873fa0d
ES
5125 }
5126
69eb33dc 5127 block = newes->es_lblk + newes->es_len;
e30b5dca 5128 ext4_es_find_delayed_extent_range(inode, block, EXT_MAX_BLOCKS, &es);
be401363
ZL
5129 if (es.es_len == 0)
5130 next_del = EXT_MAX_BLOCKS;
5131 else
5132 next_del = es.es_lblk;
5133
91dd8c11 5134 return next_del;
6873fa0d 5135}
6873fa0d
ES
5136/* fiemap flags we can handle specified here */
5137#define EXT4_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC|FIEMAP_FLAG_XATTR)
5138
3a06d778
AK
5139static int ext4_xattr_fiemap(struct inode *inode,
5140 struct fiemap_extent_info *fieinfo)
6873fa0d
ES
5141{
5142 __u64 physical = 0;
5143 __u64 length;
5144 __u32 flags = FIEMAP_EXTENT_LAST;
5145 int blockbits = inode->i_sb->s_blocksize_bits;
5146 int error = 0;
5147
5148 /* in-inode? */
19f5fb7a 5149 if (ext4_test_inode_state(inode, EXT4_STATE_XATTR)) {
6873fa0d
ES
5150 struct ext4_iloc iloc;
5151 int offset; /* offset of xattr in inode */
5152
5153 error = ext4_get_inode_loc(inode, &iloc);
5154 if (error)
5155 return error;
a60697f4 5156 physical = (__u64)iloc.bh->b_blocknr << blockbits;
6873fa0d
ES
5157 offset = EXT4_GOOD_OLD_INODE_SIZE +
5158 EXT4_I(inode)->i_extra_isize;
5159 physical += offset;
5160 length = EXT4_SB(inode->i_sb)->s_inode_size - offset;
5161 flags |= FIEMAP_EXTENT_DATA_INLINE;
fd2dd9fb 5162 brelse(iloc.bh);
6873fa0d 5163 } else { /* external block */
a60697f4 5164 physical = (__u64)EXT4_I(inode)->i_file_acl << blockbits;
6873fa0d
ES
5165 length = inode->i_sb->s_blocksize;
5166 }
5167
5168 if (physical)
5169 error = fiemap_fill_next_extent(fieinfo, 0, physical,
5170 length, flags);
5171 return (error < 0 ? error : 0);
5172}
5173
5174int ext4_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
5175 __u64 start, __u64 len)
5176{
5177 ext4_lblk_t start_blk;
6873fa0d
ES
5178 int error = 0;
5179
94191985
TM
5180 if (ext4_has_inline_data(inode)) {
5181 int has_inline = 1;
5182
d952d69e
DM
5183 error = ext4_inline_data_fiemap(inode, fieinfo, &has_inline,
5184 start, len);
94191985
TM
5185
5186 if (has_inline)
5187 return error;
5188 }
5189
7869a4a6
TT
5190 if (fieinfo->fi_flags & FIEMAP_FLAG_CACHE) {
5191 error = ext4_ext_precache(inode);
5192 if (error)
5193 return error;
5194 }
5195
6873fa0d 5196 /* fallback to generic here if not in extents fmt */
12e9b892 5197 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
ad7fefb1
TT
5198 return generic_block_fiemap(inode, fieinfo, start, len,
5199 ext4_get_block);
6873fa0d
ES
5200
5201 if (fiemap_check_flags(fieinfo, EXT4_FIEMAP_FLAGS))
5202 return -EBADR;
5203
5204 if (fieinfo->fi_flags & FIEMAP_FLAG_XATTR) {
5205 error = ext4_xattr_fiemap(inode, fieinfo);
5206 } else {
aca92ff6
LM
5207 ext4_lblk_t len_blks;
5208 __u64 last_blk;
5209
6873fa0d 5210 start_blk = start >> inode->i_sb->s_blocksize_bits;
aca92ff6 5211 last_blk = (start + len - 1) >> inode->i_sb->s_blocksize_bits;
f17722f9
LC
5212 if (last_blk >= EXT_MAX_BLOCKS)
5213 last_blk = EXT_MAX_BLOCKS-1;
aca92ff6 5214 len_blks = ((ext4_lblk_t) last_blk) - start_blk + 1;
6873fa0d
ES
5215
5216 /*
91dd8c11
LC
5217 * Walk the extent tree gathering extent information
5218 * and pushing extents back to the user.
6873fa0d 5219 */
91dd8c11
LC
5220 error = ext4_fill_fiemap_extents(inode, start_blk,
5221 len_blks, fieinfo);
6873fa0d 5222 }
6873fa0d
ES
5223 return error;
5224}
9eb79482
NJ
5225
5226/*
5227 * ext4_access_path:
5228 * Function to access the path buffer for marking it dirty.
5229 * It also checks if there are sufficient credits left in the journal handle
5230 * to update path.
5231 */
5232static int
5233ext4_access_path(handle_t *handle, struct inode *inode,
5234 struct ext4_ext_path *path)
5235{
5236 int credits, err;
5237
5238 if (!ext4_handle_valid(handle))
5239 return 0;
5240
5241 /*
5242 * Check if need to extend journal credits
5243 * 3 for leaf, sb, and inode plus 2 (bmap and group
5244 * descriptor) for each block group; assume two block
5245 * groups
5246 */
5247 if (handle->h_buffer_credits < 7) {
5248 credits = ext4_writepage_trans_blocks(inode);
5249 err = ext4_ext_truncate_extend_restart(handle, inode, credits);
5250 /* EAGAIN is success */
5251 if (err && err != -EAGAIN)
5252 return err;
5253 }
5254
5255 err = ext4_ext_get_access(handle, inode, path);
5256 return err;
5257}
5258
5259/*
5260 * ext4_ext_shift_path_extents:
5261 * Shift the extents of a path structure lying between path[depth].p_ext
331573fe
NJ
5262 * and EXT_LAST_EXTENT(path[depth].p_hdr), by @shift blocks. @SHIFT tells
5263 * if it is right shift or left shift operation.
9eb79482
NJ
5264 */
5265static int
5266ext4_ext_shift_path_extents(struct ext4_ext_path *path, ext4_lblk_t shift,
5267 struct inode *inode, handle_t *handle,
331573fe 5268 enum SHIFT_DIRECTION SHIFT)
9eb79482
NJ
5269{
5270 int depth, err = 0;
5271 struct ext4_extent *ex_start, *ex_last;
5272 bool update = 0;
5273 depth = path->p_depth;
5274
5275 while (depth >= 0) {
5276 if (depth == path->p_depth) {
5277 ex_start = path[depth].p_ext;
5278 if (!ex_start)
6a797d27 5279 return -EFSCORRUPTED;
9eb79482
NJ
5280
5281 ex_last = EXT_LAST_EXTENT(path[depth].p_hdr);
9eb79482
NJ
5282
5283 err = ext4_access_path(handle, inode, path + depth);
5284 if (err)
5285 goto out;
5286
5287 if (ex_start == EXT_FIRST_EXTENT(path[depth].p_hdr))
5288 update = 1;
5289
9eb79482 5290 while (ex_start <= ex_last) {
331573fe
NJ
5291 if (SHIFT == SHIFT_LEFT) {
5292 le32_add_cpu(&ex_start->ee_block,
5293 -shift);
5294 /* Try to merge to the left. */
5295 if ((ex_start >
5296 EXT_FIRST_EXTENT(path[depth].p_hdr))
5297 &&
5298 ext4_ext_try_to_merge_right(inode,
5299 path, ex_start - 1))
5300 ex_last--;
5301 else
5302 ex_start++;
5303 } else {
5304 le32_add_cpu(&ex_last->ee_block, shift);
5305 ext4_ext_try_to_merge_right(inode, path,
5306 ex_last);
6dd834ef 5307 ex_last--;
331573fe 5308 }
9eb79482
NJ
5309 }
5310 err = ext4_ext_dirty(handle, inode, path + depth);
5311 if (err)
5312 goto out;
5313
5314 if (--depth < 0 || !update)
5315 break;
5316 }
5317
5318 /* Update index too */
5319 err = ext4_access_path(handle, inode, path + depth);
5320 if (err)
5321 goto out;
5322
331573fe
NJ
5323 if (SHIFT == SHIFT_LEFT)
5324 le32_add_cpu(&path[depth].p_idx->ei_block, -shift);
5325 else
5326 le32_add_cpu(&path[depth].p_idx->ei_block, shift);
9eb79482
NJ
5327 err = ext4_ext_dirty(handle, inode, path + depth);
5328 if (err)
5329 goto out;
5330
5331 /* we are done if current index is not a starting index */
5332 if (path[depth].p_idx != EXT_FIRST_INDEX(path[depth].p_hdr))
5333 break;
5334
5335 depth--;
5336 }
5337
5338out:
5339 return err;
5340}
5341
5342/*
5343 * ext4_ext_shift_extents:
331573fe
NJ
5344 * All the extents which lies in the range from @start to the last allocated
5345 * block for the @inode are shifted either towards left or right (depending
5346 * upon @SHIFT) by @shift blocks.
9eb79482
NJ
5347 * On success, 0 is returned, error otherwise.
5348 */
5349static int
5350ext4_ext_shift_extents(struct inode *inode, handle_t *handle,
331573fe
NJ
5351 ext4_lblk_t start, ext4_lblk_t shift,
5352 enum SHIFT_DIRECTION SHIFT)
9eb79482
NJ
5353{
5354 struct ext4_ext_path *path;
5355 int ret = 0, depth;
5356 struct ext4_extent *extent;
331573fe 5357 ext4_lblk_t stop, *iterator, ex_start, ex_end;
9eb79482
NJ
5358
5359 /* Let path point to the last extent */
ed8a1a76 5360 path = ext4_find_extent(inode, EXT_MAX_BLOCKS - 1, NULL, 0);
9eb79482
NJ
5361 if (IS_ERR(path))
5362 return PTR_ERR(path);
5363
5364 depth = path->p_depth;
5365 extent = path[depth].p_ext;
ee4bd0d9
TT
5366 if (!extent)
5367 goto out;
9eb79482 5368
331573fe 5369 stop = le32_to_cpu(extent->ee_block) +
847c6c42 5370 ext4_ext_get_actual_len(extent);
9eb79482 5371
331573fe
NJ
5372 /*
5373 * In case of left shift, Don't start shifting extents until we make
5374 * sure the hole is big enough to accommodate the shift.
5375 */
5376 if (SHIFT == SHIFT_LEFT) {
5377 path = ext4_find_extent(inode, start - 1, &path, 0);
5378 if (IS_ERR(path))
5379 return PTR_ERR(path);
5380 depth = path->p_depth;
5381 extent = path[depth].p_ext;
5382 if (extent) {
5383 ex_start = le32_to_cpu(extent->ee_block);
5384 ex_end = le32_to_cpu(extent->ee_block) +
5385 ext4_ext_get_actual_len(extent);
5386 } else {
5387 ex_start = 0;
5388 ex_end = 0;
5389 }
9eb79482 5390
331573fe
NJ
5391 if ((start == ex_start && shift > ex_start) ||
5392 (shift > start - ex_end)) {
5393 ext4_ext_drop_refs(path);
5394 kfree(path);
5395 return -EINVAL;
5396 }
8dc79ec4 5397 }
9eb79482 5398
331573fe
NJ
5399 /*
5400 * In case of left shift, iterator points to start and it is increased
5401 * till we reach stop. In case of right shift, iterator points to stop
5402 * and it is decreased till we reach start.
5403 */
5404 if (SHIFT == SHIFT_LEFT)
5405 iterator = &start;
5406 else
5407 iterator = &stop;
9eb79482
NJ
5408
5409 /* Its safe to start updating extents */
331573fe
NJ
5410 while (start < stop) {
5411 path = ext4_find_extent(inode, *iterator, &path, 0);
9eb79482
NJ
5412 if (IS_ERR(path))
5413 return PTR_ERR(path);
5414 depth = path->p_depth;
5415 extent = path[depth].p_ext;
a18ed359
DM
5416 if (!extent) {
5417 EXT4_ERROR_INODE(inode, "unexpected hole at %lu",
331573fe 5418 (unsigned long) *iterator);
6a797d27 5419 return -EFSCORRUPTED;
a18ed359 5420 }
331573fe
NJ
5421 if (SHIFT == SHIFT_LEFT && *iterator >
5422 le32_to_cpu(extent->ee_block)) {
9eb79482 5423 /* Hole, move to the next extent */
f8fb4f41
DM
5424 if (extent < EXT_LAST_EXTENT(path[depth].p_hdr)) {
5425 path[depth].p_ext++;
5426 } else {
331573fe 5427 *iterator = ext4_ext_next_allocated_block(path);
f8fb4f41 5428 continue;
9eb79482
NJ
5429 }
5430 }
331573fe
NJ
5431
5432 if (SHIFT == SHIFT_LEFT) {
5433 extent = EXT_LAST_EXTENT(path[depth].p_hdr);
5434 *iterator = le32_to_cpu(extent->ee_block) +
5435 ext4_ext_get_actual_len(extent);
5436 } else {
5437 extent = EXT_FIRST_EXTENT(path[depth].p_hdr);
5438 *iterator = le32_to_cpu(extent->ee_block) > 0 ?
5439 le32_to_cpu(extent->ee_block) - 1 : 0;
5440 /* Update path extent in case we need to stop */
5441 while (le32_to_cpu(extent->ee_block) < start)
5442 extent++;
5443 path[depth].p_ext = extent;
5444 }
9eb79482 5445 ret = ext4_ext_shift_path_extents(path, shift, inode,
331573fe 5446 handle, SHIFT);
9eb79482
NJ
5447 if (ret)
5448 break;
5449 }
ee4bd0d9
TT
5450out:
5451 ext4_ext_drop_refs(path);
5452 kfree(path);
9eb79482
NJ
5453 return ret;
5454}
5455
5456/*
5457 * ext4_collapse_range:
5458 * This implements the fallocate's collapse range functionality for ext4
5459 * Returns: 0 and non-zero on error.
5460 */
5461int ext4_collapse_range(struct inode *inode, loff_t offset, loff_t len)
5462{
5463 struct super_block *sb = inode->i_sb;
5464 ext4_lblk_t punch_start, punch_stop;
5465 handle_t *handle;
5466 unsigned int credits;
a8680e0d 5467 loff_t new_size, ioffset;
9eb79482
NJ
5468 int ret;
5469
b9576fc3
TT
5470 /*
5471 * We need to test this early because xfstests assumes that a
5472 * collapse range of (0, 1) will return EOPNOTSUPP if the file
5473 * system does not support collapse range.
5474 */
5475 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
5476 return -EOPNOTSUPP;
5477
9eb79482 5478 /* Collapse range works only on fs block size aligned offsets. */
ee98fa3a
NJ
5479 if (offset & (EXT4_CLUSTER_SIZE(sb) - 1) ||
5480 len & (EXT4_CLUSTER_SIZE(sb) - 1))
9eb79482
NJ
5481 return -EINVAL;
5482
5483 if (!S_ISREG(inode->i_mode))
86f1ca38 5484 return -EINVAL;
9eb79482
NJ
5485
5486 trace_ext4_collapse_range(inode, offset, len);
5487
5488 punch_start = offset >> EXT4_BLOCK_SIZE_BITS(sb);
5489 punch_stop = (offset + len) >> EXT4_BLOCK_SIZE_BITS(sb);
5490
1ce01c4a
NJ
5491 /* Call ext4_force_commit to flush all data in case of data=journal. */
5492 if (ext4_should_journal_data(inode)) {
5493 ret = ext4_force_commit(inode->i_sb);
5494 if (ret)
5495 return ret;
5496 }
5497
5955102c 5498 inode_lock(inode);
23fffa92
LC
5499 /*
5500 * There is no need to overlap collapse range with EOF, in which case
5501 * it is effectively a truncate operation
5502 */
5503 if (offset + len >= i_size_read(inode)) {
5504 ret = -EINVAL;
5505 goto out_mutex;
5506 }
5507
9eb79482
NJ
5508 /* Currently just for extent based files */
5509 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
5510 ret = -EOPNOTSUPP;
5511 goto out_mutex;
5512 }
5513
9eb79482
NJ
5514 /* Wait for existing dio to complete */
5515 ext4_inode_block_unlocked_dio(inode);
5516 inode_dio_wait(inode);
5517
ea3d7209
JK
5518 /*
5519 * Prevent page faults from reinstantiating pages we have released from
5520 * page cache.
5521 */
5522 down_write(&EXT4_I(inode)->i_mmap_sem);
32ebffd3
JK
5523 /*
5524 * Need to round down offset to be aligned with page size boundary
5525 * for page size > block size.
5526 */
5527 ioffset = round_down(offset, PAGE_SIZE);
5528 /*
5529 * Write tail of the last page before removed range since it will get
5530 * removed from the page cache below.
5531 */
5532 ret = filemap_write_and_wait_range(inode->i_mapping, ioffset, offset);
5533 if (ret)
5534 goto out_mmap;
5535 /*
5536 * Write data that will be shifted to preserve them when discarding
5537 * page cache below. We are also protected from pages becoming dirty
5538 * by i_mmap_sem.
5539 */
5540 ret = filemap_write_and_wait_range(inode->i_mapping, offset + len,
5541 LLONG_MAX);
5542 if (ret)
5543 goto out_mmap;
ea3d7209
JK
5544 truncate_pagecache(inode, ioffset);
5545
9eb79482
NJ
5546 credits = ext4_writepage_trans_blocks(inode);
5547 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
5548 if (IS_ERR(handle)) {
5549 ret = PTR_ERR(handle);
ea3d7209 5550 goto out_mmap;
9eb79482
NJ
5551 }
5552
5553 down_write(&EXT4_I(inode)->i_data_sem);
5554 ext4_discard_preallocations(inode);
5555
5556 ret = ext4_es_remove_extent(inode, punch_start,
2c1d2328 5557 EXT_MAX_BLOCKS - punch_start);
9eb79482
NJ
5558 if (ret) {
5559 up_write(&EXT4_I(inode)->i_data_sem);
5560 goto out_stop;
5561 }
5562
5563 ret = ext4_ext_remove_space(inode, punch_start, punch_stop - 1);
5564 if (ret) {
5565 up_write(&EXT4_I(inode)->i_data_sem);
5566 goto out_stop;
5567 }
ef24f6c2 5568 ext4_discard_preallocations(inode);
9eb79482
NJ
5569
5570 ret = ext4_ext_shift_extents(inode, handle, punch_stop,
331573fe 5571 punch_stop - punch_start, SHIFT_LEFT);
9eb79482
NJ
5572 if (ret) {
5573 up_write(&EXT4_I(inode)->i_data_sem);
5574 goto out_stop;
5575 }
5576
5577 new_size = i_size_read(inode) - len;
9337d5d3 5578 i_size_write(inode, new_size);
9eb79482
NJ
5579 EXT4_I(inode)->i_disksize = new_size;
5580
9eb79482
NJ
5581 up_write(&EXT4_I(inode)->i_data_sem);
5582 if (IS_SYNC(inode))
5583 ext4_handle_sync(handle);
5584 inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
5585 ext4_mark_inode_dirty(handle, inode);
5586
5587out_stop:
5588 ext4_journal_stop(handle);
ea3d7209
JK
5589out_mmap:
5590 up_write(&EXT4_I(inode)->i_mmap_sem);
9eb79482
NJ
5591 ext4_inode_resume_unlocked_dio(inode);
5592out_mutex:
5955102c 5593 inode_unlock(inode);
9eb79482
NJ
5594 return ret;
5595}
fcf6b1b7 5596
331573fe
NJ
5597/*
5598 * ext4_insert_range:
5599 * This function implements the FALLOC_FL_INSERT_RANGE flag of fallocate.
5600 * The data blocks starting from @offset to the EOF are shifted by @len
5601 * towards right to create a hole in the @inode. Inode size is increased
5602 * by len bytes.
5603 * Returns 0 on success, error otherwise.
5604 */
5605int ext4_insert_range(struct inode *inode, loff_t offset, loff_t len)
5606{
5607 struct super_block *sb = inode->i_sb;
5608 handle_t *handle;
5609 struct ext4_ext_path *path;
5610 struct ext4_extent *extent;
5611 ext4_lblk_t offset_lblk, len_lblk, ee_start_lblk = 0;
5612 unsigned int credits, ee_len;
5613 int ret = 0, depth, split_flag = 0;
5614 loff_t ioffset;
5615
5616 /*
5617 * We need to test this early because xfstests assumes that an
5618 * insert range of (0, 1) will return EOPNOTSUPP if the file
5619 * system does not support insert range.
5620 */
5621 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
5622 return -EOPNOTSUPP;
5623
5624 /* Insert range works only on fs block size aligned offsets. */
5625 if (offset & (EXT4_CLUSTER_SIZE(sb) - 1) ||
5626 len & (EXT4_CLUSTER_SIZE(sb) - 1))
5627 return -EINVAL;
5628
5629 if (!S_ISREG(inode->i_mode))
5630 return -EOPNOTSUPP;
5631
5632 trace_ext4_insert_range(inode, offset, len);
5633
5634 offset_lblk = offset >> EXT4_BLOCK_SIZE_BITS(sb);
5635 len_lblk = len >> EXT4_BLOCK_SIZE_BITS(sb);
5636
5637 /* Call ext4_force_commit to flush all data in case of data=journal */
5638 if (ext4_should_journal_data(inode)) {
5639 ret = ext4_force_commit(inode->i_sb);
5640 if (ret)
5641 return ret;
5642 }
5643
5955102c 5644 inode_lock(inode);
331573fe
NJ
5645 /* Currently just for extent based files */
5646 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
5647 ret = -EOPNOTSUPP;
5648 goto out_mutex;
5649 }
5650
5651 /* Check for wrap through zero */
5652 if (inode->i_size + len > inode->i_sb->s_maxbytes) {
5653 ret = -EFBIG;
5654 goto out_mutex;
5655 }
5656
5657 /* Offset should be less than i_size */
5658 if (offset >= i_size_read(inode)) {
5659 ret = -EINVAL;
5660 goto out_mutex;
5661 }
5662
331573fe
NJ
5663 /* Wait for existing dio to complete */
5664 ext4_inode_block_unlocked_dio(inode);
5665 inode_dio_wait(inode);
5666
ea3d7209
JK
5667 /*
5668 * Prevent page faults from reinstantiating pages we have released from
5669 * page cache.
5670 */
5671 down_write(&EXT4_I(inode)->i_mmap_sem);
32ebffd3
JK
5672 /*
5673 * Need to round down to align start offset to page size boundary
5674 * for page size > block size.
5675 */
5676 ioffset = round_down(offset, PAGE_SIZE);
5677 /* Write out all dirty pages */
5678 ret = filemap_write_and_wait_range(inode->i_mapping, ioffset,
5679 LLONG_MAX);
5680 if (ret)
5681 goto out_mmap;
ea3d7209
JK
5682 truncate_pagecache(inode, ioffset);
5683
331573fe
NJ
5684 credits = ext4_writepage_trans_blocks(inode);
5685 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
5686 if (IS_ERR(handle)) {
5687 ret = PTR_ERR(handle);
ea3d7209 5688 goto out_mmap;
331573fe
NJ
5689 }
5690
5691 /* Expand file to avoid data loss if there is error while shifting */
5692 inode->i_size += len;
5693 EXT4_I(inode)->i_disksize += len;
5694 inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
5695 ret = ext4_mark_inode_dirty(handle, inode);
5696 if (ret)
5697 goto out_stop;
5698
5699 down_write(&EXT4_I(inode)->i_data_sem);
5700 ext4_discard_preallocations(inode);
5701
5702 path = ext4_find_extent(inode, offset_lblk, NULL, 0);
5703 if (IS_ERR(path)) {
5704 up_write(&EXT4_I(inode)->i_data_sem);
5705 goto out_stop;
5706 }
5707
5708 depth = ext_depth(inode);
5709 extent = path[depth].p_ext;
5710 if (extent) {
5711 ee_start_lblk = le32_to_cpu(extent->ee_block);
5712 ee_len = ext4_ext_get_actual_len(extent);
5713
5714 /*
5715 * If offset_lblk is not the starting block of extent, split
5716 * the extent @offset_lblk
5717 */
5718 if ((offset_lblk > ee_start_lblk) &&
5719 (offset_lblk < (ee_start_lblk + ee_len))) {
5720 if (ext4_ext_is_unwritten(extent))
5721 split_flag = EXT4_EXT_MARK_UNWRIT1 |
5722 EXT4_EXT_MARK_UNWRIT2;
5723 ret = ext4_split_extent_at(handle, inode, &path,
5724 offset_lblk, split_flag,
5725 EXT4_EX_NOCACHE |
5726 EXT4_GET_BLOCKS_PRE_IO |
5727 EXT4_GET_BLOCKS_METADATA_NOFAIL);
5728 }
5729
5730 ext4_ext_drop_refs(path);
5731 kfree(path);
5732 if (ret < 0) {
5733 up_write(&EXT4_I(inode)->i_data_sem);
5734 goto out_stop;
5735 }
5736 }
5737
5738 ret = ext4_es_remove_extent(inode, offset_lblk,
5739 EXT_MAX_BLOCKS - offset_lblk);
5740 if (ret) {
5741 up_write(&EXT4_I(inode)->i_data_sem);
5742 goto out_stop;
5743 }
5744
5745 /*
5746 * if offset_lblk lies in a hole which is at start of file, use
5747 * ee_start_lblk to shift extents
5748 */
5749 ret = ext4_ext_shift_extents(inode, handle,
5750 ee_start_lblk > offset_lblk ? ee_start_lblk : offset_lblk,
5751 len_lblk, SHIFT_RIGHT);
5752
5753 up_write(&EXT4_I(inode)->i_data_sem);
5754 if (IS_SYNC(inode))
5755 ext4_handle_sync(handle);
5756
5757out_stop:
5758 ext4_journal_stop(handle);
ea3d7209
JK
5759out_mmap:
5760 up_write(&EXT4_I(inode)->i_mmap_sem);
331573fe
NJ
5761 ext4_inode_resume_unlocked_dio(inode);
5762out_mutex:
5955102c 5763 inode_unlock(inode);
331573fe
NJ
5764 return ret;
5765}
5766
fcf6b1b7
DM
5767/**
5768 * ext4_swap_extents - Swap extents between two inodes
5769 *
5770 * @inode1: First inode
5771 * @inode2: Second inode
5772 * @lblk1: Start block for first inode
5773 * @lblk2: Start block for second inode
5774 * @count: Number of blocks to swap
5775 * @mark_unwritten: Mark second inode's extents as unwritten after swap
5776 * @erp: Pointer to save error value
5777 *
5778 * This helper routine does exactly what is promise "swap extents". All other
5779 * stuff such as page-cache locking consistency, bh mapping consistency or
5780 * extent's data copying must be performed by caller.
5781 * Locking:
5782 * i_mutex is held for both inodes
5783 * i_data_sem is locked for write for both inodes
5784 * Assumptions:
5785 * All pages from requested range are locked for both inodes
5786 */
5787int
5788ext4_swap_extents(handle_t *handle, struct inode *inode1,
5789 struct inode *inode2, ext4_lblk_t lblk1, ext4_lblk_t lblk2,
5790 ext4_lblk_t count, int unwritten, int *erp)
5791{
5792 struct ext4_ext_path *path1 = NULL;
5793 struct ext4_ext_path *path2 = NULL;
5794 int replaced_count = 0;
5795
5796 BUG_ON(!rwsem_is_locked(&EXT4_I(inode1)->i_data_sem));
5797 BUG_ON(!rwsem_is_locked(&EXT4_I(inode2)->i_data_sem));
5955102c
AV
5798 BUG_ON(!inode_is_locked(inode1));
5799 BUG_ON(!inode_is_locked(inode2));
fcf6b1b7
DM
5800
5801 *erp = ext4_es_remove_extent(inode1, lblk1, count);
19008f6d 5802 if (unlikely(*erp))
fcf6b1b7
DM
5803 return 0;
5804 *erp = ext4_es_remove_extent(inode2, lblk2, count);
19008f6d 5805 if (unlikely(*erp))
fcf6b1b7
DM
5806 return 0;
5807
5808 while (count) {
5809 struct ext4_extent *ex1, *ex2, tmp_ex;
5810 ext4_lblk_t e1_blk, e2_blk;
5811 int e1_len, e2_len, len;
5812 int split = 0;
5813
ed8a1a76 5814 path1 = ext4_find_extent(inode1, lblk1, NULL, EXT4_EX_NOCACHE);
a1c83681 5815 if (IS_ERR(path1)) {
fcf6b1b7 5816 *erp = PTR_ERR(path1);
19008f6d
TT
5817 path1 = NULL;
5818 finish:
5819 count = 0;
5820 goto repeat;
fcf6b1b7 5821 }
ed8a1a76 5822 path2 = ext4_find_extent(inode2, lblk2, NULL, EXT4_EX_NOCACHE);
a1c83681 5823 if (IS_ERR(path2)) {
fcf6b1b7 5824 *erp = PTR_ERR(path2);
19008f6d
TT
5825 path2 = NULL;
5826 goto finish;
fcf6b1b7
DM
5827 }
5828 ex1 = path1[path1->p_depth].p_ext;
5829 ex2 = path2[path2->p_depth].p_ext;
5830 /* Do we have somthing to swap ? */
5831 if (unlikely(!ex2 || !ex1))
19008f6d 5832 goto finish;
fcf6b1b7
DM
5833
5834 e1_blk = le32_to_cpu(ex1->ee_block);
5835 e2_blk = le32_to_cpu(ex2->ee_block);
5836 e1_len = ext4_ext_get_actual_len(ex1);
5837 e2_len = ext4_ext_get_actual_len(ex2);
5838
5839 /* Hole handling */
5840 if (!in_range(lblk1, e1_blk, e1_len) ||
5841 !in_range(lblk2, e2_blk, e2_len)) {
5842 ext4_lblk_t next1, next2;
5843
5844 /* if hole after extent, then go to next extent */
5845 next1 = ext4_ext_next_allocated_block(path1);
5846 next2 = ext4_ext_next_allocated_block(path2);
5847 /* If hole before extent, then shift to that extent */
5848 if (e1_blk > lblk1)
5849 next1 = e1_blk;
5850 if (e2_blk > lblk2)
5851 next2 = e1_blk;
5852 /* Do we have something to swap */
5853 if (next1 == EXT_MAX_BLOCKS || next2 == EXT_MAX_BLOCKS)
19008f6d 5854 goto finish;
fcf6b1b7
DM
5855 /* Move to the rightest boundary */
5856 len = next1 - lblk1;
5857 if (len < next2 - lblk2)
5858 len = next2 - lblk2;
5859 if (len > count)
5860 len = count;
5861 lblk1 += len;
5862 lblk2 += len;
5863 count -= len;
5864 goto repeat;
5865 }
5866
5867 /* Prepare left boundary */
5868 if (e1_blk < lblk1) {
5869 split = 1;
5870 *erp = ext4_force_split_extent_at(handle, inode1,
dfe50809 5871 &path1, lblk1, 0);
19008f6d
TT
5872 if (unlikely(*erp))
5873 goto finish;
fcf6b1b7
DM
5874 }
5875 if (e2_blk < lblk2) {
5876 split = 1;
5877 *erp = ext4_force_split_extent_at(handle, inode2,
dfe50809 5878 &path2, lblk2, 0);
19008f6d
TT
5879 if (unlikely(*erp))
5880 goto finish;
fcf6b1b7 5881 }
dfe50809 5882 /* ext4_split_extent_at() may result in leaf extent split,
fcf6b1b7
DM
5883 * path must to be revalidated. */
5884 if (split)
5885 goto repeat;
5886
5887 /* Prepare right boundary */
5888 len = count;
5889 if (len > e1_blk + e1_len - lblk1)
5890 len = e1_blk + e1_len - lblk1;
5891 if (len > e2_blk + e2_len - lblk2)
5892 len = e2_blk + e2_len - lblk2;
5893
5894 if (len != e1_len) {
5895 split = 1;
5896 *erp = ext4_force_split_extent_at(handle, inode1,
dfe50809 5897 &path1, lblk1 + len, 0);
19008f6d
TT
5898 if (unlikely(*erp))
5899 goto finish;
fcf6b1b7
DM
5900 }
5901 if (len != e2_len) {
5902 split = 1;
5903 *erp = ext4_force_split_extent_at(handle, inode2,
dfe50809 5904 &path2, lblk2 + len, 0);
fcf6b1b7 5905 if (*erp)
19008f6d 5906 goto finish;
fcf6b1b7 5907 }
dfe50809 5908 /* ext4_split_extent_at() may result in leaf extent split,
fcf6b1b7
DM
5909 * path must to be revalidated. */
5910 if (split)
5911 goto repeat;
5912
5913 BUG_ON(e2_len != e1_len);
5914 *erp = ext4_ext_get_access(handle, inode1, path1 + path1->p_depth);
19008f6d
TT
5915 if (unlikely(*erp))
5916 goto finish;
fcf6b1b7 5917 *erp = ext4_ext_get_access(handle, inode2, path2 + path2->p_depth);
19008f6d
TT
5918 if (unlikely(*erp))
5919 goto finish;
fcf6b1b7
DM
5920
5921 /* Both extents are fully inside boundaries. Swap it now */
5922 tmp_ex = *ex1;
5923 ext4_ext_store_pblock(ex1, ext4_ext_pblock(ex2));
5924 ext4_ext_store_pblock(ex2, ext4_ext_pblock(&tmp_ex));
5925 ex1->ee_len = cpu_to_le16(e2_len);
5926 ex2->ee_len = cpu_to_le16(e1_len);
5927 if (unwritten)
5928 ext4_ext_mark_unwritten(ex2);
5929 if (ext4_ext_is_unwritten(&tmp_ex))
5930 ext4_ext_mark_unwritten(ex1);
5931
5932 ext4_ext_try_to_merge(handle, inode2, path2, ex2);
5933 ext4_ext_try_to_merge(handle, inode1, path1, ex1);
5934 *erp = ext4_ext_dirty(handle, inode2, path2 +
5935 path2->p_depth);
19008f6d
TT
5936 if (unlikely(*erp))
5937 goto finish;
fcf6b1b7
DM
5938 *erp = ext4_ext_dirty(handle, inode1, path1 +
5939 path1->p_depth);
5940 /*
5941 * Looks scarry ah..? second inode already points to new blocks,
5942 * and it was successfully dirtied. But luckily error may happen
5943 * only due to journal error, so full transaction will be
5944 * aborted anyway.
5945 */
19008f6d
TT
5946 if (unlikely(*erp))
5947 goto finish;
fcf6b1b7
DM
5948 lblk1 += len;
5949 lblk2 += len;
5950 replaced_count += len;
5951 count -= len;
5952
5953 repeat:
b7ea89ad
TT
5954 ext4_ext_drop_refs(path1);
5955 kfree(path1);
5956 ext4_ext_drop_refs(path2);
5957 kfree(path2);
5958 path1 = path2 = NULL;
fcf6b1b7 5959 }
fcf6b1b7
DM
5960 return replaced_count;
5961}