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