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