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