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