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