blob: 54750b7c162d26a8696afd85c9e1060439a454d8 [file] [log] [blame]
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001// SPDX-License-Identifier: GPL-2.0
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>
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
20#include <linux/fs.h>
21#include <linux/time.h>
22#include <linux/jbd2.h>
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>
28#include <linux/uaccess.h>
29#include <linux/fiemap.h>
30#include <linux/backing-dev.h>
Olivier Deprez157378f2022-04-04 15:47:50 +020031#include <linux/iomap.h>
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000032#include "ext4_jbd2.h"
33#include "ext4_extents.h"
34#include "xattr.h"
35
36#include <trace/events/ext4.h>
37
38/*
39 * used by extent splitting.
40 */
41#define EXT4_EXT_MAY_ZEROOUT 0x1 /* safe to zeroout if split fails \
42 due to ENOSPC */
43#define EXT4_EXT_MARK_UNWRIT1 0x2 /* mark first half unwritten */
44#define EXT4_EXT_MARK_UNWRIT2 0x4 /* mark second half unwritten */
45
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
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
66 if (!ext4_has_metadata_csum(inode->i_sb))
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
80 if (!ext4_has_metadata_csum(inode->i_sb))
81 return;
82
83 et = find_ext4_extent_tail(eh);
84 et->et_checksum = ext4_extent_block_csum(inode, eh);
85}
86
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000087static int ext4_split_extent_at(handle_t *handle,
88 struct inode *inode,
89 struct ext4_ext_path **ppath,
90 ext4_lblk_t split,
91 int split_flag,
92 int flags);
93
Olivier Deprez157378f2022-04-04 15:47:50 +020094static int ext4_ext_trunc_restart_fn(struct inode *inode, int *dropped)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000095{
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000096 /*
Olivier Deprez157378f2022-04-04 15:47:50 +020097 * 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.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000101 */
Olivier Deprez157378f2022-04-04 15:47:50 +0200102 BUG_ON(EXT4_JOURNAL(inode) == NULL);
103 ext4_discard_preallocations(inode, 0);
104 up_write(&EXT4_I(inode)->i_data_sem);
105 *dropped = 1;
106 return 0;
107}
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000108
Olivier Deprez157378f2022-04-04 15:47:50 +0200109/*
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,
118 int check_cred, int restart_cred,
119 int revoke_cred)
120{
121 int ret;
122 int dropped = 0;
123
124 ret = ext4_journal_ensure_credits_fn(handle, check_cred, restart_cred,
125 revoke_cred, ext4_ext_trunc_restart_fn(inode, &dropped));
126 if (dropped)
127 down_write(&EXT4_I(inode)->i_data_sem);
128 return ret;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000129}
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{
Olivier Deprez157378f2022-04-04 15:47:50 +0200139 int err = 0;
140
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000141 if (path->p_bh) {
142 /* path points to block */
143 BUFFER_TRACE(path->p_bh, "get_write_access");
Olivier Deprez157378f2022-04-04 15:47:50 +0200144 err = ext4_journal_get_write_access(handle, path->p_bh);
145 /*
146 * The extent buffer's verified bit will be set again in
147 * __ext4_ext_dirty(). We could leave an inconsistent
148 * buffer if the extents updating procudure break off du
149 * to some error happens, force to check it again.
150 */
151 if (!err)
152 clear_buffer_verified(path->p_bh);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000153 }
154 /* path points to leaf/index in inode body */
155 /* we use in-core data, no need to protect them */
Olivier Deprez157378f2022-04-04 15:47:50 +0200156 return err;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000157}
158
159/*
160 * could return:
161 * - EROFS
162 * - ENOMEM
163 * - EIO
164 */
Olivier Deprez157378f2022-04-04 15:47:50 +0200165static int __ext4_ext_dirty(const char *where, unsigned int line,
166 handle_t *handle, struct inode *inode,
167 struct ext4_ext_path *path)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000168{
169 int err;
170
171 WARN_ON(!rwsem_is_locked(&EXT4_I(inode)->i_data_sem));
172 if (path->p_bh) {
173 ext4_extent_block_csum_set(inode, ext_block_hdr(path->p_bh));
174 /* path points to block */
175 err = __ext4_handle_dirty_metadata(where, line, handle,
176 inode, path->p_bh);
Olivier Deprez157378f2022-04-04 15:47:50 +0200177 /* Extents updating done, re-set verified flag */
178 if (!err)
179 set_buffer_verified(path->p_bh);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000180 } else {
181 /* path points to leaf/index in inode body */
182 err = ext4_mark_inode_dirty(handle, inode);
183 }
184 return err;
185}
186
Olivier Deprez157378f2022-04-04 15:47:50 +0200187#define ext4_ext_dirty(handle, inode, path) \
188 __ext4_ext_dirty(__func__, __LINE__, (handle), (inode), (path))
189
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000190static ext4_fsblk_t ext4_ext_find_goal(struct inode *inode,
191 struct ext4_ext_path *path,
192 ext4_lblk_t block)
193{
194 if (path) {
195 int depth = path->p_depth;
196 struct ext4_extent *ex;
197
198 /*
199 * Try to predict block placement assuming that we are
200 * filling in a file which will eventually be
201 * non-sparse --- i.e., in the case of libbfd writing
202 * an ELF object sections out-of-order but in a way
203 * the eventually results in a contiguous object or
204 * executable file, or some database extending a table
205 * space file. However, this is actually somewhat
206 * non-ideal if we are writing a sparse file such as
207 * qemu or KVM writing a raw image file that is going
208 * to stay fairly sparse, since it will end up
209 * fragmenting the file system's free space. Maybe we
210 * should have some hueristics or some way to allow
211 * userspace to pass a hint to file system,
212 * especially if the latter case turns out to be
213 * common.
214 */
215 ex = path[depth].p_ext;
216 if (ex) {
217 ext4_fsblk_t ext_pblk = ext4_ext_pblock(ex);
218 ext4_lblk_t ext_block = le32_to_cpu(ex->ee_block);
219
220 if (block > ext_block)
221 return ext_pblk + (block - ext_block);
222 else
223 return ext_pblk - (ext_block - block);
224 }
225
226 /* it looks like index is empty;
227 * try to find starting block from index itself */
228 if (path[depth].p_bh)
229 return path[depth].p_bh->b_blocknr;
230 }
231
232 /* OK. use inode's group */
233 return ext4_inode_to_goal_block(inode);
234}
235
236/*
237 * Allocation for a meta data block
238 */
239static ext4_fsblk_t
240ext4_ext_new_meta_block(handle_t *handle, struct inode *inode,
241 struct ext4_ext_path *path,
242 struct ext4_extent *ex, int *err, unsigned int flags)
243{
244 ext4_fsblk_t goal, newblock;
245
246 goal = ext4_ext_find_goal(inode, path, le32_to_cpu(ex->ee_block));
247 newblock = ext4_new_meta_blocks(handle, inode, goal, flags,
248 NULL, err);
249 return newblock;
250}
251
252static inline int ext4_ext_space_block(struct inode *inode, int check)
253{
254 int size;
255
256 size = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
257 / sizeof(struct ext4_extent);
258#ifdef AGGRESSIVE_TEST
259 if (!check && size > 6)
260 size = 6;
261#endif
262 return size;
263}
264
265static inline int ext4_ext_space_block_idx(struct inode *inode, int check)
266{
267 int size;
268
269 size = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))
270 / sizeof(struct ext4_extent_idx);
271#ifdef AGGRESSIVE_TEST
272 if (!check && size > 5)
273 size = 5;
274#endif
275 return size;
276}
277
278static inline int ext4_ext_space_root(struct inode *inode, int check)
279{
280 int size;
281
282 size = sizeof(EXT4_I(inode)->i_data);
283 size -= sizeof(struct ext4_extent_header);
284 size /= sizeof(struct ext4_extent);
285#ifdef AGGRESSIVE_TEST
286 if (!check && size > 3)
287 size = 3;
288#endif
289 return size;
290}
291
292static inline int ext4_ext_space_root_idx(struct inode *inode, int check)
293{
294 int size;
295
296 size = sizeof(EXT4_I(inode)->i_data);
297 size -= sizeof(struct ext4_extent_header);
298 size /= sizeof(struct ext4_extent_idx);
299#ifdef AGGRESSIVE_TEST
300 if (!check && size > 4)
301 size = 4;
302#endif
303 return size;
304}
305
306static inline int
307ext4_force_split_extent_at(handle_t *handle, struct inode *inode,
308 struct ext4_ext_path **ppath, ext4_lblk_t lblk,
309 int nofail)
310{
311 struct ext4_ext_path *path = *ppath;
312 int unwritten = ext4_ext_is_unwritten(path[path->p_depth].p_ext);
Olivier Deprez157378f2022-04-04 15:47:50 +0200313 int flags = EXT4_EX_NOCACHE | EXT4_GET_BLOCKS_PRE_IO;
314
315 if (nofail)
316 flags |= EXT4_GET_BLOCKS_METADATA_NOFAIL | EXT4_EX_NOFAIL;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000317
318 return ext4_split_extent_at(handle, inode, ppath, lblk, unwritten ?
319 EXT4_EXT_MARK_UNWRIT1|EXT4_EXT_MARK_UNWRIT2 : 0,
Olivier Deprez157378f2022-04-04 15:47:50 +0200320 flags);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000321}
322
323static int
324ext4_ext_max_entries(struct inode *inode, int depth)
325{
326 int max;
327
328 if (depth == ext_depth(inode)) {
329 if (depth == 0)
330 max = ext4_ext_space_root(inode, 1);
331 else
332 max = ext4_ext_space_root_idx(inode, 1);
333 } else {
334 if (depth == 0)
335 max = ext4_ext_space_block(inode, 1);
336 else
337 max = ext4_ext_space_block_idx(inode, 1);
338 }
339
340 return max;
341}
342
343static int ext4_valid_extent(struct inode *inode, struct ext4_extent *ext)
344{
345 ext4_fsblk_t block = ext4_ext_pblock(ext);
346 int len = ext4_ext_get_actual_len(ext);
347 ext4_lblk_t lblock = le32_to_cpu(ext->ee_block);
348
349 /*
350 * We allow neither:
351 * - zero length
352 * - overflow/wrap-around
353 */
354 if (lblock + len <= lblock)
355 return 0;
Olivier Deprez157378f2022-04-04 15:47:50 +0200356 return ext4_inode_block_valid(inode, block, len);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000357}
358
359static int ext4_valid_extent_idx(struct inode *inode,
360 struct ext4_extent_idx *ext_idx)
361{
362 ext4_fsblk_t block = ext4_idx_pblock(ext_idx);
363
Olivier Deprez157378f2022-04-04 15:47:50 +0200364 return ext4_inode_block_valid(inode, block, 1);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000365}
366
367static int ext4_valid_extent_entries(struct inode *inode,
Olivier Deprez157378f2022-04-04 15:47:50 +0200368 struct ext4_extent_header *eh,
369 ext4_lblk_t lblk, ext4_fsblk_t *pblk,
370 int depth)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000371{
372 unsigned short entries;
Olivier Deprez157378f2022-04-04 15:47:50 +0200373 ext4_lblk_t lblock = 0;
Olivier Deprez92d4c212022-12-06 15:05:30 +0100374 ext4_lblk_t cur = 0;
Olivier Deprez157378f2022-04-04 15:47:50 +0200375
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000376 if (eh->eh_entries == 0)
377 return 1;
378
379 entries = le16_to_cpu(eh->eh_entries);
380
381 if (depth == 0) {
382 /* leaf entries */
383 struct ext4_extent *ext = EXT_FIRST_EXTENT(eh);
Olivier Deprez157378f2022-04-04 15:47:50 +0200384
385 /*
386 * The logical block in the first entry should equal to
387 * the number in the index block.
388 */
389 if (depth != ext_depth(inode) &&
390 lblk != le32_to_cpu(ext->ee_block))
391 return 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000392 while (entries) {
393 if (!ext4_valid_extent(inode, ext))
394 return 0;
395
396 /* Check for overlapping extents */
397 lblock = le32_to_cpu(ext->ee_block);
Olivier Deprez92d4c212022-12-06 15:05:30 +0100398 if (lblock < cur) {
Olivier Deprez157378f2022-04-04 15:47:50 +0200399 *pblk = ext4_ext_pblock(ext);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000400 return 0;
401 }
Olivier Deprez92d4c212022-12-06 15:05:30 +0100402 cur = lblock + ext4_ext_get_actual_len(ext);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000403 ext++;
404 entries--;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000405 }
406 } else {
407 struct ext4_extent_idx *ext_idx = EXT_FIRST_INDEX(eh);
Olivier Deprez157378f2022-04-04 15:47:50 +0200408
409 /*
410 * The logical block in the first entry should equal to
411 * the number in the parent index block.
412 */
413 if (depth != ext_depth(inode) &&
414 lblk != le32_to_cpu(ext_idx->ei_block))
415 return 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000416 while (entries) {
417 if (!ext4_valid_extent_idx(inode, ext_idx))
418 return 0;
Olivier Deprez157378f2022-04-04 15:47:50 +0200419
420 /* Check for overlapping index extents */
421 lblock = le32_to_cpu(ext_idx->ei_block);
Olivier Deprez92d4c212022-12-06 15:05:30 +0100422 if (lblock < cur) {
Olivier Deprez157378f2022-04-04 15:47:50 +0200423 *pblk = ext4_idx_pblock(ext_idx);
424 return 0;
425 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000426 ext_idx++;
427 entries--;
Olivier Deprez92d4c212022-12-06 15:05:30 +0100428 cur = lblock + 1;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000429 }
430 }
431 return 1;
432}
433
434static int __ext4_ext_check(const char *function, unsigned int line,
435 struct inode *inode, struct ext4_extent_header *eh,
Olivier Deprez157378f2022-04-04 15:47:50 +0200436 int depth, ext4_fsblk_t pblk, ext4_lblk_t lblk)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000437{
438 const char *error_msg;
439 int max = 0, err = -EFSCORRUPTED;
440
441 if (unlikely(eh->eh_magic != EXT4_EXT_MAGIC)) {
442 error_msg = "invalid magic";
443 goto corrupted;
444 }
445 if (unlikely(le16_to_cpu(eh->eh_depth) != depth)) {
446 error_msg = "unexpected eh_depth";
447 goto corrupted;
448 }
449 if (unlikely(eh->eh_max == 0)) {
450 error_msg = "invalid eh_max";
451 goto corrupted;
452 }
453 max = ext4_ext_max_entries(inode, depth);
454 if (unlikely(le16_to_cpu(eh->eh_max) > max)) {
455 error_msg = "too large eh_max";
456 goto corrupted;
457 }
458 if (unlikely(le16_to_cpu(eh->eh_entries) > le16_to_cpu(eh->eh_max))) {
459 error_msg = "invalid eh_entries";
460 goto corrupted;
461 }
Olivier Deprez92d4c212022-12-06 15:05:30 +0100462 if (unlikely((eh->eh_entries == 0) && (depth > 0))) {
463 error_msg = "eh_entries is 0 but eh_depth is > 0";
464 goto corrupted;
465 }
Olivier Deprez157378f2022-04-04 15:47:50 +0200466 if (!ext4_valid_extent_entries(inode, eh, lblk, &pblk, depth)) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000467 error_msg = "invalid extent entries";
468 goto corrupted;
469 }
470 if (unlikely(depth > 32)) {
471 error_msg = "too large eh_depth";
472 goto corrupted;
473 }
474 /* Verify checksum on non-root extent tree nodes */
475 if (ext_depth(inode) != depth &&
476 !ext4_extent_block_csum_verify(inode, eh)) {
477 error_msg = "extent tree corrupted";
478 err = -EFSBADCRC;
479 goto corrupted;
480 }
481 return 0;
482
483corrupted:
Olivier Deprez157378f2022-04-04 15:47:50 +0200484 ext4_error_inode_err(inode, function, line, 0, -err,
485 "pblk %llu bad header/extent: %s - magic %x, "
486 "entries %u, max %u(%u), depth %u(%u)",
487 (unsigned long long) pblk, error_msg,
488 le16_to_cpu(eh->eh_magic),
489 le16_to_cpu(eh->eh_entries),
490 le16_to_cpu(eh->eh_max),
491 max, le16_to_cpu(eh->eh_depth), depth);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000492 return err;
493}
494
495#define ext4_ext_check(inode, eh, depth, pblk) \
Olivier Deprez157378f2022-04-04 15:47:50 +0200496 __ext4_ext_check(__func__, __LINE__, (inode), (eh), (depth), (pblk), 0)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000497
498int ext4_ext_check_inode(struct inode *inode)
499{
500 return ext4_ext_check(inode, ext_inode_hdr(inode), ext_depth(inode), 0);
501}
502
Olivier Deprez0e641232021-09-23 10:07:05 +0200503static void ext4_cache_extents(struct inode *inode,
504 struct ext4_extent_header *eh)
505{
506 struct ext4_extent *ex = EXT_FIRST_EXTENT(eh);
507 ext4_lblk_t prev = 0;
508 int i;
509
510 for (i = le16_to_cpu(eh->eh_entries); i > 0; i--, ex++) {
511 unsigned int status = EXTENT_STATUS_WRITTEN;
512 ext4_lblk_t lblk = le32_to_cpu(ex->ee_block);
513 int len = ext4_ext_get_actual_len(ex);
514
515 if (prev && (prev != lblk))
516 ext4_es_cache_extent(inode, prev, lblk - prev, ~0,
517 EXTENT_STATUS_HOLE);
518
519 if (ext4_ext_is_unwritten(ex))
520 status = EXTENT_STATUS_UNWRITTEN;
521 ext4_es_cache_extent(inode, lblk, len,
522 ext4_ext_pblock(ex), status);
523 prev = lblk + len;
524 }
525}
526
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000527static struct buffer_head *
528__read_extent_tree_block(const char *function, unsigned int line,
Olivier Deprez157378f2022-04-04 15:47:50 +0200529 struct inode *inode, struct ext4_extent_idx *idx,
530 int depth, int flags)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000531{
532 struct buffer_head *bh;
533 int err;
Olivier Deprez157378f2022-04-04 15:47:50 +0200534 gfp_t gfp_flags = __GFP_MOVABLE | GFP_NOFS;
535 ext4_fsblk_t pblk;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000536
Olivier Deprez157378f2022-04-04 15:47:50 +0200537 if (flags & EXT4_EX_NOFAIL)
538 gfp_flags |= __GFP_NOFAIL;
539
540 pblk = ext4_idx_pblock(idx);
541 bh = sb_getblk_gfp(inode->i_sb, pblk, gfp_flags);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000542 if (unlikely(!bh))
543 return ERR_PTR(-ENOMEM);
544
545 if (!bh_uptodate_or_lock(bh)) {
546 trace_ext4_ext_load_extent(inode, pblk, _RET_IP_);
Olivier Deprez157378f2022-04-04 15:47:50 +0200547 err = ext4_read_bh(bh, 0, NULL);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000548 if (err < 0)
549 goto errout;
550 }
551 if (buffer_verified(bh) && !(flags & EXT4_EX_FORCE_CACHE))
552 return bh;
Olivier Deprez157378f2022-04-04 15:47:50 +0200553 err = __ext4_ext_check(function, line, inode, ext_block_hdr(bh),
554 depth, pblk, le32_to_cpu(idx->ei_block));
555 if (err)
556 goto errout;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000557 set_buffer_verified(bh);
558 /*
559 * If this is a leaf block, cache all of its entries
560 */
561 if (!(flags & EXT4_EX_NOCACHE) && depth == 0) {
562 struct ext4_extent_header *eh = ext_block_hdr(bh);
Olivier Deprez0e641232021-09-23 10:07:05 +0200563 ext4_cache_extents(inode, eh);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000564 }
565 return bh;
566errout:
567 put_bh(bh);
568 return ERR_PTR(err);
569
570}
571
Olivier Deprez157378f2022-04-04 15:47:50 +0200572#define read_extent_tree_block(inode, idx, depth, flags) \
573 __read_extent_tree_block(__func__, __LINE__, (inode), (idx), \
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000574 (depth), (flags))
575
576/*
577 * This function is called to cache a file's extent information in the
578 * extent status tree
579 */
580int ext4_ext_precache(struct inode *inode)
581{
582 struct ext4_inode_info *ei = EXT4_I(inode);
583 struct ext4_ext_path *path = NULL;
584 struct buffer_head *bh;
585 int i = 0, depth, ret = 0;
586
587 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
588 return 0; /* not an extent-mapped inode */
589
590 down_read(&ei->i_data_sem);
591 depth = ext_depth(inode);
592
Olivier Deprez157378f2022-04-04 15:47:50 +0200593 /* Don't cache anything if there are no external extent blocks */
594 if (!depth) {
595 up_read(&ei->i_data_sem);
596 return ret;
597 }
598
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000599 path = kcalloc(depth + 1, sizeof(struct ext4_ext_path),
600 GFP_NOFS);
601 if (path == NULL) {
602 up_read(&ei->i_data_sem);
603 return -ENOMEM;
604 }
605
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000606 path[0].p_hdr = ext_inode_hdr(inode);
607 ret = ext4_ext_check(inode, path[0].p_hdr, depth, 0);
608 if (ret)
609 goto out;
610 path[0].p_idx = EXT_FIRST_INDEX(path[0].p_hdr);
611 while (i >= 0) {
612 /*
613 * If this is a leaf block or we've reached the end of
614 * the index block, go up
615 */
616 if ((i == depth) ||
617 path[i].p_idx > EXT_LAST_INDEX(path[i].p_hdr)) {
618 brelse(path[i].p_bh);
619 path[i].p_bh = NULL;
620 i--;
621 continue;
622 }
Olivier Deprez157378f2022-04-04 15:47:50 +0200623 bh = read_extent_tree_block(inode, path[i].p_idx++,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000624 depth - i - 1,
625 EXT4_EX_FORCE_CACHE);
626 if (IS_ERR(bh)) {
627 ret = PTR_ERR(bh);
628 break;
629 }
630 i++;
631 path[i].p_bh = bh;
632 path[i].p_hdr = ext_block_hdr(bh);
633 path[i].p_idx = EXT_FIRST_INDEX(path[i].p_hdr);
634 }
635 ext4_set_inode_state(inode, EXT4_STATE_EXT_PRECACHED);
636out:
637 up_read(&ei->i_data_sem);
638 ext4_ext_drop_refs(path);
639 kfree(path);
640 return ret;
641}
642
643#ifdef EXT_DEBUG
644static void ext4_ext_show_path(struct inode *inode, struct ext4_ext_path *path)
645{
646 int k, l = path->p_depth;
647
Olivier Deprez157378f2022-04-04 15:47:50 +0200648 ext_debug(inode, "path:");
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000649 for (k = 0; k <= l; k++, path++) {
650 if (path->p_idx) {
Olivier Deprez157378f2022-04-04 15:47:50 +0200651 ext_debug(inode, " %d->%llu",
652 le32_to_cpu(path->p_idx->ei_block),
653 ext4_idx_pblock(path->p_idx));
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000654 } else if (path->p_ext) {
Olivier Deprez157378f2022-04-04 15:47:50 +0200655 ext_debug(inode, " %d:[%d]%d:%llu ",
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000656 le32_to_cpu(path->p_ext->ee_block),
657 ext4_ext_is_unwritten(path->p_ext),
658 ext4_ext_get_actual_len(path->p_ext),
659 ext4_ext_pblock(path->p_ext));
660 } else
Olivier Deprez157378f2022-04-04 15:47:50 +0200661 ext_debug(inode, " []");
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000662 }
Olivier Deprez157378f2022-04-04 15:47:50 +0200663 ext_debug(inode, "\n");
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000664}
665
666static void ext4_ext_show_leaf(struct inode *inode, struct ext4_ext_path *path)
667{
668 int depth = ext_depth(inode);
669 struct ext4_extent_header *eh;
670 struct ext4_extent *ex;
671 int i;
672
673 if (!path)
674 return;
675
676 eh = path[depth].p_hdr;
677 ex = EXT_FIRST_EXTENT(eh);
678
Olivier Deprez157378f2022-04-04 15:47:50 +0200679 ext_debug(inode, "Displaying leaf extents\n");
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000680
681 for (i = 0; i < le16_to_cpu(eh->eh_entries); i++, ex++) {
Olivier Deprez157378f2022-04-04 15:47:50 +0200682 ext_debug(inode, "%d:[%d]%d:%llu ", le32_to_cpu(ex->ee_block),
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000683 ext4_ext_is_unwritten(ex),
684 ext4_ext_get_actual_len(ex), ext4_ext_pblock(ex));
685 }
Olivier Deprez157378f2022-04-04 15:47:50 +0200686 ext_debug(inode, "\n");
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000687}
688
689static void ext4_ext_show_move(struct inode *inode, struct ext4_ext_path *path,
690 ext4_fsblk_t newblock, int level)
691{
692 int depth = ext_depth(inode);
693 struct ext4_extent *ex;
694
695 if (depth != level) {
696 struct ext4_extent_idx *idx;
697 idx = path[level].p_idx;
698 while (idx <= EXT_MAX_INDEX(path[level].p_hdr)) {
Olivier Deprez157378f2022-04-04 15:47:50 +0200699 ext_debug(inode, "%d: move %d:%llu in new index %llu\n",
700 level, le32_to_cpu(idx->ei_block),
701 ext4_idx_pblock(idx), newblock);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000702 idx++;
703 }
704
705 return;
706 }
707
708 ex = path[depth].p_ext;
709 while (ex <= EXT_MAX_EXTENT(path[depth].p_hdr)) {
Olivier Deprez157378f2022-04-04 15:47:50 +0200710 ext_debug(inode, "move %d:%llu:[%d]%d in new leaf %llu\n",
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000711 le32_to_cpu(ex->ee_block),
712 ext4_ext_pblock(ex),
713 ext4_ext_is_unwritten(ex),
714 ext4_ext_get_actual_len(ex),
715 newblock);
716 ex++;
717 }
718}
719
720#else
721#define ext4_ext_show_path(inode, path)
722#define ext4_ext_show_leaf(inode, path)
723#define ext4_ext_show_move(inode, path, newblock, level)
724#endif
725
726void ext4_ext_drop_refs(struct ext4_ext_path *path)
727{
728 int depth, i;
729
730 if (!path)
731 return;
732 depth = path->p_depth;
Olivier Deprez157378f2022-04-04 15:47:50 +0200733 for (i = 0; i <= depth; i++, path++) {
734 brelse(path->p_bh);
735 path->p_bh = NULL;
736 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000737}
738
739/*
740 * ext4_ext_binsearch_idx:
741 * binary search for the closest index of the given block
742 * the header must be checked before calling this
743 */
744static void
745ext4_ext_binsearch_idx(struct inode *inode,
746 struct ext4_ext_path *path, ext4_lblk_t block)
747{
748 struct ext4_extent_header *eh = path->p_hdr;
749 struct ext4_extent_idx *r, *l, *m;
750
751
Olivier Deprez157378f2022-04-04 15:47:50 +0200752 ext_debug(inode, "binsearch for %u(idx): ", block);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000753
754 l = EXT_FIRST_INDEX(eh) + 1;
755 r = EXT_LAST_INDEX(eh);
756 while (l <= r) {
757 m = l + (r - l) / 2;
758 if (block < le32_to_cpu(m->ei_block))
759 r = m - 1;
760 else
761 l = m + 1;
Olivier Deprez157378f2022-04-04 15:47:50 +0200762 ext_debug(inode, "%p(%u):%p(%u):%p(%u) ", l,
763 le32_to_cpu(l->ei_block), m, le32_to_cpu(m->ei_block),
764 r, le32_to_cpu(r->ei_block));
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000765 }
766
767 path->p_idx = l - 1;
Olivier Deprez157378f2022-04-04 15:47:50 +0200768 ext_debug(inode, " -> %u->%lld ", le32_to_cpu(path->p_idx->ei_block),
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000769 ext4_idx_pblock(path->p_idx));
770
771#ifdef CHECK_BINSEARCH
772 {
773 struct ext4_extent_idx *chix, *ix;
774 int k;
775
776 chix = ix = EXT_FIRST_INDEX(eh);
777 for (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ix++) {
Olivier Deprez157378f2022-04-04 15:47:50 +0200778 if (k != 0 && le32_to_cpu(ix->ei_block) <=
779 le32_to_cpu(ix[-1].ei_block)) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000780 printk(KERN_DEBUG "k=%d, ix=0x%p, "
781 "first=0x%p\n", k,
782 ix, EXT_FIRST_INDEX(eh));
783 printk(KERN_DEBUG "%u <= %u\n",
784 le32_to_cpu(ix->ei_block),
785 le32_to_cpu(ix[-1].ei_block));
786 }
787 BUG_ON(k && le32_to_cpu(ix->ei_block)
788 <= le32_to_cpu(ix[-1].ei_block));
789 if (block < le32_to_cpu(ix->ei_block))
790 break;
791 chix = ix;
792 }
793 BUG_ON(chix != path->p_idx);
794 }
795#endif
796
797}
798
799/*
800 * ext4_ext_binsearch:
801 * binary search for closest extent of the given block
802 * the header must be checked before calling this
803 */
804static void
805ext4_ext_binsearch(struct inode *inode,
806 struct ext4_ext_path *path, ext4_lblk_t block)
807{
808 struct ext4_extent_header *eh = path->p_hdr;
809 struct ext4_extent *r, *l, *m;
810
811 if (eh->eh_entries == 0) {
812 /*
813 * this leaf is empty:
814 * we get such a leaf in split/add case
815 */
816 return;
817 }
818
Olivier Deprez157378f2022-04-04 15:47:50 +0200819 ext_debug(inode, "binsearch for %u: ", block);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000820
821 l = EXT_FIRST_EXTENT(eh) + 1;
822 r = EXT_LAST_EXTENT(eh);
823
824 while (l <= r) {
825 m = l + (r - l) / 2;
826 if (block < le32_to_cpu(m->ee_block))
827 r = m - 1;
828 else
829 l = m + 1;
Olivier Deprez157378f2022-04-04 15:47:50 +0200830 ext_debug(inode, "%p(%u):%p(%u):%p(%u) ", l,
831 le32_to_cpu(l->ee_block), m, le32_to_cpu(m->ee_block),
832 r, le32_to_cpu(r->ee_block));
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000833 }
834
835 path->p_ext = l - 1;
Olivier Deprez157378f2022-04-04 15:47:50 +0200836 ext_debug(inode, " -> %d:%llu:[%d]%d ",
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000837 le32_to_cpu(path->p_ext->ee_block),
838 ext4_ext_pblock(path->p_ext),
839 ext4_ext_is_unwritten(path->p_ext),
840 ext4_ext_get_actual_len(path->p_ext));
841
842#ifdef CHECK_BINSEARCH
843 {
844 struct ext4_extent *chex, *ex;
845 int k;
846
847 chex = ex = EXT_FIRST_EXTENT(eh);
848 for (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ex++) {
849 BUG_ON(k && le32_to_cpu(ex->ee_block)
850 <= le32_to_cpu(ex[-1].ee_block));
851 if (block < le32_to_cpu(ex->ee_block))
852 break;
853 chex = ex;
854 }
855 BUG_ON(chex != path->p_ext);
856 }
857#endif
858
859}
860
Olivier Deprez157378f2022-04-04 15:47:50 +0200861void ext4_ext_tree_init(handle_t *handle, struct inode *inode)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000862{
863 struct ext4_extent_header *eh;
864
865 eh = ext_inode_hdr(inode);
866 eh->eh_depth = 0;
867 eh->eh_entries = 0;
868 eh->eh_magic = EXT4_EXT_MAGIC;
869 eh->eh_max = cpu_to_le16(ext4_ext_space_root(inode, 0));
Olivier Deprez0e641232021-09-23 10:07:05 +0200870 eh->eh_generation = 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000871 ext4_mark_inode_dirty(handle, inode);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000872}
873
874struct ext4_ext_path *
875ext4_find_extent(struct inode *inode, ext4_lblk_t block,
876 struct ext4_ext_path **orig_path, int flags)
877{
878 struct ext4_extent_header *eh;
879 struct buffer_head *bh;
880 struct ext4_ext_path *path = orig_path ? *orig_path : NULL;
881 short int depth, i, ppos = 0;
882 int ret;
Olivier Deprez157378f2022-04-04 15:47:50 +0200883 gfp_t gfp_flags = GFP_NOFS;
884
885 if (flags & EXT4_EX_NOFAIL)
886 gfp_flags |= __GFP_NOFAIL;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000887
888 eh = ext_inode_hdr(inode);
889 depth = ext_depth(inode);
890 if (depth < 0 || depth > EXT4_MAX_EXTENT_DEPTH) {
891 EXT4_ERROR_INODE(inode, "inode has invalid extent depth: %d",
892 depth);
893 ret = -EFSCORRUPTED;
894 goto err;
895 }
896
897 if (path) {
898 ext4_ext_drop_refs(path);
899 if (depth > path[0].p_maxdepth) {
900 kfree(path);
901 *orig_path = path = NULL;
902 }
903 }
904 if (!path) {
905 /* account possible depth increase */
906 path = kcalloc(depth + 2, sizeof(struct ext4_ext_path),
Olivier Deprez157378f2022-04-04 15:47:50 +0200907 gfp_flags);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000908 if (unlikely(!path))
909 return ERR_PTR(-ENOMEM);
910 path[0].p_maxdepth = depth + 1;
911 }
912 path[0].p_hdr = eh;
913 path[0].p_bh = NULL;
914
915 i = depth;
Olivier Deprez0e641232021-09-23 10:07:05 +0200916 if (!(flags & EXT4_EX_NOCACHE) && depth == 0)
917 ext4_cache_extents(inode, eh);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000918 /* walk through the tree */
919 while (i) {
Olivier Deprez157378f2022-04-04 15:47:50 +0200920 ext_debug(inode, "depth %d: num %d, max %d\n",
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000921 ppos, le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
922
923 ext4_ext_binsearch_idx(inode, path + ppos, block);
924 path[ppos].p_block = ext4_idx_pblock(path[ppos].p_idx);
925 path[ppos].p_depth = i;
926 path[ppos].p_ext = NULL;
927
Olivier Deprez157378f2022-04-04 15:47:50 +0200928 bh = read_extent_tree_block(inode, path[ppos].p_idx, --i, flags);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000929 if (IS_ERR(bh)) {
930 ret = PTR_ERR(bh);
931 goto err;
932 }
933
934 eh = ext_block_hdr(bh);
935 ppos++;
936 path[ppos].p_bh = bh;
937 path[ppos].p_hdr = eh;
938 }
939
940 path[ppos].p_depth = i;
941 path[ppos].p_ext = NULL;
942 path[ppos].p_idx = NULL;
943
944 /* find extent */
945 ext4_ext_binsearch(inode, path + ppos, block);
946 /* if not an empty leaf */
947 if (path[ppos].p_ext)
948 path[ppos].p_block = ext4_ext_pblock(path[ppos].p_ext);
949
950 ext4_ext_show_path(inode, path);
951
952 return path;
953
954err:
955 ext4_ext_drop_refs(path);
956 kfree(path);
957 if (orig_path)
958 *orig_path = NULL;
959 return ERR_PTR(ret);
960}
961
962/*
963 * ext4_ext_insert_index:
964 * insert new index [@logical;@ptr] into the block at @curp;
965 * check where to insert: before @curp or after @curp
966 */
967static int ext4_ext_insert_index(handle_t *handle, struct inode *inode,
968 struct ext4_ext_path *curp,
969 int logical, ext4_fsblk_t ptr)
970{
971 struct ext4_extent_idx *ix;
972 int len, err;
973
974 err = ext4_ext_get_access(handle, inode, curp);
975 if (err)
976 return err;
977
978 if (unlikely(logical == le32_to_cpu(curp->p_idx->ei_block))) {
979 EXT4_ERROR_INODE(inode,
980 "logical %d == ei_block %d!",
981 logical, le32_to_cpu(curp->p_idx->ei_block));
982 return -EFSCORRUPTED;
983 }
984
985 if (unlikely(le16_to_cpu(curp->p_hdr->eh_entries)
986 >= le16_to_cpu(curp->p_hdr->eh_max))) {
987 EXT4_ERROR_INODE(inode,
988 "eh_entries %d >= eh_max %d!",
989 le16_to_cpu(curp->p_hdr->eh_entries),
990 le16_to_cpu(curp->p_hdr->eh_max));
991 return -EFSCORRUPTED;
992 }
993
994 if (logical > le32_to_cpu(curp->p_idx->ei_block)) {
995 /* insert after */
Olivier Deprez157378f2022-04-04 15:47:50 +0200996 ext_debug(inode, "insert new index %d after: %llu\n",
997 logical, ptr);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000998 ix = curp->p_idx + 1;
999 } else {
1000 /* insert before */
Olivier Deprez157378f2022-04-04 15:47:50 +02001001 ext_debug(inode, "insert new index %d before: %llu\n",
1002 logical, ptr);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001003 ix = curp->p_idx;
1004 }
1005
1006 len = EXT_LAST_INDEX(curp->p_hdr) - ix + 1;
1007 BUG_ON(len < 0);
1008 if (len > 0) {
Olivier Deprez157378f2022-04-04 15:47:50 +02001009 ext_debug(inode, "insert new index %d: "
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001010 "move %d indices from 0x%p to 0x%p\n",
1011 logical, len, ix, ix + 1);
1012 memmove(ix + 1, ix, len * sizeof(struct ext4_extent_idx));
1013 }
1014
1015 if (unlikely(ix > EXT_MAX_INDEX(curp->p_hdr))) {
1016 EXT4_ERROR_INODE(inode, "ix > EXT_MAX_INDEX!");
1017 return -EFSCORRUPTED;
1018 }
1019
1020 ix->ei_block = cpu_to_le32(logical);
1021 ext4_idx_store_pblock(ix, ptr);
1022 le16_add_cpu(&curp->p_hdr->eh_entries, 1);
1023
1024 if (unlikely(ix > EXT_LAST_INDEX(curp->p_hdr))) {
1025 EXT4_ERROR_INODE(inode, "ix > EXT_LAST_INDEX!");
1026 return -EFSCORRUPTED;
1027 }
1028
1029 err = ext4_ext_dirty(handle, inode, curp);
1030 ext4_std_error(inode->i_sb, err);
1031
1032 return err;
1033}
1034
1035/*
1036 * ext4_ext_split:
1037 * inserts new subtree into the path, using free index entry
1038 * at depth @at:
1039 * - allocates all needed blocks (new leaf and all intermediate index blocks)
1040 * - makes decision where to split
1041 * - moves remaining extents and index entries (right to the split point)
1042 * into the newly allocated blocks
1043 * - initializes subtree
1044 */
1045static int ext4_ext_split(handle_t *handle, struct inode *inode,
1046 unsigned int flags,
1047 struct ext4_ext_path *path,
1048 struct ext4_extent *newext, int at)
1049{
1050 struct buffer_head *bh = NULL;
1051 int depth = ext_depth(inode);
1052 struct ext4_extent_header *neh;
1053 struct ext4_extent_idx *fidx;
1054 int i = at, k, m, a;
1055 ext4_fsblk_t newblock, oldblock;
1056 __le32 border;
1057 ext4_fsblk_t *ablocks = NULL; /* array of allocated blocks */
Olivier Deprez157378f2022-04-04 15:47:50 +02001058 gfp_t gfp_flags = GFP_NOFS;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001059 int err = 0;
David Brazdil0f672f62019-12-10 10:32:29 +00001060 size_t ext_size = 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001061
Olivier Deprez157378f2022-04-04 15:47:50 +02001062 if (flags & EXT4_EX_NOFAIL)
1063 gfp_flags |= __GFP_NOFAIL;
1064
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001065 /* make decision: where to split? */
1066 /* FIXME: now decision is simplest: at current extent */
1067
1068 /* if current leaf will be split, then we should use
1069 * border from split point */
1070 if (unlikely(path[depth].p_ext > EXT_MAX_EXTENT(path[depth].p_hdr))) {
1071 EXT4_ERROR_INODE(inode, "p_ext > EXT_MAX_EXTENT!");
1072 return -EFSCORRUPTED;
1073 }
1074 if (path[depth].p_ext != EXT_MAX_EXTENT(path[depth].p_hdr)) {
1075 border = path[depth].p_ext[1].ee_block;
Olivier Deprez157378f2022-04-04 15:47:50 +02001076 ext_debug(inode, "leaf will be split."
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001077 " next leaf starts at %d\n",
1078 le32_to_cpu(border));
1079 } else {
1080 border = newext->ee_block;
Olivier Deprez157378f2022-04-04 15:47:50 +02001081 ext_debug(inode, "leaf will be added."
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001082 " next leaf starts at %d\n",
1083 le32_to_cpu(border));
1084 }
1085
1086 /*
1087 * If error occurs, then we break processing
1088 * and mark filesystem read-only. index won't
1089 * be inserted and tree will be in consistent
1090 * state. Next mount will repair buffers too.
1091 */
1092
1093 /*
1094 * Get array to track all allocated blocks.
1095 * We need this to handle errors and free blocks
1096 * upon them.
1097 */
Olivier Deprez157378f2022-04-04 15:47:50 +02001098 ablocks = kcalloc(depth, sizeof(ext4_fsblk_t), gfp_flags);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001099 if (!ablocks)
1100 return -ENOMEM;
1101
1102 /* allocate all needed blocks */
Olivier Deprez157378f2022-04-04 15:47:50 +02001103 ext_debug(inode, "allocate %d blocks for indexes/leaf\n", depth - at);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001104 for (a = 0; a < depth - at; a++) {
1105 newblock = ext4_ext_new_meta_block(handle, inode, path,
1106 newext, &err, flags);
1107 if (newblock == 0)
1108 goto cleanup;
1109 ablocks[a] = newblock;
1110 }
1111
1112 /* initialize new leaf */
1113 newblock = ablocks[--a];
1114 if (unlikely(newblock == 0)) {
1115 EXT4_ERROR_INODE(inode, "newblock == 0!");
1116 err = -EFSCORRUPTED;
1117 goto cleanup;
1118 }
1119 bh = sb_getblk_gfp(inode->i_sb, newblock, __GFP_MOVABLE | GFP_NOFS);
1120 if (unlikely(!bh)) {
1121 err = -ENOMEM;
1122 goto cleanup;
1123 }
1124 lock_buffer(bh);
1125
1126 err = ext4_journal_get_create_access(handle, bh);
1127 if (err)
1128 goto cleanup;
1129
1130 neh = ext_block_hdr(bh);
1131 neh->eh_entries = 0;
1132 neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0));
1133 neh->eh_magic = EXT4_EXT_MAGIC;
1134 neh->eh_depth = 0;
Olivier Deprez0e641232021-09-23 10:07:05 +02001135 neh->eh_generation = 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001136
1137 /* move remainder of path[depth] to the new leaf */
1138 if (unlikely(path[depth].p_hdr->eh_entries !=
1139 path[depth].p_hdr->eh_max)) {
1140 EXT4_ERROR_INODE(inode, "eh_entries %d != eh_max %d!",
1141 path[depth].p_hdr->eh_entries,
1142 path[depth].p_hdr->eh_max);
1143 err = -EFSCORRUPTED;
1144 goto cleanup;
1145 }
1146 /* start copy from next extent */
1147 m = EXT_MAX_EXTENT(path[depth].p_hdr) - path[depth].p_ext++;
1148 ext4_ext_show_move(inode, path, newblock, depth);
1149 if (m) {
1150 struct ext4_extent *ex;
1151 ex = EXT_FIRST_EXTENT(neh);
1152 memmove(ex, path[depth].p_ext, sizeof(struct ext4_extent) * m);
1153 le16_add_cpu(&neh->eh_entries, m);
1154 }
1155
David Brazdil0f672f62019-12-10 10:32:29 +00001156 /* zero out unused area in the extent block */
1157 ext_size = sizeof(struct ext4_extent_header) +
1158 sizeof(struct ext4_extent) * le16_to_cpu(neh->eh_entries);
1159 memset(bh->b_data + ext_size, 0, inode->i_sb->s_blocksize - ext_size);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001160 ext4_extent_block_csum_set(inode, neh);
1161 set_buffer_uptodate(bh);
1162 unlock_buffer(bh);
1163
1164 err = ext4_handle_dirty_metadata(handle, inode, bh);
1165 if (err)
1166 goto cleanup;
1167 brelse(bh);
1168 bh = NULL;
1169
1170 /* correct old leaf */
1171 if (m) {
1172 err = ext4_ext_get_access(handle, inode, path + depth);
1173 if (err)
1174 goto cleanup;
1175 le16_add_cpu(&path[depth].p_hdr->eh_entries, -m);
1176 err = ext4_ext_dirty(handle, inode, path + depth);
1177 if (err)
1178 goto cleanup;
1179
1180 }
1181
1182 /* create intermediate indexes */
1183 k = depth - at - 1;
1184 if (unlikely(k < 0)) {
1185 EXT4_ERROR_INODE(inode, "k %d < 0!", k);
1186 err = -EFSCORRUPTED;
1187 goto cleanup;
1188 }
1189 if (k)
Olivier Deprez157378f2022-04-04 15:47:50 +02001190 ext_debug(inode, "create %d intermediate indices\n", k);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001191 /* insert new index into current index block */
1192 /* current depth stored in i var */
1193 i = depth - 1;
1194 while (k--) {
1195 oldblock = newblock;
1196 newblock = ablocks[--a];
1197 bh = sb_getblk(inode->i_sb, newblock);
1198 if (unlikely(!bh)) {
1199 err = -ENOMEM;
1200 goto cleanup;
1201 }
1202 lock_buffer(bh);
1203
1204 err = ext4_journal_get_create_access(handle, bh);
1205 if (err)
1206 goto cleanup;
1207
1208 neh = ext_block_hdr(bh);
1209 neh->eh_entries = cpu_to_le16(1);
1210 neh->eh_magic = EXT4_EXT_MAGIC;
1211 neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0));
1212 neh->eh_depth = cpu_to_le16(depth - i);
Olivier Deprez0e641232021-09-23 10:07:05 +02001213 neh->eh_generation = 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001214 fidx = EXT_FIRST_INDEX(neh);
1215 fidx->ei_block = border;
1216 ext4_idx_store_pblock(fidx, oldblock);
1217
Olivier Deprez157378f2022-04-04 15:47:50 +02001218 ext_debug(inode, "int.index at %d (block %llu): %u -> %llu\n",
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001219 i, newblock, le32_to_cpu(border), oldblock);
1220
1221 /* move remainder of path[i] to the new index block */
1222 if (unlikely(EXT_MAX_INDEX(path[i].p_hdr) !=
1223 EXT_LAST_INDEX(path[i].p_hdr))) {
1224 EXT4_ERROR_INODE(inode,
1225 "EXT_MAX_INDEX != EXT_LAST_INDEX ee_block %d!",
1226 le32_to_cpu(path[i].p_ext->ee_block));
1227 err = -EFSCORRUPTED;
1228 goto cleanup;
1229 }
1230 /* start copy indexes */
1231 m = EXT_MAX_INDEX(path[i].p_hdr) - path[i].p_idx++;
Olivier Deprez157378f2022-04-04 15:47:50 +02001232 ext_debug(inode, "cur 0x%p, last 0x%p\n", path[i].p_idx,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001233 EXT_MAX_INDEX(path[i].p_hdr));
1234 ext4_ext_show_move(inode, path, newblock, i);
1235 if (m) {
1236 memmove(++fidx, path[i].p_idx,
1237 sizeof(struct ext4_extent_idx) * m);
1238 le16_add_cpu(&neh->eh_entries, m);
1239 }
David Brazdil0f672f62019-12-10 10:32:29 +00001240 /* zero out unused area in the extent block */
1241 ext_size = sizeof(struct ext4_extent_header) +
1242 (sizeof(struct ext4_extent) * le16_to_cpu(neh->eh_entries));
1243 memset(bh->b_data + ext_size, 0,
1244 inode->i_sb->s_blocksize - ext_size);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001245 ext4_extent_block_csum_set(inode, neh);
1246 set_buffer_uptodate(bh);
1247 unlock_buffer(bh);
1248
1249 err = ext4_handle_dirty_metadata(handle, inode, bh);
1250 if (err)
1251 goto cleanup;
1252 brelse(bh);
1253 bh = NULL;
1254
1255 /* correct old index */
1256 if (m) {
1257 err = ext4_ext_get_access(handle, inode, path + i);
1258 if (err)
1259 goto cleanup;
1260 le16_add_cpu(&path[i].p_hdr->eh_entries, -m);
1261 err = ext4_ext_dirty(handle, inode, path + i);
1262 if (err)
1263 goto cleanup;
1264 }
1265
1266 i--;
1267 }
1268
1269 /* insert new index */
1270 err = ext4_ext_insert_index(handle, inode, path + at,
1271 le32_to_cpu(border), newblock);
1272
1273cleanup:
1274 if (bh) {
1275 if (buffer_locked(bh))
1276 unlock_buffer(bh);
1277 brelse(bh);
1278 }
1279
1280 if (err) {
1281 /* free all allocated blocks in error case */
1282 for (i = 0; i < depth; i++) {
1283 if (!ablocks[i])
1284 continue;
1285 ext4_free_blocks(handle, inode, NULL, ablocks[i], 1,
1286 EXT4_FREE_BLOCKS_METADATA);
1287 }
1288 }
1289 kfree(ablocks);
1290
1291 return err;
1292}
1293
1294/*
1295 * ext4_ext_grow_indepth:
1296 * implements tree growing procedure:
1297 * - allocates new block
1298 * - moves top-level data (index block or leaf) into the new block
1299 * - initializes new top-level, creating index that points to the
1300 * just created block
1301 */
1302static int ext4_ext_grow_indepth(handle_t *handle, struct inode *inode,
1303 unsigned int flags)
1304{
1305 struct ext4_extent_header *neh;
1306 struct buffer_head *bh;
1307 ext4_fsblk_t newblock, goal = 0;
1308 struct ext4_super_block *es = EXT4_SB(inode->i_sb)->s_es;
1309 int err = 0;
David Brazdil0f672f62019-12-10 10:32:29 +00001310 size_t ext_size = 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001311
1312 /* Try to prepend new index to old one */
1313 if (ext_depth(inode))
1314 goal = ext4_idx_pblock(EXT_FIRST_INDEX(ext_inode_hdr(inode)));
1315 if (goal > le32_to_cpu(es->s_first_data_block)) {
1316 flags |= EXT4_MB_HINT_TRY_GOAL;
1317 goal--;
1318 } else
1319 goal = ext4_inode_to_goal_block(inode);
1320 newblock = ext4_new_meta_blocks(handle, inode, goal, flags,
1321 NULL, &err);
1322 if (newblock == 0)
1323 return err;
1324
1325 bh = sb_getblk_gfp(inode->i_sb, newblock, __GFP_MOVABLE | GFP_NOFS);
1326 if (unlikely(!bh))
1327 return -ENOMEM;
1328 lock_buffer(bh);
1329
1330 err = ext4_journal_get_create_access(handle, bh);
1331 if (err) {
1332 unlock_buffer(bh);
1333 goto out;
1334 }
1335
David Brazdil0f672f62019-12-10 10:32:29 +00001336 ext_size = sizeof(EXT4_I(inode)->i_data);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001337 /* move top-level index/leaf into new block */
David Brazdil0f672f62019-12-10 10:32:29 +00001338 memmove(bh->b_data, EXT4_I(inode)->i_data, ext_size);
1339 /* zero out unused area in the extent block */
1340 memset(bh->b_data + ext_size, 0, inode->i_sb->s_blocksize - ext_size);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001341
1342 /* set size of new block */
1343 neh = ext_block_hdr(bh);
1344 /* old root could have indexes or leaves
1345 * so calculate e_max right way */
1346 if (ext_depth(inode))
1347 neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0));
1348 else
1349 neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0));
1350 neh->eh_magic = EXT4_EXT_MAGIC;
1351 ext4_extent_block_csum_set(inode, neh);
1352 set_buffer_uptodate(bh);
1353 unlock_buffer(bh);
1354
1355 err = ext4_handle_dirty_metadata(handle, inode, bh);
1356 if (err)
1357 goto out;
1358
1359 /* Update top-level index: num,max,pointer */
1360 neh = ext_inode_hdr(inode);
1361 neh->eh_entries = cpu_to_le16(1);
1362 ext4_idx_store_pblock(EXT_FIRST_INDEX(neh), newblock);
1363 if (neh->eh_depth == 0) {
1364 /* Root extent block becomes index block */
1365 neh->eh_max = cpu_to_le16(ext4_ext_space_root_idx(inode, 0));
1366 EXT_FIRST_INDEX(neh)->ei_block =
1367 EXT_FIRST_EXTENT(neh)->ee_block;
1368 }
Olivier Deprez157378f2022-04-04 15:47:50 +02001369 ext_debug(inode, "new root: num %d(%d), lblock %d, ptr %llu\n",
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001370 le16_to_cpu(neh->eh_entries), le16_to_cpu(neh->eh_max),
1371 le32_to_cpu(EXT_FIRST_INDEX(neh)->ei_block),
1372 ext4_idx_pblock(EXT_FIRST_INDEX(neh)));
1373
1374 le16_add_cpu(&neh->eh_depth, 1);
Olivier Deprez157378f2022-04-04 15:47:50 +02001375 err = ext4_mark_inode_dirty(handle, inode);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001376out:
1377 brelse(bh);
1378
1379 return err;
1380}
1381
1382/*
1383 * ext4_ext_create_new_leaf:
1384 * finds empty index and adds new leaf.
1385 * if no free index is found, then it requests in-depth growing.
1386 */
1387static int ext4_ext_create_new_leaf(handle_t *handle, struct inode *inode,
1388 unsigned int mb_flags,
1389 unsigned int gb_flags,
1390 struct ext4_ext_path **ppath,
1391 struct ext4_extent *newext)
1392{
1393 struct ext4_ext_path *path = *ppath;
1394 struct ext4_ext_path *curp;
1395 int depth, i, err = 0;
1396
1397repeat:
1398 i = depth = ext_depth(inode);
1399
1400 /* walk up to the tree and look for free index entry */
1401 curp = path + depth;
1402 while (i > 0 && !EXT_HAS_FREE_INDEX(curp)) {
1403 i--;
1404 curp--;
1405 }
1406
1407 /* we use already allocated block for index block,
1408 * so subsequent data blocks should be contiguous */
1409 if (EXT_HAS_FREE_INDEX(curp)) {
1410 /* if we found index with free entry, then use that
1411 * entry: create all needed subtree and add new leaf */
1412 err = ext4_ext_split(handle, inode, mb_flags, path, newext, i);
1413 if (err)
1414 goto out;
1415
1416 /* refill path */
1417 path = ext4_find_extent(inode,
1418 (ext4_lblk_t)le32_to_cpu(newext->ee_block),
1419 ppath, gb_flags);
1420 if (IS_ERR(path))
1421 err = PTR_ERR(path);
1422 } else {
1423 /* tree is full, time to grow in depth */
1424 err = ext4_ext_grow_indepth(handle, inode, mb_flags);
1425 if (err)
1426 goto out;
1427
1428 /* refill path */
1429 path = ext4_find_extent(inode,
1430 (ext4_lblk_t)le32_to_cpu(newext->ee_block),
1431 ppath, gb_flags);
1432 if (IS_ERR(path)) {
1433 err = PTR_ERR(path);
1434 goto out;
1435 }
1436
1437 /*
1438 * only first (depth 0 -> 1) produces free space;
1439 * in all other cases we have to split the grown tree
1440 */
1441 depth = ext_depth(inode);
1442 if (path[depth].p_hdr->eh_entries == path[depth].p_hdr->eh_max) {
1443 /* now we need to split */
1444 goto repeat;
1445 }
1446 }
1447
1448out:
1449 return err;
1450}
1451
1452/*
1453 * search the closest allocated block to the left for *logical
1454 * and returns it at @logical + it's physical address at @phys
1455 * if *logical is the smallest allocated block, the function
1456 * returns 0 at @phys
1457 * return value contains 0 (success) or error code
1458 */
1459static int ext4_ext_search_left(struct inode *inode,
1460 struct ext4_ext_path *path,
1461 ext4_lblk_t *logical, ext4_fsblk_t *phys)
1462{
1463 struct ext4_extent_idx *ix;
1464 struct ext4_extent *ex;
1465 int depth, ee_len;
1466
1467 if (unlikely(path == NULL)) {
1468 EXT4_ERROR_INODE(inode, "path == NULL *logical %d!", *logical);
1469 return -EFSCORRUPTED;
1470 }
1471 depth = path->p_depth;
1472 *phys = 0;
1473
1474 if (depth == 0 && path->p_ext == NULL)
1475 return 0;
1476
1477 /* usually extent in the path covers blocks smaller
1478 * then *logical, but it can be that extent is the
1479 * first one in the file */
1480
1481 ex = path[depth].p_ext;
1482 ee_len = ext4_ext_get_actual_len(ex);
1483 if (*logical < le32_to_cpu(ex->ee_block)) {
1484 if (unlikely(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex)) {
1485 EXT4_ERROR_INODE(inode,
1486 "EXT_FIRST_EXTENT != ex *logical %d ee_block %d!",
1487 *logical, le32_to_cpu(ex->ee_block));
1488 return -EFSCORRUPTED;
1489 }
1490 while (--depth >= 0) {
1491 ix = path[depth].p_idx;
1492 if (unlikely(ix != EXT_FIRST_INDEX(path[depth].p_hdr))) {
1493 EXT4_ERROR_INODE(inode,
1494 "ix (%d) != EXT_FIRST_INDEX (%d) (depth %d)!",
1495 ix != NULL ? le32_to_cpu(ix->ei_block) : 0,
1496 EXT_FIRST_INDEX(path[depth].p_hdr) != NULL ?
1497 le32_to_cpu(EXT_FIRST_INDEX(path[depth].p_hdr)->ei_block) : 0,
1498 depth);
1499 return -EFSCORRUPTED;
1500 }
1501 }
1502 return 0;
1503 }
1504
1505 if (unlikely(*logical < (le32_to_cpu(ex->ee_block) + ee_len))) {
1506 EXT4_ERROR_INODE(inode,
1507 "logical %d < ee_block %d + ee_len %d!",
1508 *logical, le32_to_cpu(ex->ee_block), ee_len);
1509 return -EFSCORRUPTED;
1510 }
1511
1512 *logical = le32_to_cpu(ex->ee_block) + ee_len - 1;
1513 *phys = ext4_ext_pblock(ex) + ee_len - 1;
1514 return 0;
1515}
1516
1517/*
Olivier Deprez157378f2022-04-04 15:47:50 +02001518 * Search the closest allocated block to the right for *logical
1519 * and returns it at @logical + it's physical address at @phys.
1520 * If not exists, return 0 and @phys is set to 0. We will return
1521 * 1 which means we found an allocated block and ret_ex is valid.
1522 * Or return a (< 0) error code.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001523 */
1524static int ext4_ext_search_right(struct inode *inode,
1525 struct ext4_ext_path *path,
1526 ext4_lblk_t *logical, ext4_fsblk_t *phys,
Olivier Deprez157378f2022-04-04 15:47:50 +02001527 struct ext4_extent *ret_ex)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001528{
1529 struct buffer_head *bh = NULL;
1530 struct ext4_extent_header *eh;
1531 struct ext4_extent_idx *ix;
1532 struct ext4_extent *ex;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001533 int depth; /* Note, NOT eh_depth; depth from top of tree */
1534 int ee_len;
1535
1536 if (unlikely(path == NULL)) {
1537 EXT4_ERROR_INODE(inode, "path == NULL *logical %d!", *logical);
1538 return -EFSCORRUPTED;
1539 }
1540 depth = path->p_depth;
1541 *phys = 0;
1542
1543 if (depth == 0 && path->p_ext == NULL)
1544 return 0;
1545
1546 /* usually extent in the path covers blocks smaller
1547 * then *logical, but it can be that extent is the
1548 * first one in the file */
1549
1550 ex = path[depth].p_ext;
1551 ee_len = ext4_ext_get_actual_len(ex);
1552 if (*logical < le32_to_cpu(ex->ee_block)) {
1553 if (unlikely(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex)) {
1554 EXT4_ERROR_INODE(inode,
1555 "first_extent(path[%d].p_hdr) != ex",
1556 depth);
1557 return -EFSCORRUPTED;
1558 }
1559 while (--depth >= 0) {
1560 ix = path[depth].p_idx;
1561 if (unlikely(ix != EXT_FIRST_INDEX(path[depth].p_hdr))) {
1562 EXT4_ERROR_INODE(inode,
1563 "ix != EXT_FIRST_INDEX *logical %d!",
1564 *logical);
1565 return -EFSCORRUPTED;
1566 }
1567 }
1568 goto found_extent;
1569 }
1570
1571 if (unlikely(*logical < (le32_to_cpu(ex->ee_block) + ee_len))) {
1572 EXT4_ERROR_INODE(inode,
1573 "logical %d < ee_block %d + ee_len %d!",
1574 *logical, le32_to_cpu(ex->ee_block), ee_len);
1575 return -EFSCORRUPTED;
1576 }
1577
1578 if (ex != EXT_LAST_EXTENT(path[depth].p_hdr)) {
1579 /* next allocated block in this leaf */
1580 ex++;
1581 goto found_extent;
1582 }
1583
1584 /* go up and search for index to the right */
1585 while (--depth >= 0) {
1586 ix = path[depth].p_idx;
1587 if (ix != EXT_LAST_INDEX(path[depth].p_hdr))
1588 goto got_index;
1589 }
1590
1591 /* we've gone up to the root and found no index to the right */
1592 return 0;
1593
1594got_index:
1595 /* we've found index to the right, let's
1596 * follow it and find the closest allocated
1597 * block to the right */
1598 ix++;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001599 while (++depth < path->p_depth) {
1600 /* subtract from p_depth to get proper eh_depth */
Olivier Deprez157378f2022-04-04 15:47:50 +02001601 bh = read_extent_tree_block(inode, ix, path->p_depth - depth, 0);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001602 if (IS_ERR(bh))
1603 return PTR_ERR(bh);
1604 eh = ext_block_hdr(bh);
1605 ix = EXT_FIRST_INDEX(eh);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001606 put_bh(bh);
1607 }
1608
Olivier Deprez157378f2022-04-04 15:47:50 +02001609 bh = read_extent_tree_block(inode, ix, path->p_depth - depth, 0);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001610 if (IS_ERR(bh))
1611 return PTR_ERR(bh);
1612 eh = ext_block_hdr(bh);
1613 ex = EXT_FIRST_EXTENT(eh);
1614found_extent:
1615 *logical = le32_to_cpu(ex->ee_block);
1616 *phys = ext4_ext_pblock(ex);
Olivier Deprez157378f2022-04-04 15:47:50 +02001617 if (ret_ex)
1618 *ret_ex = *ex;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001619 if (bh)
1620 put_bh(bh);
Olivier Deprez157378f2022-04-04 15:47:50 +02001621 return 1;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001622}
1623
1624/*
1625 * ext4_ext_next_allocated_block:
1626 * returns allocated block in subsequent extent or EXT_MAX_BLOCKS.
1627 * NOTE: it considers block number from index entry as
1628 * allocated block. Thus, index entries have to be consistent
1629 * with leaves.
1630 */
1631ext4_lblk_t
1632ext4_ext_next_allocated_block(struct ext4_ext_path *path)
1633{
1634 int depth;
1635
1636 BUG_ON(path == NULL);
1637 depth = path->p_depth;
1638
1639 if (depth == 0 && path->p_ext == NULL)
1640 return EXT_MAX_BLOCKS;
1641
1642 while (depth >= 0) {
Olivier Deprez157378f2022-04-04 15:47:50 +02001643 struct ext4_ext_path *p = &path[depth];
1644
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001645 if (depth == path->p_depth) {
1646 /* leaf */
Olivier Deprez157378f2022-04-04 15:47:50 +02001647 if (p->p_ext && p->p_ext != EXT_LAST_EXTENT(p->p_hdr))
1648 return le32_to_cpu(p->p_ext[1].ee_block);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001649 } else {
1650 /* index */
Olivier Deprez157378f2022-04-04 15:47:50 +02001651 if (p->p_idx != EXT_LAST_INDEX(p->p_hdr))
1652 return le32_to_cpu(p->p_idx[1].ei_block);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001653 }
1654 depth--;
1655 }
1656
1657 return EXT_MAX_BLOCKS;
1658}
1659
1660/*
1661 * ext4_ext_next_leaf_block:
1662 * returns first allocated block from next leaf or EXT_MAX_BLOCKS
1663 */
1664static ext4_lblk_t ext4_ext_next_leaf_block(struct ext4_ext_path *path)
1665{
1666 int depth;
1667
1668 BUG_ON(path == NULL);
1669 depth = path->p_depth;
1670
1671 /* zero-tree has no leaf blocks at all */
1672 if (depth == 0)
1673 return EXT_MAX_BLOCKS;
1674
1675 /* go to index block */
1676 depth--;
1677
1678 while (depth >= 0) {
1679 if (path[depth].p_idx !=
1680 EXT_LAST_INDEX(path[depth].p_hdr))
1681 return (ext4_lblk_t)
1682 le32_to_cpu(path[depth].p_idx[1].ei_block);
1683 depth--;
1684 }
1685
1686 return EXT_MAX_BLOCKS;
1687}
1688
1689/*
1690 * ext4_ext_correct_indexes:
1691 * if leaf gets modified and modified extent is first in the leaf,
1692 * then we have to correct all indexes above.
1693 * TODO: do we need to correct tree in all cases?
1694 */
1695static int ext4_ext_correct_indexes(handle_t *handle, struct inode *inode,
1696 struct ext4_ext_path *path)
1697{
1698 struct ext4_extent_header *eh;
1699 int depth = ext_depth(inode);
1700 struct ext4_extent *ex;
1701 __le32 border;
1702 int k, err = 0;
1703
1704 eh = path[depth].p_hdr;
1705 ex = path[depth].p_ext;
1706
1707 if (unlikely(ex == NULL || eh == NULL)) {
1708 EXT4_ERROR_INODE(inode,
1709 "ex %p == NULL or eh %p == NULL", ex, eh);
1710 return -EFSCORRUPTED;
1711 }
1712
1713 if (depth == 0) {
1714 /* there is no tree at all */
1715 return 0;
1716 }
1717
1718 if (ex != EXT_FIRST_EXTENT(eh)) {
1719 /* we correct tree if first leaf got modified only */
1720 return 0;
1721 }
1722
1723 /*
1724 * TODO: we need correction if border is smaller than current one
1725 */
1726 k = depth - 1;
1727 border = path[depth].p_ext->ee_block;
1728 err = ext4_ext_get_access(handle, inode, path + k);
1729 if (err)
1730 return err;
1731 path[k].p_idx->ei_block = border;
1732 err = ext4_ext_dirty(handle, inode, path + k);
1733 if (err)
1734 return err;
1735
1736 while (k--) {
1737 /* change all left-side indexes */
1738 if (path[k+1].p_idx != EXT_FIRST_INDEX(path[k+1].p_hdr))
1739 break;
1740 err = ext4_ext_get_access(handle, inode, path + k);
1741 if (err)
1742 break;
1743 path[k].p_idx->ei_block = border;
1744 err = ext4_ext_dirty(handle, inode, path + k);
1745 if (err)
1746 break;
1747 }
1748
1749 return err;
1750}
1751
Olivier Deprez157378f2022-04-04 15:47:50 +02001752static int ext4_can_extents_be_merged(struct inode *inode,
1753 struct ext4_extent *ex1,
1754 struct ext4_extent *ex2)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001755{
1756 unsigned short ext1_ee_len, ext2_ee_len;
1757
1758 if (ext4_ext_is_unwritten(ex1) != ext4_ext_is_unwritten(ex2))
1759 return 0;
1760
1761 ext1_ee_len = ext4_ext_get_actual_len(ex1);
1762 ext2_ee_len = ext4_ext_get_actual_len(ex2);
1763
1764 if (le32_to_cpu(ex1->ee_block) + ext1_ee_len !=
1765 le32_to_cpu(ex2->ee_block))
1766 return 0;
1767
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001768 if (ext1_ee_len + ext2_ee_len > EXT_INIT_MAX_LEN)
1769 return 0;
Olivier Deprez157378f2022-04-04 15:47:50 +02001770
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001771 if (ext4_ext_is_unwritten(ex1) &&
Olivier Deprez157378f2022-04-04 15:47:50 +02001772 ext1_ee_len + ext2_ee_len > EXT_UNWRITTEN_MAX_LEN)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001773 return 0;
1774#ifdef AGGRESSIVE_TEST
1775 if (ext1_ee_len >= 4)
1776 return 0;
1777#endif
1778
1779 if (ext4_ext_pblock(ex1) + ext1_ee_len == ext4_ext_pblock(ex2))
1780 return 1;
1781 return 0;
1782}
1783
1784/*
1785 * This function tries to merge the "ex" extent to the next extent in the tree.
1786 * It always tries to merge towards right. If you want to merge towards
1787 * left, pass "ex - 1" as argument instead of "ex".
1788 * Returns 0 if the extents (ex and ex+1) were _not_ merged and returns
1789 * 1 if they got merged.
1790 */
1791static int ext4_ext_try_to_merge_right(struct inode *inode,
1792 struct ext4_ext_path *path,
1793 struct ext4_extent *ex)
1794{
1795 struct ext4_extent_header *eh;
1796 unsigned int depth, len;
1797 int merge_done = 0, unwritten;
1798
1799 depth = ext_depth(inode);
1800 BUG_ON(path[depth].p_hdr == NULL);
1801 eh = path[depth].p_hdr;
1802
1803 while (ex < EXT_LAST_EXTENT(eh)) {
1804 if (!ext4_can_extents_be_merged(inode, ex, ex + 1))
1805 break;
1806 /* merge with next extent! */
1807 unwritten = ext4_ext_is_unwritten(ex);
1808 ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
1809 + ext4_ext_get_actual_len(ex + 1));
1810 if (unwritten)
1811 ext4_ext_mark_unwritten(ex);
1812
1813 if (ex + 1 < EXT_LAST_EXTENT(eh)) {
1814 len = (EXT_LAST_EXTENT(eh) - ex - 1)
1815 * sizeof(struct ext4_extent);
1816 memmove(ex + 1, ex + 2, len);
1817 }
1818 le16_add_cpu(&eh->eh_entries, -1);
1819 merge_done = 1;
1820 WARN_ON(eh->eh_entries == 0);
1821 if (!eh->eh_entries)
1822 EXT4_ERROR_INODE(inode, "eh->eh_entries = 0!");
1823 }
1824
1825 return merge_done;
1826}
1827
1828/*
1829 * This function does a very simple check to see if we can collapse
1830 * an extent tree with a single extent tree leaf block into the inode.
1831 */
1832static void ext4_ext_try_to_merge_up(handle_t *handle,
1833 struct inode *inode,
1834 struct ext4_ext_path *path)
1835{
1836 size_t s;
1837 unsigned max_root = ext4_ext_space_root(inode, 0);
1838 ext4_fsblk_t blk;
1839
1840 if ((path[0].p_depth != 1) ||
1841 (le16_to_cpu(path[0].p_hdr->eh_entries) != 1) ||
1842 (le16_to_cpu(path[1].p_hdr->eh_entries) > max_root))
1843 return;
1844
1845 /*
1846 * We need to modify the block allocation bitmap and the block
1847 * group descriptor to release the extent tree block. If we
1848 * can't get the journal credits, give up.
1849 */
Olivier Deprez157378f2022-04-04 15:47:50 +02001850 if (ext4_journal_extend(handle, 2,
1851 ext4_free_metadata_revoke_credits(inode->i_sb, 1)))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001852 return;
1853
1854 /*
1855 * Copy the extent data up to the inode
1856 */
1857 blk = ext4_idx_pblock(path[0].p_idx);
1858 s = le16_to_cpu(path[1].p_hdr->eh_entries) *
1859 sizeof(struct ext4_extent_idx);
1860 s += sizeof(struct ext4_extent_header);
1861
1862 path[1].p_maxdepth = path[0].p_maxdepth;
1863 memcpy(path[0].p_hdr, path[1].p_hdr, s);
1864 path[0].p_depth = 0;
1865 path[0].p_ext = EXT_FIRST_EXTENT(path[0].p_hdr) +
1866 (path[1].p_ext - EXT_FIRST_EXTENT(path[1].p_hdr));
1867 path[0].p_hdr->eh_max = cpu_to_le16(max_root);
1868
1869 brelse(path[1].p_bh);
1870 ext4_free_blocks(handle, inode, NULL, blk, 1,
1871 EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET);
1872}
1873
1874/*
Olivier Deprez157378f2022-04-04 15:47:50 +02001875 * This function tries to merge the @ex extent to neighbours in the tree, then
1876 * tries to collapse the extent tree into the inode.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001877 */
1878static void ext4_ext_try_to_merge(handle_t *handle,
1879 struct inode *inode,
1880 struct ext4_ext_path *path,
Olivier Deprez157378f2022-04-04 15:47:50 +02001881 struct ext4_extent *ex)
1882{
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001883 struct ext4_extent_header *eh;
1884 unsigned int depth;
1885 int merge_done = 0;
1886
1887 depth = ext_depth(inode);
1888 BUG_ON(path[depth].p_hdr == NULL);
1889 eh = path[depth].p_hdr;
1890
1891 if (ex > EXT_FIRST_EXTENT(eh))
1892 merge_done = ext4_ext_try_to_merge_right(inode, path, ex - 1);
1893
1894 if (!merge_done)
1895 (void) ext4_ext_try_to_merge_right(inode, path, ex);
1896
1897 ext4_ext_try_to_merge_up(handle, inode, path);
1898}
1899
1900/*
1901 * check if a portion of the "newext" extent overlaps with an
1902 * existing extent.
1903 *
1904 * If there is an overlap discovered, it updates the length of the newext
1905 * such that there will be no overlap, and then returns 1.
1906 * If there is no overlap found, it returns 0.
1907 */
1908static unsigned int ext4_ext_check_overlap(struct ext4_sb_info *sbi,
1909 struct inode *inode,
1910 struct ext4_extent *newext,
1911 struct ext4_ext_path *path)
1912{
1913 ext4_lblk_t b1, b2;
1914 unsigned int depth, len1;
1915 unsigned int ret = 0;
1916
1917 b1 = le32_to_cpu(newext->ee_block);
1918 len1 = ext4_ext_get_actual_len(newext);
1919 depth = ext_depth(inode);
1920 if (!path[depth].p_ext)
1921 goto out;
1922 b2 = EXT4_LBLK_CMASK(sbi, le32_to_cpu(path[depth].p_ext->ee_block));
1923
1924 /*
1925 * get the next allocated block if the extent in the path
1926 * is before the requested block(s)
1927 */
1928 if (b2 < b1) {
1929 b2 = ext4_ext_next_allocated_block(path);
1930 if (b2 == EXT_MAX_BLOCKS)
1931 goto out;
1932 b2 = EXT4_LBLK_CMASK(sbi, b2);
1933 }
1934
1935 /* check for wrap through zero on extent logical start block*/
1936 if (b1 + len1 < b1) {
1937 len1 = EXT_MAX_BLOCKS - b1;
1938 newext->ee_len = cpu_to_le16(len1);
1939 ret = 1;
1940 }
1941
1942 /* check for overlap */
1943 if (b1 + len1 > b2) {
1944 newext->ee_len = cpu_to_le16(b2 - b1);
1945 ret = 1;
1946 }
1947out:
1948 return ret;
1949}
1950
1951/*
1952 * ext4_ext_insert_extent:
Olivier Deprez157378f2022-04-04 15:47:50 +02001953 * tries to merge requested extent into the existing extent or
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001954 * inserts requested extent as new one into the tree,
1955 * creating new leaf in the no-space case.
1956 */
1957int ext4_ext_insert_extent(handle_t *handle, struct inode *inode,
1958 struct ext4_ext_path **ppath,
1959 struct ext4_extent *newext, int gb_flags)
1960{
1961 struct ext4_ext_path *path = *ppath;
1962 struct ext4_extent_header *eh;
1963 struct ext4_extent *ex, *fex;
1964 struct ext4_extent *nearex; /* nearest extent */
1965 struct ext4_ext_path *npath = NULL;
1966 int depth, len, err;
1967 ext4_lblk_t next;
1968 int mb_flags = 0, unwritten;
1969
1970 if (gb_flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
1971 mb_flags |= EXT4_MB_DELALLOC_RESERVED;
1972 if (unlikely(ext4_ext_get_actual_len(newext) == 0)) {
1973 EXT4_ERROR_INODE(inode, "ext4_ext_get_actual_len(newext) == 0");
1974 return -EFSCORRUPTED;
1975 }
1976 depth = ext_depth(inode);
1977 ex = path[depth].p_ext;
1978 eh = path[depth].p_hdr;
1979 if (unlikely(path[depth].p_hdr == NULL)) {
1980 EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
1981 return -EFSCORRUPTED;
1982 }
1983
1984 /* try to insert block into found extent and return */
1985 if (ex && !(gb_flags & EXT4_GET_BLOCKS_PRE_IO)) {
1986
1987 /*
1988 * Try to see whether we should rather test the extent on
1989 * right from ex, or from the left of ex. This is because
1990 * ext4_find_extent() can return either extent on the
1991 * left, or on the right from the searched position. This
1992 * will make merging more effective.
1993 */
1994 if (ex < EXT_LAST_EXTENT(eh) &&
1995 (le32_to_cpu(ex->ee_block) +
1996 ext4_ext_get_actual_len(ex) <
1997 le32_to_cpu(newext->ee_block))) {
1998 ex += 1;
1999 goto prepend;
2000 } else if ((ex > EXT_FIRST_EXTENT(eh)) &&
2001 (le32_to_cpu(newext->ee_block) +
2002 ext4_ext_get_actual_len(newext) <
2003 le32_to_cpu(ex->ee_block)))
2004 ex -= 1;
2005
2006 /* Try to append newex to the ex */
2007 if (ext4_can_extents_be_merged(inode, ex, newext)) {
Olivier Deprez157378f2022-04-04 15:47:50 +02002008 ext_debug(inode, "append [%d]%d block to %u:[%d]%d"
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002009 "(from %llu)\n",
2010 ext4_ext_is_unwritten(newext),
2011 ext4_ext_get_actual_len(newext),
2012 le32_to_cpu(ex->ee_block),
2013 ext4_ext_is_unwritten(ex),
2014 ext4_ext_get_actual_len(ex),
2015 ext4_ext_pblock(ex));
2016 err = ext4_ext_get_access(handle, inode,
2017 path + depth);
2018 if (err)
2019 return err;
2020 unwritten = ext4_ext_is_unwritten(ex);
2021 ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
2022 + ext4_ext_get_actual_len(newext));
2023 if (unwritten)
2024 ext4_ext_mark_unwritten(ex);
2025 eh = path[depth].p_hdr;
2026 nearex = ex;
2027 goto merge;
2028 }
2029
2030prepend:
2031 /* Try to prepend newex to the ex */
2032 if (ext4_can_extents_be_merged(inode, newext, ex)) {
Olivier Deprez157378f2022-04-04 15:47:50 +02002033 ext_debug(inode, "prepend %u[%d]%d block to %u:[%d]%d"
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002034 "(from %llu)\n",
2035 le32_to_cpu(newext->ee_block),
2036 ext4_ext_is_unwritten(newext),
2037 ext4_ext_get_actual_len(newext),
2038 le32_to_cpu(ex->ee_block),
2039 ext4_ext_is_unwritten(ex),
2040 ext4_ext_get_actual_len(ex),
2041 ext4_ext_pblock(ex));
2042 err = ext4_ext_get_access(handle, inode,
2043 path + depth);
2044 if (err)
2045 return err;
2046
2047 unwritten = ext4_ext_is_unwritten(ex);
2048 ex->ee_block = newext->ee_block;
2049 ext4_ext_store_pblock(ex, ext4_ext_pblock(newext));
2050 ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
2051 + ext4_ext_get_actual_len(newext));
2052 if (unwritten)
2053 ext4_ext_mark_unwritten(ex);
2054 eh = path[depth].p_hdr;
2055 nearex = ex;
2056 goto merge;
2057 }
2058 }
2059
2060 depth = ext_depth(inode);
2061 eh = path[depth].p_hdr;
2062 if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max))
2063 goto has_space;
2064
2065 /* probably next leaf has space for us? */
2066 fex = EXT_LAST_EXTENT(eh);
2067 next = EXT_MAX_BLOCKS;
2068 if (le32_to_cpu(newext->ee_block) > le32_to_cpu(fex->ee_block))
2069 next = ext4_ext_next_leaf_block(path);
2070 if (next != EXT_MAX_BLOCKS) {
Olivier Deprez157378f2022-04-04 15:47:50 +02002071 ext_debug(inode, "next leaf block - %u\n", next);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002072 BUG_ON(npath != NULL);
Olivier Deprez157378f2022-04-04 15:47:50 +02002073 npath = ext4_find_extent(inode, next, NULL, gb_flags);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002074 if (IS_ERR(npath))
2075 return PTR_ERR(npath);
2076 BUG_ON(npath->p_depth != path->p_depth);
2077 eh = npath[depth].p_hdr;
2078 if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max)) {
Olivier Deprez157378f2022-04-04 15:47:50 +02002079 ext_debug(inode, "next leaf isn't full(%d)\n",
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002080 le16_to_cpu(eh->eh_entries));
2081 path = npath;
2082 goto has_space;
2083 }
Olivier Deprez157378f2022-04-04 15:47:50 +02002084 ext_debug(inode, "next leaf has no free space(%d,%d)\n",
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002085 le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
2086 }
2087
2088 /*
2089 * There is no free space in the found leaf.
2090 * We're gonna add a new leaf in the tree.
2091 */
2092 if (gb_flags & EXT4_GET_BLOCKS_METADATA_NOFAIL)
2093 mb_flags |= EXT4_MB_USE_RESERVED;
2094 err = ext4_ext_create_new_leaf(handle, inode, mb_flags, gb_flags,
2095 ppath, newext);
2096 if (err)
2097 goto cleanup;
2098 depth = ext_depth(inode);
2099 eh = path[depth].p_hdr;
2100
2101has_space:
2102 nearex = path[depth].p_ext;
2103
2104 err = ext4_ext_get_access(handle, inode, path + depth);
2105 if (err)
2106 goto cleanup;
2107
2108 if (!nearex) {
2109 /* there is no extent in this leaf, create first one */
Olivier Deprez157378f2022-04-04 15:47:50 +02002110 ext_debug(inode, "first extent in the leaf: %u:%llu:[%d]%d\n",
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002111 le32_to_cpu(newext->ee_block),
2112 ext4_ext_pblock(newext),
2113 ext4_ext_is_unwritten(newext),
2114 ext4_ext_get_actual_len(newext));
2115 nearex = EXT_FIRST_EXTENT(eh);
2116 } else {
2117 if (le32_to_cpu(newext->ee_block)
2118 > le32_to_cpu(nearex->ee_block)) {
2119 /* Insert after */
Olivier Deprez157378f2022-04-04 15:47:50 +02002120 ext_debug(inode, "insert %u:%llu:[%d]%d before: "
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002121 "nearest %p\n",
2122 le32_to_cpu(newext->ee_block),
2123 ext4_ext_pblock(newext),
2124 ext4_ext_is_unwritten(newext),
2125 ext4_ext_get_actual_len(newext),
2126 nearex);
2127 nearex++;
2128 } else {
2129 /* Insert before */
2130 BUG_ON(newext->ee_block == nearex->ee_block);
Olivier Deprez157378f2022-04-04 15:47:50 +02002131 ext_debug(inode, "insert %u:%llu:[%d]%d after: "
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002132 "nearest %p\n",
2133 le32_to_cpu(newext->ee_block),
2134 ext4_ext_pblock(newext),
2135 ext4_ext_is_unwritten(newext),
2136 ext4_ext_get_actual_len(newext),
2137 nearex);
2138 }
2139 len = EXT_LAST_EXTENT(eh) - nearex + 1;
2140 if (len > 0) {
Olivier Deprez157378f2022-04-04 15:47:50 +02002141 ext_debug(inode, "insert %u:%llu:[%d]%d: "
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002142 "move %d extents from 0x%p to 0x%p\n",
2143 le32_to_cpu(newext->ee_block),
2144 ext4_ext_pblock(newext),
2145 ext4_ext_is_unwritten(newext),
2146 ext4_ext_get_actual_len(newext),
2147 len, nearex, nearex + 1);
2148 memmove(nearex + 1, nearex,
2149 len * sizeof(struct ext4_extent));
2150 }
2151 }
2152
2153 le16_add_cpu(&eh->eh_entries, 1);
2154 path[depth].p_ext = nearex;
2155 nearex->ee_block = newext->ee_block;
2156 ext4_ext_store_pblock(nearex, ext4_ext_pblock(newext));
2157 nearex->ee_len = newext->ee_len;
2158
2159merge:
2160 /* try to merge extents */
2161 if (!(gb_flags & EXT4_GET_BLOCKS_PRE_IO))
2162 ext4_ext_try_to_merge(handle, inode, path, nearex);
2163
2164
2165 /* time to correct all indexes above */
2166 err = ext4_ext_correct_indexes(handle, inode, path);
2167 if (err)
2168 goto cleanup;
2169
2170 err = ext4_ext_dirty(handle, inode, path + path->p_depth);
2171
2172cleanup:
2173 ext4_ext_drop_refs(npath);
2174 kfree(npath);
2175 return err;
2176}
2177
David Brazdil0f672f62019-12-10 10:32:29 +00002178static int ext4_fill_es_cache_info(struct inode *inode,
2179 ext4_lblk_t block, ext4_lblk_t num,
2180 struct fiemap_extent_info *fieinfo)
2181{
2182 ext4_lblk_t next, end = block + num - 1;
2183 struct extent_status es;
2184 unsigned char blksize_bits = inode->i_sb->s_blocksize_bits;
2185 unsigned int flags;
2186 int err;
2187
2188 while (block <= end) {
2189 next = 0;
2190 flags = 0;
2191 if (!ext4_es_lookup_extent(inode, block, &next, &es))
2192 break;
2193 if (ext4_es_is_unwritten(&es))
2194 flags |= FIEMAP_EXTENT_UNWRITTEN;
2195 if (ext4_es_is_delayed(&es))
2196 flags |= (FIEMAP_EXTENT_DELALLOC |
2197 FIEMAP_EXTENT_UNKNOWN);
2198 if (ext4_es_is_hole(&es))
2199 flags |= EXT4_FIEMAP_EXTENT_HOLE;
2200 if (next == 0)
2201 flags |= FIEMAP_EXTENT_LAST;
2202 if (flags & (FIEMAP_EXTENT_DELALLOC|
2203 EXT4_FIEMAP_EXTENT_HOLE))
2204 es.es_pblk = 0;
2205 else
2206 es.es_pblk = ext4_es_pblock(&es);
2207 err = fiemap_fill_next_extent(fieinfo,
2208 (__u64)es.es_lblk << blksize_bits,
2209 (__u64)es.es_pblk << blksize_bits,
2210 (__u64)es.es_len << blksize_bits,
2211 flags);
2212 if (next == 0)
2213 break;
2214 block = next;
2215 if (err < 0)
2216 return err;
2217 if (err == 1)
2218 return 0;
2219 }
2220 return 0;
2221}
2222
2223
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002224/*
2225 * ext4_ext_determine_hole - determine hole around given block
2226 * @inode: inode we lookup in
2227 * @path: path in extent tree to @lblk
2228 * @lblk: pointer to logical block around which we want to determine hole
2229 *
2230 * Determine hole length (and start if easily possible) around given logical
2231 * block. We don't try too hard to find the beginning of the hole but @path
2232 * actually points to extent before @lblk, we provide it.
2233 *
2234 * The function returns the length of a hole starting at @lblk. We update @lblk
2235 * to the beginning of the hole if we managed to find it.
2236 */
2237static ext4_lblk_t ext4_ext_determine_hole(struct inode *inode,
2238 struct ext4_ext_path *path,
2239 ext4_lblk_t *lblk)
2240{
2241 int depth = ext_depth(inode);
2242 struct ext4_extent *ex;
2243 ext4_lblk_t len;
2244
2245 ex = path[depth].p_ext;
2246 if (ex == NULL) {
2247 /* there is no extent yet, so gap is [0;-] */
2248 *lblk = 0;
2249 len = EXT_MAX_BLOCKS;
2250 } else if (*lblk < le32_to_cpu(ex->ee_block)) {
2251 len = le32_to_cpu(ex->ee_block) - *lblk;
2252 } else if (*lblk >= le32_to_cpu(ex->ee_block)
2253 + ext4_ext_get_actual_len(ex)) {
2254 ext4_lblk_t next;
2255
2256 *lblk = le32_to_cpu(ex->ee_block) + ext4_ext_get_actual_len(ex);
2257 next = ext4_ext_next_allocated_block(path);
2258 BUG_ON(next == *lblk);
2259 len = next - *lblk;
2260 } else {
2261 BUG();
2262 }
2263 return len;
2264}
2265
2266/*
2267 * ext4_ext_put_gap_in_cache:
2268 * calculate boundaries of the gap that the requested block fits into
2269 * and cache this gap
2270 */
2271static void
2272ext4_ext_put_gap_in_cache(struct inode *inode, ext4_lblk_t hole_start,
2273 ext4_lblk_t hole_len)
2274{
2275 struct extent_status es;
2276
David Brazdil0f672f62019-12-10 10:32:29 +00002277 ext4_es_find_extent_range(inode, &ext4_es_is_delayed, hole_start,
2278 hole_start + hole_len - 1, &es);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002279 if (es.es_len) {
2280 /* There's delayed extent containing lblock? */
2281 if (es.es_lblk <= hole_start)
2282 return;
2283 hole_len = min(es.es_lblk - hole_start, hole_len);
2284 }
Olivier Deprez157378f2022-04-04 15:47:50 +02002285 ext_debug(inode, " -> %u:%u\n", hole_start, hole_len);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002286 ext4_es_insert_extent(inode, hole_start, hole_len, ~0,
2287 EXTENT_STATUS_HOLE);
2288}
2289
2290/*
2291 * ext4_ext_rm_idx:
2292 * removes index from the index block.
2293 */
2294static int ext4_ext_rm_idx(handle_t *handle, struct inode *inode,
2295 struct ext4_ext_path *path, int depth)
2296{
2297 int err;
2298 ext4_fsblk_t leaf;
2299
2300 /* free index block */
2301 depth--;
2302 path = path + depth;
2303 leaf = ext4_idx_pblock(path->p_idx);
2304 if (unlikely(path->p_hdr->eh_entries == 0)) {
2305 EXT4_ERROR_INODE(inode, "path->p_hdr->eh_entries == 0");
2306 return -EFSCORRUPTED;
2307 }
2308 err = ext4_ext_get_access(handle, inode, path);
2309 if (err)
2310 return err;
2311
2312 if (path->p_idx != EXT_LAST_INDEX(path->p_hdr)) {
2313 int len = EXT_LAST_INDEX(path->p_hdr) - path->p_idx;
2314 len *= sizeof(struct ext4_extent_idx);
2315 memmove(path->p_idx, path->p_idx + 1, len);
2316 }
2317
2318 le16_add_cpu(&path->p_hdr->eh_entries, -1);
2319 err = ext4_ext_dirty(handle, inode, path);
2320 if (err)
2321 return err;
Olivier Deprez157378f2022-04-04 15:47:50 +02002322 ext_debug(inode, "index is empty, remove it, free block %llu\n", leaf);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002323 trace_ext4_ext_rm_idx(inode, leaf);
2324
2325 ext4_free_blocks(handle, inode, NULL, leaf, 1,
2326 EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET);
2327
2328 while (--depth >= 0) {
2329 if (path->p_idx != EXT_FIRST_INDEX(path->p_hdr))
2330 break;
2331 path--;
2332 err = ext4_ext_get_access(handle, inode, path);
2333 if (err)
2334 break;
2335 path->p_idx->ei_block = (path+1)->p_idx->ei_block;
2336 err = ext4_ext_dirty(handle, inode, path);
2337 if (err)
2338 break;
2339 }
2340 return err;
2341}
2342
2343/*
2344 * ext4_ext_calc_credits_for_single_extent:
2345 * This routine returns max. credits that needed to insert an extent
2346 * to the extent tree.
2347 * When pass the actual path, the caller should calculate credits
2348 * under i_data_sem.
2349 */
2350int ext4_ext_calc_credits_for_single_extent(struct inode *inode, int nrblocks,
2351 struct ext4_ext_path *path)
2352{
2353 if (path) {
2354 int depth = ext_depth(inode);
2355 int ret = 0;
2356
2357 /* probably there is space in leaf? */
2358 if (le16_to_cpu(path[depth].p_hdr->eh_entries)
2359 < le16_to_cpu(path[depth].p_hdr->eh_max)) {
2360
2361 /*
2362 * There are some space in the leaf tree, no
2363 * need to account for leaf block credit
2364 *
2365 * bitmaps and block group descriptor blocks
2366 * and other metadata blocks still need to be
2367 * accounted.
2368 */
2369 /* 1 bitmap, 1 block group descriptor */
2370 ret = 2 + EXT4_META_TRANS_BLOCKS(inode->i_sb);
2371 return ret;
2372 }
2373 }
2374
2375 return ext4_chunk_trans_blocks(inode, nrblocks);
2376}
2377
2378/*
2379 * How many index/leaf blocks need to change/allocate to add @extents extents?
2380 *
2381 * If we add a single extent, then in the worse case, each tree level
2382 * index/leaf need to be changed in case of the tree split.
2383 *
2384 * If more extents are inserted, they could cause the whole tree split more
2385 * than once, but this is really rare.
2386 */
2387int ext4_ext_index_trans_blocks(struct inode *inode, int extents)
2388{
2389 int index;
2390 int depth;
2391
2392 /* If we are converting the inline data, only one is needed here. */
2393 if (ext4_has_inline_data(inode))
2394 return 1;
2395
2396 depth = ext_depth(inode);
2397
2398 if (extents <= 1)
2399 index = depth * 2;
2400 else
2401 index = depth * 3;
2402
2403 return index;
2404}
2405
2406static inline int get_default_free_blocks_flags(struct inode *inode)
2407{
2408 if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode) ||
2409 ext4_test_inode_flag(inode, EXT4_INODE_EA_INODE))
2410 return EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET;
2411 else if (ext4_should_journal_data(inode))
2412 return EXT4_FREE_BLOCKS_FORGET;
2413 return 0;
2414}
2415
David Brazdil0f672f62019-12-10 10:32:29 +00002416/*
2417 * ext4_rereserve_cluster - increment the reserved cluster count when
2418 * freeing a cluster with a pending reservation
2419 *
2420 * @inode - file containing the cluster
2421 * @lblk - logical block in cluster to be reserved
2422 *
2423 * Increments the reserved cluster count and adjusts quota in a bigalloc
2424 * file system when freeing a partial cluster containing at least one
2425 * delayed and unwritten block. A partial cluster meeting that
2426 * requirement will have a pending reservation. If so, the
2427 * RERESERVE_CLUSTER flag is used when calling ext4_free_blocks() to
2428 * defer reserved and allocated space accounting to a subsequent call
2429 * to this function.
2430 */
2431static void ext4_rereserve_cluster(struct inode *inode, ext4_lblk_t lblk)
2432{
2433 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2434 struct ext4_inode_info *ei = EXT4_I(inode);
2435
2436 dquot_reclaim_block(inode, EXT4_C2B(sbi, 1));
2437
2438 spin_lock(&ei->i_block_reservation_lock);
2439 ei->i_reserved_data_blocks++;
2440 percpu_counter_add(&sbi->s_dirtyclusters_counter, 1);
2441 spin_unlock(&ei->i_block_reservation_lock);
2442
2443 percpu_counter_add(&sbi->s_freeclusters_counter, 1);
2444 ext4_remove_pending(inode, lblk);
2445}
2446
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002447static int ext4_remove_blocks(handle_t *handle, struct inode *inode,
2448 struct ext4_extent *ex,
David Brazdil0f672f62019-12-10 10:32:29 +00002449 struct partial_cluster *partial,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002450 ext4_lblk_t from, ext4_lblk_t to)
2451{
2452 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2453 unsigned short ee_len = ext4_ext_get_actual_len(ex);
David Brazdil0f672f62019-12-10 10:32:29 +00002454 ext4_fsblk_t last_pblk, pblk;
2455 ext4_lblk_t num;
2456 int flags;
2457
2458 /* only extent tail removal is allowed */
2459 if (from < le32_to_cpu(ex->ee_block) ||
2460 to != le32_to_cpu(ex->ee_block) + ee_len - 1) {
2461 ext4_error(sbi->s_sb,
2462 "strange request: removal(2) %u-%u from %u:%u",
2463 from, to, le32_to_cpu(ex->ee_block), ee_len);
2464 return 0;
2465 }
2466
2467#ifdef EXTENTS_STATS
2468 spin_lock(&sbi->s_ext_stats_lock);
2469 sbi->s_ext_blocks += ee_len;
2470 sbi->s_ext_extents++;
2471 if (ee_len < sbi->s_ext_min)
2472 sbi->s_ext_min = ee_len;
2473 if (ee_len > sbi->s_ext_max)
2474 sbi->s_ext_max = ee_len;
2475 if (ext_depth(inode) > sbi->s_depth_max)
2476 sbi->s_depth_max = ext_depth(inode);
2477 spin_unlock(&sbi->s_ext_stats_lock);
2478#endif
2479
2480 trace_ext4_remove_blocks(inode, ex, from, to, partial);
2481
2482 /*
2483 * if we have a partial cluster, and it's different from the
2484 * cluster of the last block in the extent, we free it
2485 */
2486 last_pblk = ext4_ext_pblock(ex) + ee_len - 1;
2487
2488 if (partial->state != initial &&
2489 partial->pclu != EXT4_B2C(sbi, last_pblk)) {
2490 if (partial->state == tofree) {
2491 flags = get_default_free_blocks_flags(inode);
2492 if (ext4_is_pending(inode, partial->lblk))
2493 flags |= EXT4_FREE_BLOCKS_RERESERVE_CLUSTER;
2494 ext4_free_blocks(handle, inode, NULL,
2495 EXT4_C2B(sbi, partial->pclu),
2496 sbi->s_cluster_ratio, flags);
2497 if (flags & EXT4_FREE_BLOCKS_RERESERVE_CLUSTER)
2498 ext4_rereserve_cluster(inode, partial->lblk);
2499 }
2500 partial->state = initial;
2501 }
2502
2503 num = le32_to_cpu(ex->ee_block) + ee_len - from;
2504 pblk = ext4_ext_pblock(ex) + ee_len - num;
2505
2506 /*
2507 * We free the partial cluster at the end of the extent (if any),
2508 * unless the cluster is used by another extent (partial_cluster
2509 * state is nofree). If a partial cluster exists here, it must be
2510 * shared with the last block in the extent.
2511 */
2512 flags = get_default_free_blocks_flags(inode);
2513
2514 /* partial, left end cluster aligned, right end unaligned */
2515 if ((EXT4_LBLK_COFF(sbi, to) != sbi->s_cluster_ratio - 1) &&
2516 (EXT4_LBLK_CMASK(sbi, to) >= from) &&
2517 (partial->state != nofree)) {
2518 if (ext4_is_pending(inode, to))
2519 flags |= EXT4_FREE_BLOCKS_RERESERVE_CLUSTER;
2520 ext4_free_blocks(handle, inode, NULL,
2521 EXT4_PBLK_CMASK(sbi, last_pblk),
2522 sbi->s_cluster_ratio, flags);
2523 if (flags & EXT4_FREE_BLOCKS_RERESERVE_CLUSTER)
2524 ext4_rereserve_cluster(inode, to);
2525 partial->state = initial;
2526 flags = get_default_free_blocks_flags(inode);
2527 }
2528
2529 flags |= EXT4_FREE_BLOCKS_NOFREE_LAST_CLUSTER;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002530
2531 /*
2532 * For bigalloc file systems, we never free a partial cluster
David Brazdil0f672f62019-12-10 10:32:29 +00002533 * at the beginning of the extent. Instead, we check to see if we
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002534 * need to free it on a subsequent call to ext4_remove_blocks,
2535 * or at the end of ext4_ext_rm_leaf or ext4_ext_remove_space.
2536 */
2537 flags |= EXT4_FREE_BLOCKS_NOFREE_FIRST_CLUSTER;
David Brazdil0f672f62019-12-10 10:32:29 +00002538 ext4_free_blocks(handle, inode, NULL, pblk, num, flags);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002539
David Brazdil0f672f62019-12-10 10:32:29 +00002540 /* reset the partial cluster if we've freed past it */
2541 if (partial->state != initial && partial->pclu != EXT4_B2C(sbi, pblk))
2542 partial->state = initial;
2543
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002544 /*
David Brazdil0f672f62019-12-10 10:32:29 +00002545 * If we've freed the entire extent but the beginning is not left
2546 * cluster aligned and is not marked as ineligible for freeing we
2547 * record the partial cluster at the beginning of the extent. It
2548 * wasn't freed by the preceding ext4_free_blocks() call, and we
2549 * need to look farther to the left to determine if it's to be freed
2550 * (not shared with another extent). Else, reset the partial
2551 * cluster - we're either done freeing or the beginning of the
2552 * extent is left cluster aligned.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002553 */
David Brazdil0f672f62019-12-10 10:32:29 +00002554 if (EXT4_LBLK_COFF(sbi, from) && num == ee_len) {
2555 if (partial->state == initial) {
2556 partial->pclu = EXT4_B2C(sbi, pblk);
2557 partial->lblk = from;
2558 partial->state = tofree;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002559 }
David Brazdil0f672f62019-12-10 10:32:29 +00002560 } else {
2561 partial->state = initial;
2562 }
2563
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002564 return 0;
2565}
2566
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002567/*
2568 * ext4_ext_rm_leaf() Removes the extents associated with the
2569 * blocks appearing between "start" and "end". Both "start"
2570 * and "end" must appear in the same extent or EIO is returned.
2571 *
2572 * @handle: The journal handle
2573 * @inode: The files inode
2574 * @path: The path to the leaf
2575 * @partial_cluster: The cluster which we'll have to free if all extents
2576 * has been released from it. However, if this value is
2577 * negative, it's a cluster just to the right of the
2578 * punched region and it must not be freed.
2579 * @start: The first block to remove
2580 * @end: The last block to remove
2581 */
2582static int
2583ext4_ext_rm_leaf(handle_t *handle, struct inode *inode,
2584 struct ext4_ext_path *path,
David Brazdil0f672f62019-12-10 10:32:29 +00002585 struct partial_cluster *partial,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002586 ext4_lblk_t start, ext4_lblk_t end)
2587{
2588 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2589 int err = 0, correct_index = 0;
Olivier Deprez157378f2022-04-04 15:47:50 +02002590 int depth = ext_depth(inode), credits, revoke_credits;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002591 struct ext4_extent_header *eh;
2592 ext4_lblk_t a, b;
2593 unsigned num;
2594 ext4_lblk_t ex_ee_block;
2595 unsigned short ex_ee_len;
2596 unsigned unwritten = 0;
2597 struct ext4_extent *ex;
2598 ext4_fsblk_t pblk;
2599
2600 /* the header must be checked already in ext4_ext_remove_space() */
Olivier Deprez157378f2022-04-04 15:47:50 +02002601 ext_debug(inode, "truncate since %u in leaf to %u\n", start, end);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002602 if (!path[depth].p_hdr)
2603 path[depth].p_hdr = ext_block_hdr(path[depth].p_bh);
2604 eh = path[depth].p_hdr;
2605 if (unlikely(path[depth].p_hdr == NULL)) {
2606 EXT4_ERROR_INODE(inode, "path[%d].p_hdr == NULL", depth);
2607 return -EFSCORRUPTED;
2608 }
2609 /* find where to start removing */
2610 ex = path[depth].p_ext;
2611 if (!ex)
2612 ex = EXT_LAST_EXTENT(eh);
2613
2614 ex_ee_block = le32_to_cpu(ex->ee_block);
2615 ex_ee_len = ext4_ext_get_actual_len(ex);
2616
David Brazdil0f672f62019-12-10 10:32:29 +00002617 trace_ext4_ext_rm_leaf(inode, start, ex, partial);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002618
2619 while (ex >= EXT_FIRST_EXTENT(eh) &&
2620 ex_ee_block + ex_ee_len > start) {
2621
2622 if (ext4_ext_is_unwritten(ex))
2623 unwritten = 1;
2624 else
2625 unwritten = 0;
2626
Olivier Deprez157378f2022-04-04 15:47:50 +02002627 ext_debug(inode, "remove ext %u:[%d]%d\n", ex_ee_block,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002628 unwritten, ex_ee_len);
2629 path[depth].p_ext = ex;
2630
2631 a = ex_ee_block > start ? ex_ee_block : start;
2632 b = ex_ee_block+ex_ee_len - 1 < end ?
2633 ex_ee_block+ex_ee_len - 1 : end;
2634
Olivier Deprez157378f2022-04-04 15:47:50 +02002635 ext_debug(inode, " border %u:%u\n", a, b);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002636
2637 /* If this extent is beyond the end of the hole, skip it */
2638 if (end < ex_ee_block) {
2639 /*
2640 * We're going to skip this extent and move to another,
2641 * so note that its first cluster is in use to avoid
2642 * freeing it when removing blocks. Eventually, the
2643 * right edge of the truncated/punched region will
2644 * be just to the left.
2645 */
2646 if (sbi->s_cluster_ratio > 1) {
2647 pblk = ext4_ext_pblock(ex);
David Brazdil0f672f62019-12-10 10:32:29 +00002648 partial->pclu = EXT4_B2C(sbi, pblk);
2649 partial->state = nofree;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002650 }
2651 ex--;
2652 ex_ee_block = le32_to_cpu(ex->ee_block);
2653 ex_ee_len = ext4_ext_get_actual_len(ex);
2654 continue;
2655 } else if (b != ex_ee_block + ex_ee_len - 1) {
2656 EXT4_ERROR_INODE(inode,
2657 "can not handle truncate %u:%u "
2658 "on extent %u:%u",
2659 start, end, ex_ee_block,
2660 ex_ee_block + ex_ee_len - 1);
2661 err = -EFSCORRUPTED;
2662 goto out;
2663 } else if (a != ex_ee_block) {
2664 /* remove tail of the extent */
2665 num = a - ex_ee_block;
2666 } else {
2667 /* remove whole extent: excellent! */
2668 num = 0;
2669 }
2670 /*
2671 * 3 for leaf, sb, and inode plus 2 (bmap and group
2672 * descriptor) for each block group; assume two block
2673 * groups plus ex_ee_len/blocks_per_block_group for
2674 * the worst case
2675 */
2676 credits = 7 + 2*(ex_ee_len/EXT4_BLOCKS_PER_GROUP(inode->i_sb));
2677 if (ex == EXT_FIRST_EXTENT(eh)) {
2678 correct_index = 1;
2679 credits += (ext_depth(inode)) + 1;
2680 }
2681 credits += EXT4_MAXQUOTAS_TRANS_BLOCKS(inode->i_sb);
Olivier Deprez157378f2022-04-04 15:47:50 +02002682 /*
2683 * We may end up freeing some index blocks and data from the
2684 * punched range. Note that partial clusters are accounted for
2685 * by ext4_free_data_revoke_credits().
2686 */
2687 revoke_credits =
2688 ext4_free_metadata_revoke_credits(inode->i_sb,
2689 ext_depth(inode)) +
2690 ext4_free_data_revoke_credits(inode, b - a + 1);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002691
Olivier Deprez157378f2022-04-04 15:47:50 +02002692 err = ext4_datasem_ensure_credits(handle, inode, credits,
2693 credits, revoke_credits);
2694 if (err) {
2695 if (err > 0)
2696 err = -EAGAIN;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002697 goto out;
Olivier Deprez157378f2022-04-04 15:47:50 +02002698 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002699
2700 err = ext4_ext_get_access(handle, inode, path + depth);
2701 if (err)
2702 goto out;
2703
David Brazdil0f672f62019-12-10 10:32:29 +00002704 err = ext4_remove_blocks(handle, inode, ex, partial, a, b);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002705 if (err)
2706 goto out;
2707
2708 if (num == 0)
2709 /* this extent is removed; mark slot entirely unused */
2710 ext4_ext_store_pblock(ex, 0);
2711
2712 ex->ee_len = cpu_to_le16(num);
2713 /*
2714 * Do not mark unwritten if all the blocks in the
2715 * extent have been removed.
2716 */
2717 if (unwritten && num)
2718 ext4_ext_mark_unwritten(ex);
2719 /*
2720 * If the extent was completely released,
2721 * we need to remove it from the leaf
2722 */
2723 if (num == 0) {
2724 if (end != EXT_MAX_BLOCKS - 1) {
2725 /*
2726 * For hole punching, we need to scoot all the
2727 * extents up when an extent is removed so that
2728 * we dont have blank extents in the middle
2729 */
2730 memmove(ex, ex+1, (EXT_LAST_EXTENT(eh) - ex) *
2731 sizeof(struct ext4_extent));
2732
2733 /* Now get rid of the one at the end */
2734 memset(EXT_LAST_EXTENT(eh), 0,
2735 sizeof(struct ext4_extent));
2736 }
2737 le16_add_cpu(&eh->eh_entries, -1);
2738 }
2739
2740 err = ext4_ext_dirty(handle, inode, path + depth);
2741 if (err)
2742 goto out;
2743
Olivier Deprez157378f2022-04-04 15:47:50 +02002744 ext_debug(inode, "new extent: %u:%u:%llu\n", ex_ee_block, num,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002745 ext4_ext_pblock(ex));
2746 ex--;
2747 ex_ee_block = le32_to_cpu(ex->ee_block);
2748 ex_ee_len = ext4_ext_get_actual_len(ex);
2749 }
2750
2751 if (correct_index && eh->eh_entries)
2752 err = ext4_ext_correct_indexes(handle, inode, path);
2753
2754 /*
2755 * If there's a partial cluster and at least one extent remains in
2756 * the leaf, free the partial cluster if it isn't shared with the
2757 * current extent. If it is shared with the current extent
David Brazdil0f672f62019-12-10 10:32:29 +00002758 * we reset the partial cluster because we've reached the start of the
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002759 * truncated/punched region and we're done removing blocks.
2760 */
David Brazdil0f672f62019-12-10 10:32:29 +00002761 if (partial->state == tofree && ex >= EXT_FIRST_EXTENT(eh)) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002762 pblk = ext4_ext_pblock(ex) + ex_ee_len - 1;
David Brazdil0f672f62019-12-10 10:32:29 +00002763 if (partial->pclu != EXT4_B2C(sbi, pblk)) {
2764 int flags = get_default_free_blocks_flags(inode);
2765
2766 if (ext4_is_pending(inode, partial->lblk))
2767 flags |= EXT4_FREE_BLOCKS_RERESERVE_CLUSTER;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002768 ext4_free_blocks(handle, inode, NULL,
David Brazdil0f672f62019-12-10 10:32:29 +00002769 EXT4_C2B(sbi, partial->pclu),
2770 sbi->s_cluster_ratio, flags);
2771 if (flags & EXT4_FREE_BLOCKS_RERESERVE_CLUSTER)
2772 ext4_rereserve_cluster(inode, partial->lblk);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002773 }
David Brazdil0f672f62019-12-10 10:32:29 +00002774 partial->state = initial;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002775 }
2776
2777 /* if this leaf is free, then we should
2778 * remove it from index block above */
2779 if (err == 0 && eh->eh_entries == 0 && path[depth].p_bh != NULL)
2780 err = ext4_ext_rm_idx(handle, inode, path, depth);
2781
2782out:
2783 return err;
2784}
2785
2786/*
2787 * ext4_ext_more_to_rm:
2788 * returns 1 if current index has to be freed (even partial)
2789 */
2790static int
2791ext4_ext_more_to_rm(struct ext4_ext_path *path)
2792{
2793 BUG_ON(path->p_idx == NULL);
2794
2795 if (path->p_idx < EXT_FIRST_INDEX(path->p_hdr))
2796 return 0;
2797
2798 /*
2799 * if truncate on deeper level happened, it wasn't partial,
2800 * so we have to consider current index for truncation
2801 */
2802 if (le16_to_cpu(path->p_hdr->eh_entries) == path->p_block)
2803 return 0;
2804 return 1;
2805}
2806
2807int ext4_ext_remove_space(struct inode *inode, ext4_lblk_t start,
2808 ext4_lblk_t end)
2809{
2810 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2811 int depth = ext_depth(inode);
2812 struct ext4_ext_path *path = NULL;
David Brazdil0f672f62019-12-10 10:32:29 +00002813 struct partial_cluster partial;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002814 handle_t *handle;
2815 int i = 0, err = 0;
2816
David Brazdil0f672f62019-12-10 10:32:29 +00002817 partial.pclu = 0;
2818 partial.lblk = 0;
2819 partial.state = initial;
2820
Olivier Deprez157378f2022-04-04 15:47:50 +02002821 ext_debug(inode, "truncate since %u to %u\n", start, end);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002822
2823 /* probably first extent we're gonna free will be last in block */
Olivier Deprez157378f2022-04-04 15:47:50 +02002824 handle = ext4_journal_start_with_revoke(inode, EXT4_HT_TRUNCATE,
2825 depth + 1,
2826 ext4_free_metadata_revoke_credits(inode->i_sb, depth));
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002827 if (IS_ERR(handle))
2828 return PTR_ERR(handle);
2829
2830again:
2831 trace_ext4_ext_remove_space(inode, start, end, depth);
2832
2833 /*
2834 * Check if we are removing extents inside the extent tree. If that
2835 * is the case, we are going to punch a hole inside the extent tree
2836 * so we have to check whether we need to split the extent covering
2837 * the last block to remove so we can easily remove the part of it
2838 * in ext4_ext_rm_leaf().
2839 */
2840 if (end < EXT_MAX_BLOCKS - 1) {
2841 struct ext4_extent *ex;
2842 ext4_lblk_t ee_block, ex_end, lblk;
2843 ext4_fsblk_t pblk;
2844
2845 /* find extent for or closest extent to this block */
Olivier Deprez157378f2022-04-04 15:47:50 +02002846 path = ext4_find_extent(inode, end, NULL,
2847 EXT4_EX_NOCACHE | EXT4_EX_NOFAIL);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002848 if (IS_ERR(path)) {
2849 ext4_journal_stop(handle);
2850 return PTR_ERR(path);
2851 }
2852 depth = ext_depth(inode);
2853 /* Leaf not may not exist only if inode has no blocks at all */
2854 ex = path[depth].p_ext;
2855 if (!ex) {
2856 if (depth) {
2857 EXT4_ERROR_INODE(inode,
2858 "path[%d].p_hdr == NULL",
2859 depth);
2860 err = -EFSCORRUPTED;
2861 }
2862 goto out;
2863 }
2864
2865 ee_block = le32_to_cpu(ex->ee_block);
2866 ex_end = ee_block + ext4_ext_get_actual_len(ex) - 1;
2867
2868 /*
2869 * See if the last block is inside the extent, if so split
2870 * the extent at 'end' block so we can easily remove the
2871 * tail of the first part of the split extent in
2872 * ext4_ext_rm_leaf().
2873 */
2874 if (end >= ee_block && end < ex_end) {
2875
2876 /*
2877 * If we're going to split the extent, note that
2878 * the cluster containing the block after 'end' is
2879 * in use to avoid freeing it when removing blocks.
2880 */
2881 if (sbi->s_cluster_ratio > 1) {
Olivier Deprez0e641232021-09-23 10:07:05 +02002882 pblk = ext4_ext_pblock(ex) + end - ee_block + 1;
David Brazdil0f672f62019-12-10 10:32:29 +00002883 partial.pclu = EXT4_B2C(sbi, pblk);
2884 partial.state = nofree;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002885 }
2886
2887 /*
2888 * Split the extent in two so that 'end' is the last
2889 * block in the first new extent. Also we should not
2890 * fail removing space due to ENOSPC so try to use
2891 * reserved block if that happens.
2892 */
2893 err = ext4_force_split_extent_at(handle, inode, &path,
2894 end + 1, 1);
2895 if (err < 0)
2896 goto out;
2897
David Brazdil0f672f62019-12-10 10:32:29 +00002898 } else if (sbi->s_cluster_ratio > 1 && end >= ex_end &&
2899 partial.state == initial) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002900 /*
David Brazdil0f672f62019-12-10 10:32:29 +00002901 * If we're punching, there's an extent to the right.
2902 * If the partial cluster hasn't been set, set it to
2903 * that extent's first cluster and its state to nofree
2904 * so it won't be freed should it contain blocks to be
2905 * removed. If it's already set (tofree/nofree), we're
2906 * retrying and keep the original partial cluster info
2907 * so a cluster marked tofree as a result of earlier
2908 * extent removal is not lost.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002909 */
2910 lblk = ex_end + 1;
2911 err = ext4_ext_search_right(inode, path, &lblk, &pblk,
Olivier Deprez157378f2022-04-04 15:47:50 +02002912 NULL);
2913 if (err < 0)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002914 goto out;
David Brazdil0f672f62019-12-10 10:32:29 +00002915 if (pblk) {
2916 partial.pclu = EXT4_B2C(sbi, pblk);
2917 partial.state = nofree;
2918 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002919 }
2920 }
2921 /*
2922 * We start scanning from right side, freeing all the blocks
2923 * after i_size and walking into the tree depth-wise.
2924 */
2925 depth = ext_depth(inode);
2926 if (path) {
2927 int k = i = depth;
2928 while (--k > 0)
2929 path[k].p_block =
2930 le16_to_cpu(path[k].p_hdr->eh_entries)+1;
2931 } else {
2932 path = kcalloc(depth + 1, sizeof(struct ext4_ext_path),
Olivier Deprez157378f2022-04-04 15:47:50 +02002933 GFP_NOFS | __GFP_NOFAIL);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002934 if (path == NULL) {
2935 ext4_journal_stop(handle);
2936 return -ENOMEM;
2937 }
2938 path[0].p_maxdepth = path[0].p_depth = depth;
2939 path[0].p_hdr = ext_inode_hdr(inode);
2940 i = 0;
2941
2942 if (ext4_ext_check(inode, path[0].p_hdr, depth, 0)) {
2943 err = -EFSCORRUPTED;
2944 goto out;
2945 }
2946 }
2947 err = 0;
2948
2949 while (i >= 0 && err == 0) {
2950 if (i == depth) {
2951 /* this is leaf block */
2952 err = ext4_ext_rm_leaf(handle, inode, path,
David Brazdil0f672f62019-12-10 10:32:29 +00002953 &partial, start, end);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002954 /* root level has p_bh == NULL, brelse() eats this */
2955 brelse(path[i].p_bh);
2956 path[i].p_bh = NULL;
2957 i--;
2958 continue;
2959 }
2960
2961 /* this is index block */
2962 if (!path[i].p_hdr) {
Olivier Deprez157378f2022-04-04 15:47:50 +02002963 ext_debug(inode, "initialize header\n");
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002964 path[i].p_hdr = ext_block_hdr(path[i].p_bh);
2965 }
2966
2967 if (!path[i].p_idx) {
2968 /* this level hasn't been touched yet */
2969 path[i].p_idx = EXT_LAST_INDEX(path[i].p_hdr);
2970 path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries)+1;
Olivier Deprez157378f2022-04-04 15:47:50 +02002971 ext_debug(inode, "init index ptr: hdr 0x%p, num %d\n",
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002972 path[i].p_hdr,
2973 le16_to_cpu(path[i].p_hdr->eh_entries));
2974 } else {
2975 /* we were already here, see at next index */
2976 path[i].p_idx--;
2977 }
2978
Olivier Deprez157378f2022-04-04 15:47:50 +02002979 ext_debug(inode, "level %d - index, first 0x%p, cur 0x%p\n",
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002980 i, EXT_FIRST_INDEX(path[i].p_hdr),
2981 path[i].p_idx);
2982 if (ext4_ext_more_to_rm(path + i)) {
2983 struct buffer_head *bh;
2984 /* go to the next level */
Olivier Deprez157378f2022-04-04 15:47:50 +02002985 ext_debug(inode, "move to level %d (block %llu)\n",
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002986 i + 1, ext4_idx_pblock(path[i].p_idx));
2987 memset(path + i + 1, 0, sizeof(*path));
Olivier Deprez157378f2022-04-04 15:47:50 +02002988 bh = read_extent_tree_block(inode, path[i].p_idx,
2989 depth - i - 1,
2990 EXT4_EX_NOCACHE);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002991 if (IS_ERR(bh)) {
2992 /* should we reset i_size? */
2993 err = PTR_ERR(bh);
2994 break;
2995 }
2996 /* Yield here to deal with large extent trees.
2997 * Should be a no-op if we did IO above. */
2998 cond_resched();
2999 if (WARN_ON(i + 1 > depth)) {
3000 err = -EFSCORRUPTED;
3001 break;
3002 }
3003 path[i + 1].p_bh = bh;
3004
3005 /* save actual number of indexes since this
3006 * number is changed at the next iteration */
3007 path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries);
3008 i++;
3009 } else {
3010 /* we finished processing this index, go up */
3011 if (path[i].p_hdr->eh_entries == 0 && i > 0) {
3012 /* index is empty, remove it;
3013 * handle must be already prepared by the
3014 * truncatei_leaf() */
3015 err = ext4_ext_rm_idx(handle, inode, path, i);
3016 }
3017 /* root level has p_bh == NULL, brelse() eats this */
3018 brelse(path[i].p_bh);
3019 path[i].p_bh = NULL;
3020 i--;
Olivier Deprez157378f2022-04-04 15:47:50 +02003021 ext_debug(inode, "return to level %d\n", i);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003022 }
3023 }
3024
David Brazdil0f672f62019-12-10 10:32:29 +00003025 trace_ext4_ext_remove_space_done(inode, start, end, depth, &partial,
3026 path->p_hdr->eh_entries);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003027
3028 /*
David Brazdil0f672f62019-12-10 10:32:29 +00003029 * if there's a partial cluster and we have removed the first extent
3030 * in the file, then we also free the partial cluster, if any
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003031 */
David Brazdil0f672f62019-12-10 10:32:29 +00003032 if (partial.state == tofree && err == 0) {
3033 int flags = get_default_free_blocks_flags(inode);
3034
3035 if (ext4_is_pending(inode, partial.lblk))
3036 flags |= EXT4_FREE_BLOCKS_RERESERVE_CLUSTER;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003037 ext4_free_blocks(handle, inode, NULL,
David Brazdil0f672f62019-12-10 10:32:29 +00003038 EXT4_C2B(sbi, partial.pclu),
3039 sbi->s_cluster_ratio, flags);
3040 if (flags & EXT4_FREE_BLOCKS_RERESERVE_CLUSTER)
3041 ext4_rereserve_cluster(inode, partial.lblk);
3042 partial.state = initial;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003043 }
3044
3045 /* TODO: flexible tree reduction should be here */
3046 if (path->p_hdr->eh_entries == 0) {
3047 /*
3048 * truncate to zero freed all the tree,
3049 * so we need to correct eh_depth
3050 */
3051 err = ext4_ext_get_access(handle, inode, path);
3052 if (err == 0) {
3053 ext_inode_hdr(inode)->eh_depth = 0;
3054 ext_inode_hdr(inode)->eh_max =
3055 cpu_to_le16(ext4_ext_space_root(inode, 0));
3056 err = ext4_ext_dirty(handle, inode, path);
3057 }
3058 }
3059out:
3060 ext4_ext_drop_refs(path);
3061 kfree(path);
3062 path = NULL;
3063 if (err == -EAGAIN)
3064 goto again;
3065 ext4_journal_stop(handle);
3066
3067 return err;
3068}
3069
3070/*
3071 * called at mount time
3072 */
3073void ext4_ext_init(struct super_block *sb)
3074{
3075 /*
3076 * possible initialization would be here
3077 */
3078
3079 if (ext4_has_feature_extents(sb)) {
3080#if defined(AGGRESSIVE_TEST) || defined(CHECK_BINSEARCH) || defined(EXTENTS_STATS)
3081 printk(KERN_INFO "EXT4-fs: file extents enabled"
3082#ifdef AGGRESSIVE_TEST
3083 ", aggressive tests"
3084#endif
3085#ifdef CHECK_BINSEARCH
3086 ", check binsearch"
3087#endif
3088#ifdef EXTENTS_STATS
3089 ", stats"
3090#endif
3091 "\n");
3092#endif
3093#ifdef EXTENTS_STATS
3094 spin_lock_init(&EXT4_SB(sb)->s_ext_stats_lock);
3095 EXT4_SB(sb)->s_ext_min = 1 << 30;
3096 EXT4_SB(sb)->s_ext_max = 0;
3097#endif
3098 }
3099}
3100
3101/*
3102 * called at umount time
3103 */
3104void ext4_ext_release(struct super_block *sb)
3105{
3106 if (!ext4_has_feature_extents(sb))
3107 return;
3108
3109#ifdef EXTENTS_STATS
3110 if (EXT4_SB(sb)->s_ext_blocks && EXT4_SB(sb)->s_ext_extents) {
3111 struct ext4_sb_info *sbi = EXT4_SB(sb);
3112 printk(KERN_ERR "EXT4-fs: %lu blocks in %lu extents (%lu ave)\n",
3113 sbi->s_ext_blocks, sbi->s_ext_extents,
3114 sbi->s_ext_blocks / sbi->s_ext_extents);
3115 printk(KERN_ERR "EXT4-fs: extents: %lu min, %lu max, max depth %lu\n",
3116 sbi->s_ext_min, sbi->s_ext_max, sbi->s_depth_max);
3117 }
3118#endif
3119}
3120
3121static int ext4_zeroout_es(struct inode *inode, struct ext4_extent *ex)
3122{
3123 ext4_lblk_t ee_block;
3124 ext4_fsblk_t ee_pblock;
3125 unsigned int ee_len;
3126
3127 ee_block = le32_to_cpu(ex->ee_block);
3128 ee_len = ext4_ext_get_actual_len(ex);
3129 ee_pblock = ext4_ext_pblock(ex);
3130
3131 if (ee_len == 0)
3132 return 0;
3133
3134 return ext4_es_insert_extent(inode, ee_block, ee_len, ee_pblock,
3135 EXTENT_STATUS_WRITTEN);
3136}
3137
3138/* FIXME!! we need to try to merge to left or right after zero-out */
3139static int ext4_ext_zeroout(struct inode *inode, struct ext4_extent *ex)
3140{
3141 ext4_fsblk_t ee_pblock;
3142 unsigned int ee_len;
3143
3144 ee_len = ext4_ext_get_actual_len(ex);
3145 ee_pblock = ext4_ext_pblock(ex);
3146 return ext4_issue_zeroout(inode, le32_to_cpu(ex->ee_block), ee_pblock,
3147 ee_len);
3148}
3149
3150/*
3151 * ext4_split_extent_at() splits an extent at given block.
3152 *
3153 * @handle: the journal handle
3154 * @inode: the file inode
3155 * @path: the path to the extent
3156 * @split: the logical block where the extent is splitted.
3157 * @split_flags: indicates if the extent could be zeroout if split fails, and
3158 * the states(init or unwritten) of new extents.
3159 * @flags: flags used to insert new extent to extent tree.
3160 *
3161 *
3162 * Splits extent [a, b] into two extents [a, @split) and [@split, b], states
Olivier Deprez157378f2022-04-04 15:47:50 +02003163 * of which are determined by split_flag.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003164 *
3165 * There are two cases:
3166 * a> the extent are splitted into two extent.
3167 * b> split is not needed, and just mark the extent.
3168 *
3169 * return 0 on success.
3170 */
3171static int ext4_split_extent_at(handle_t *handle,
3172 struct inode *inode,
3173 struct ext4_ext_path **ppath,
3174 ext4_lblk_t split,
3175 int split_flag,
3176 int flags)
3177{
3178 struct ext4_ext_path *path = *ppath;
3179 ext4_fsblk_t newblock;
3180 ext4_lblk_t ee_block;
3181 struct ext4_extent *ex, newex, orig_ex, zero_ex;
3182 struct ext4_extent *ex2 = NULL;
3183 unsigned int ee_len, depth;
3184 int err = 0;
3185
3186 BUG_ON((split_flag & (EXT4_EXT_DATA_VALID1 | EXT4_EXT_DATA_VALID2)) ==
3187 (EXT4_EXT_DATA_VALID1 | EXT4_EXT_DATA_VALID2));
3188
Olivier Deprez157378f2022-04-04 15:47:50 +02003189 ext_debug(inode, "logical block %llu\n", (unsigned long long)split);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003190
3191 ext4_ext_show_leaf(inode, path);
3192
3193 depth = ext_depth(inode);
3194 ex = path[depth].p_ext;
3195 ee_block = le32_to_cpu(ex->ee_block);
3196 ee_len = ext4_ext_get_actual_len(ex);
3197 newblock = split - ee_block + ext4_ext_pblock(ex);
3198
3199 BUG_ON(split < ee_block || split >= (ee_block + ee_len));
3200 BUG_ON(!ext4_ext_is_unwritten(ex) &&
3201 split_flag & (EXT4_EXT_MAY_ZEROOUT |
3202 EXT4_EXT_MARK_UNWRIT1 |
3203 EXT4_EXT_MARK_UNWRIT2));
3204
3205 err = ext4_ext_get_access(handle, inode, path + depth);
3206 if (err)
3207 goto out;
3208
3209 if (split == ee_block) {
3210 /*
3211 * case b: block @split is the block that the extent begins with
3212 * then we just change the state of the extent, and splitting
3213 * is not needed.
3214 */
3215 if (split_flag & EXT4_EXT_MARK_UNWRIT2)
3216 ext4_ext_mark_unwritten(ex);
3217 else
3218 ext4_ext_mark_initialized(ex);
3219
3220 if (!(flags & EXT4_GET_BLOCKS_PRE_IO))
3221 ext4_ext_try_to_merge(handle, inode, path, ex);
3222
3223 err = ext4_ext_dirty(handle, inode, path + path->p_depth);
3224 goto out;
3225 }
3226
3227 /* case a */
3228 memcpy(&orig_ex, ex, sizeof(orig_ex));
3229 ex->ee_len = cpu_to_le16(split - ee_block);
3230 if (split_flag & EXT4_EXT_MARK_UNWRIT1)
3231 ext4_ext_mark_unwritten(ex);
3232
3233 /*
3234 * path may lead to new leaf, not to original leaf any more
3235 * after ext4_ext_insert_extent() returns,
3236 */
3237 err = ext4_ext_dirty(handle, inode, path + depth);
3238 if (err)
3239 goto fix_extent_len;
3240
3241 ex2 = &newex;
3242 ex2->ee_block = cpu_to_le32(split);
3243 ex2->ee_len = cpu_to_le16(ee_len - (split - ee_block));
3244 ext4_ext_store_pblock(ex2, newblock);
3245 if (split_flag & EXT4_EXT_MARK_UNWRIT2)
3246 ext4_ext_mark_unwritten(ex2);
3247
3248 err = ext4_ext_insert_extent(handle, inode, ppath, &newex, flags);
Olivier Deprez0e641232021-09-23 10:07:05 +02003249 if (err != -ENOSPC && err != -EDQUOT)
3250 goto out;
3251
3252 if (EXT4_EXT_MAY_ZEROOUT & split_flag) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003253 if (split_flag & (EXT4_EXT_DATA_VALID1|EXT4_EXT_DATA_VALID2)) {
3254 if (split_flag & EXT4_EXT_DATA_VALID1) {
3255 err = ext4_ext_zeroout(inode, ex2);
3256 zero_ex.ee_block = ex2->ee_block;
3257 zero_ex.ee_len = cpu_to_le16(
3258 ext4_ext_get_actual_len(ex2));
3259 ext4_ext_store_pblock(&zero_ex,
3260 ext4_ext_pblock(ex2));
3261 } else {
3262 err = ext4_ext_zeroout(inode, ex);
3263 zero_ex.ee_block = ex->ee_block;
3264 zero_ex.ee_len = cpu_to_le16(
3265 ext4_ext_get_actual_len(ex));
3266 ext4_ext_store_pblock(&zero_ex,
3267 ext4_ext_pblock(ex));
3268 }
3269 } else {
3270 err = ext4_ext_zeroout(inode, &orig_ex);
3271 zero_ex.ee_block = orig_ex.ee_block;
3272 zero_ex.ee_len = cpu_to_le16(
3273 ext4_ext_get_actual_len(&orig_ex));
3274 ext4_ext_store_pblock(&zero_ex,
3275 ext4_ext_pblock(&orig_ex));
3276 }
3277
Olivier Deprez0e641232021-09-23 10:07:05 +02003278 if (!err) {
3279 /* update the extent length and mark as initialized */
3280 ex->ee_len = cpu_to_le16(ee_len);
3281 ext4_ext_try_to_merge(handle, inode, path, ex);
3282 err = ext4_ext_dirty(handle, inode, path + path->p_depth);
3283 if (!err)
3284 /* update extent status tree */
3285 err = ext4_zeroout_es(inode, &zero_ex);
3286 /* If we failed at this point, we don't know in which
3287 * state the extent tree exactly is so don't try to fix
3288 * length of the original extent as it may do even more
3289 * damage.
3290 */
3291 goto out;
3292 }
3293 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003294
3295fix_extent_len:
3296 ex->ee_len = orig_ex.ee_len;
Olivier Deprez157378f2022-04-04 15:47:50 +02003297 /*
3298 * Ignore ext4_ext_dirty return value since we are already in error path
3299 * and err is a non-zero error code.
3300 */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003301 ext4_ext_dirty(handle, inode, path + path->p_depth);
3302 return err;
Olivier Deprez0e641232021-09-23 10:07:05 +02003303out:
3304 ext4_ext_show_leaf(inode, path);
3305 return err;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003306}
3307
3308/*
3309 * ext4_split_extents() splits an extent and mark extent which is covered
3310 * by @map as split_flags indicates
3311 *
3312 * It may result in splitting the extent into multiple extents (up to three)
3313 * There are three possibilities:
3314 * a> There is no split required
3315 * b> Splits in two extents: Split is happening at either end of the extent
3316 * c> Splits in three extents: Somone is splitting in middle of the extent
3317 *
3318 */
3319static int ext4_split_extent(handle_t *handle,
3320 struct inode *inode,
3321 struct ext4_ext_path **ppath,
3322 struct ext4_map_blocks *map,
3323 int split_flag,
3324 int flags)
3325{
3326 struct ext4_ext_path *path = *ppath;
3327 ext4_lblk_t ee_block;
3328 struct ext4_extent *ex;
3329 unsigned int ee_len, depth;
3330 int err = 0;
3331 int unwritten;
3332 int split_flag1, flags1;
3333 int allocated = map->m_len;
3334
3335 depth = ext_depth(inode);
3336 ex = path[depth].p_ext;
3337 ee_block = le32_to_cpu(ex->ee_block);
3338 ee_len = ext4_ext_get_actual_len(ex);
3339 unwritten = ext4_ext_is_unwritten(ex);
3340
3341 if (map->m_lblk + map->m_len < ee_block + ee_len) {
3342 split_flag1 = split_flag & EXT4_EXT_MAY_ZEROOUT;
3343 flags1 = flags | EXT4_GET_BLOCKS_PRE_IO;
3344 if (unwritten)
3345 split_flag1 |= EXT4_EXT_MARK_UNWRIT1 |
3346 EXT4_EXT_MARK_UNWRIT2;
3347 if (split_flag & EXT4_EXT_DATA_VALID2)
3348 split_flag1 |= EXT4_EXT_DATA_VALID1;
3349 err = ext4_split_extent_at(handle, inode, ppath,
3350 map->m_lblk + map->m_len, split_flag1, flags1);
3351 if (err)
3352 goto out;
3353 } else {
3354 allocated = ee_len - (map->m_lblk - ee_block);
3355 }
3356 /*
3357 * Update path is required because previous ext4_split_extent_at() may
3358 * result in split of original leaf or extent zeroout.
3359 */
Olivier Deprez157378f2022-04-04 15:47:50 +02003360 path = ext4_find_extent(inode, map->m_lblk, ppath, flags);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003361 if (IS_ERR(path))
3362 return PTR_ERR(path);
3363 depth = ext_depth(inode);
3364 ex = path[depth].p_ext;
3365 if (!ex) {
3366 EXT4_ERROR_INODE(inode, "unexpected hole at %lu",
3367 (unsigned long) map->m_lblk);
3368 return -EFSCORRUPTED;
3369 }
3370 unwritten = ext4_ext_is_unwritten(ex);
3371 split_flag1 = 0;
3372
3373 if (map->m_lblk >= ee_block) {
3374 split_flag1 = split_flag & EXT4_EXT_DATA_VALID2;
3375 if (unwritten) {
3376 split_flag1 |= EXT4_EXT_MARK_UNWRIT1;
3377 split_flag1 |= split_flag & (EXT4_EXT_MAY_ZEROOUT |
3378 EXT4_EXT_MARK_UNWRIT2);
3379 }
3380 err = ext4_split_extent_at(handle, inode, ppath,
3381 map->m_lblk, split_flag1, flags);
3382 if (err)
3383 goto out;
3384 }
3385
3386 ext4_ext_show_leaf(inode, path);
3387out:
3388 return err ? err : allocated;
3389}
3390
3391/*
3392 * This function is called by ext4_ext_map_blocks() if someone tries to write
3393 * to an unwritten extent. It may result in splitting the unwritten
3394 * extent into multiple extents (up to three - one initialized and two
3395 * unwritten).
3396 * There are three possibilities:
3397 * a> There is no split required: Entire extent should be initialized
3398 * b> Splits in two extents: Write is happening at either end of the extent
3399 * c> Splits in three extents: Somone is writing in middle of the extent
3400 *
3401 * Pre-conditions:
3402 * - The extent pointed to by 'path' is unwritten.
3403 * - The extent pointed to by 'path' contains a superset
3404 * of the logical span [map->m_lblk, map->m_lblk + map->m_len).
3405 *
3406 * Post-conditions on success:
3407 * - the returned value is the number of blocks beyond map->l_lblk
3408 * that are allocated and initialized.
3409 * It is guaranteed to be >= map->m_len.
3410 */
3411static int ext4_ext_convert_to_initialized(handle_t *handle,
3412 struct inode *inode,
3413 struct ext4_map_blocks *map,
3414 struct ext4_ext_path **ppath,
3415 int flags)
3416{
3417 struct ext4_ext_path *path = *ppath;
3418 struct ext4_sb_info *sbi;
3419 struct ext4_extent_header *eh;
3420 struct ext4_map_blocks split_map;
3421 struct ext4_extent zero_ex1, zero_ex2;
3422 struct ext4_extent *ex, *abut_ex;
3423 ext4_lblk_t ee_block, eof_block;
3424 unsigned int ee_len, depth, map_len = map->m_len;
3425 int allocated = 0, max_zeroout = 0;
3426 int err = 0;
3427 int split_flag = EXT4_EXT_DATA_VALID2;
3428
Olivier Deprez157378f2022-04-04 15:47:50 +02003429 ext_debug(inode, "logical block %llu, max_blocks %u\n",
3430 (unsigned long long)map->m_lblk, map_len);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003431
3432 sbi = EXT4_SB(inode->i_sb);
Olivier Deprez0e641232021-09-23 10:07:05 +02003433 eof_block = (EXT4_I(inode)->i_disksize + inode->i_sb->s_blocksize - 1)
3434 >> inode->i_sb->s_blocksize_bits;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003435 if (eof_block < map->m_lblk + map_len)
3436 eof_block = map->m_lblk + map_len;
3437
3438 depth = ext_depth(inode);
3439 eh = path[depth].p_hdr;
3440 ex = path[depth].p_ext;
3441 ee_block = le32_to_cpu(ex->ee_block);
3442 ee_len = ext4_ext_get_actual_len(ex);
3443 zero_ex1.ee_len = 0;
3444 zero_ex2.ee_len = 0;
3445
3446 trace_ext4_ext_convert_to_initialized_enter(inode, map, ex);
3447
3448 /* Pre-conditions */
3449 BUG_ON(!ext4_ext_is_unwritten(ex));
3450 BUG_ON(!in_range(map->m_lblk, ee_block, ee_len));
3451
3452 /*
3453 * Attempt to transfer newly initialized blocks from the currently
3454 * unwritten extent to its neighbor. This is much cheaper
3455 * than an insertion followed by a merge as those involve costly
3456 * memmove() calls. Transferring to the left is the common case in
3457 * steady state for workloads doing fallocate(FALLOC_FL_KEEP_SIZE)
3458 * followed by append writes.
3459 *
3460 * Limitations of the current logic:
3461 * - L1: we do not deal with writes covering the whole extent.
3462 * This would require removing the extent if the transfer
3463 * is possible.
3464 * - L2: we only attempt to merge with an extent stored in the
3465 * same extent tree node.
3466 */
3467 if ((map->m_lblk == ee_block) &&
3468 /* See if we can merge left */
3469 (map_len < ee_len) && /*L1*/
3470 (ex > EXT_FIRST_EXTENT(eh))) { /*L2*/
3471 ext4_lblk_t prev_lblk;
3472 ext4_fsblk_t prev_pblk, ee_pblk;
3473 unsigned int prev_len;
3474
3475 abut_ex = ex - 1;
3476 prev_lblk = le32_to_cpu(abut_ex->ee_block);
3477 prev_len = ext4_ext_get_actual_len(abut_ex);
3478 prev_pblk = ext4_ext_pblock(abut_ex);
3479 ee_pblk = ext4_ext_pblock(ex);
3480
3481 /*
3482 * A transfer of blocks from 'ex' to 'abut_ex' is allowed
3483 * upon those conditions:
3484 * - C1: abut_ex is initialized,
3485 * - C2: abut_ex is logically abutting ex,
3486 * - C3: abut_ex is physically abutting ex,
3487 * - C4: abut_ex can receive the additional blocks without
3488 * overflowing the (initialized) length limit.
3489 */
3490 if ((!ext4_ext_is_unwritten(abut_ex)) && /*C1*/
3491 ((prev_lblk + prev_len) == ee_block) && /*C2*/
3492 ((prev_pblk + prev_len) == ee_pblk) && /*C3*/
3493 (prev_len < (EXT_INIT_MAX_LEN - map_len))) { /*C4*/
3494 err = ext4_ext_get_access(handle, inode, path + depth);
3495 if (err)
3496 goto out;
3497
3498 trace_ext4_ext_convert_to_initialized_fastpath(inode,
3499 map, ex, abut_ex);
3500
3501 /* Shift the start of ex by 'map_len' blocks */
3502 ex->ee_block = cpu_to_le32(ee_block + map_len);
3503 ext4_ext_store_pblock(ex, ee_pblk + map_len);
3504 ex->ee_len = cpu_to_le16(ee_len - map_len);
3505 ext4_ext_mark_unwritten(ex); /* Restore the flag */
3506
3507 /* Extend abut_ex by 'map_len' blocks */
3508 abut_ex->ee_len = cpu_to_le16(prev_len + map_len);
3509
3510 /* Result: number of initialized blocks past m_lblk */
3511 allocated = map_len;
3512 }
3513 } else if (((map->m_lblk + map_len) == (ee_block + ee_len)) &&
3514 (map_len < ee_len) && /*L1*/
3515 ex < EXT_LAST_EXTENT(eh)) { /*L2*/
3516 /* See if we can merge right */
3517 ext4_lblk_t next_lblk;
3518 ext4_fsblk_t next_pblk, ee_pblk;
3519 unsigned int next_len;
3520
3521 abut_ex = ex + 1;
3522 next_lblk = le32_to_cpu(abut_ex->ee_block);
3523 next_len = ext4_ext_get_actual_len(abut_ex);
3524 next_pblk = ext4_ext_pblock(abut_ex);
3525 ee_pblk = ext4_ext_pblock(ex);
3526
3527 /*
3528 * A transfer of blocks from 'ex' to 'abut_ex' is allowed
3529 * upon those conditions:
3530 * - C1: abut_ex is initialized,
3531 * - C2: abut_ex is logically abutting ex,
3532 * - C3: abut_ex is physically abutting ex,
3533 * - C4: abut_ex can receive the additional blocks without
3534 * overflowing the (initialized) length limit.
3535 */
3536 if ((!ext4_ext_is_unwritten(abut_ex)) && /*C1*/
3537 ((map->m_lblk + map_len) == next_lblk) && /*C2*/
3538 ((ee_pblk + ee_len) == next_pblk) && /*C3*/
3539 (next_len < (EXT_INIT_MAX_LEN - map_len))) { /*C4*/
3540 err = ext4_ext_get_access(handle, inode, path + depth);
3541 if (err)
3542 goto out;
3543
3544 trace_ext4_ext_convert_to_initialized_fastpath(inode,
3545 map, ex, abut_ex);
3546
3547 /* Shift the start of abut_ex by 'map_len' blocks */
3548 abut_ex->ee_block = cpu_to_le32(next_lblk - map_len);
3549 ext4_ext_store_pblock(abut_ex, next_pblk - map_len);
3550 ex->ee_len = cpu_to_le16(ee_len - map_len);
3551 ext4_ext_mark_unwritten(ex); /* Restore the flag */
3552
3553 /* Extend abut_ex by 'map_len' blocks */
3554 abut_ex->ee_len = cpu_to_le16(next_len + map_len);
3555
3556 /* Result: number of initialized blocks past m_lblk */
3557 allocated = map_len;
3558 }
3559 }
3560 if (allocated) {
3561 /* Mark the block containing both extents as dirty */
Olivier Deprez157378f2022-04-04 15:47:50 +02003562 err = ext4_ext_dirty(handle, inode, path + depth);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003563
3564 /* Update path to point to the right extent */
3565 path[depth].p_ext = abut_ex;
3566 goto out;
3567 } else
3568 allocated = ee_len - (map->m_lblk - ee_block);
3569
3570 WARN_ON(map->m_lblk < ee_block);
3571 /*
3572 * It is safe to convert extent to initialized via explicit
3573 * zeroout only if extent is fully inside i_size or new_size.
3574 */
3575 split_flag |= ee_block + ee_len <= eof_block ? EXT4_EXT_MAY_ZEROOUT : 0;
3576
3577 if (EXT4_EXT_MAY_ZEROOUT & split_flag)
3578 max_zeroout = sbi->s_extent_max_zeroout_kb >>
3579 (inode->i_sb->s_blocksize_bits - 10);
3580
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003581 /*
3582 * five cases:
3583 * 1. split the extent into three extents.
3584 * 2. split the extent into two extents, zeroout the head of the first
3585 * extent.
3586 * 3. split the extent into two extents, zeroout the tail of the second
3587 * extent.
3588 * 4. split the extent into two extents with out zeroout.
3589 * 5. no splitting needed, just possibly zeroout the head and / or the
3590 * tail of the extent.
3591 */
3592 split_map.m_lblk = map->m_lblk;
3593 split_map.m_len = map->m_len;
3594
3595 if (max_zeroout && (allocated > split_map.m_len)) {
3596 if (allocated <= max_zeroout) {
3597 /* case 3 or 5 */
3598 zero_ex1.ee_block =
3599 cpu_to_le32(split_map.m_lblk +
3600 split_map.m_len);
3601 zero_ex1.ee_len =
3602 cpu_to_le16(allocated - split_map.m_len);
3603 ext4_ext_store_pblock(&zero_ex1,
3604 ext4_ext_pblock(ex) + split_map.m_lblk +
3605 split_map.m_len - ee_block);
3606 err = ext4_ext_zeroout(inode, &zero_ex1);
3607 if (err)
3608 goto out;
3609 split_map.m_len = allocated;
3610 }
3611 if (split_map.m_lblk - ee_block + split_map.m_len <
3612 max_zeroout) {
3613 /* case 2 or 5 */
3614 if (split_map.m_lblk != ee_block) {
3615 zero_ex2.ee_block = ex->ee_block;
3616 zero_ex2.ee_len = cpu_to_le16(split_map.m_lblk -
3617 ee_block);
3618 ext4_ext_store_pblock(&zero_ex2,
3619 ext4_ext_pblock(ex));
3620 err = ext4_ext_zeroout(inode, &zero_ex2);
3621 if (err)
3622 goto out;
3623 }
3624
3625 split_map.m_len += split_map.m_lblk - ee_block;
3626 split_map.m_lblk = ee_block;
3627 allocated = map->m_len;
3628 }
3629 }
3630
3631 err = ext4_split_extent(handle, inode, ppath, &split_map, split_flag,
3632 flags);
3633 if (err > 0)
3634 err = 0;
3635out:
3636 /* If we have gotten a failure, don't zero out status tree */
3637 if (!err) {
3638 err = ext4_zeroout_es(inode, &zero_ex1);
3639 if (!err)
3640 err = ext4_zeroout_es(inode, &zero_ex2);
3641 }
3642 return err ? err : allocated;
3643}
3644
3645/*
3646 * This function is called by ext4_ext_map_blocks() from
3647 * ext4_get_blocks_dio_write() when DIO to write
3648 * to an unwritten extent.
3649 *
3650 * Writing to an unwritten extent may result in splitting the unwritten
3651 * extent into multiple initialized/unwritten extents (up to three)
3652 * There are three possibilities:
3653 * a> There is no split required: Entire extent should be unwritten
3654 * b> Splits in two extents: Write is happening at either end of the extent
3655 * c> Splits in three extents: Somone is writing in middle of the extent
3656 *
3657 * This works the same way in the case of initialized -> unwritten conversion.
3658 *
3659 * One of more index blocks maybe needed if the extent tree grow after
3660 * the unwritten extent split. To prevent ENOSPC occur at the IO
3661 * complete, we need to split the unwritten extent before DIO submit
3662 * the IO. The unwritten extent called at this time will be split
3663 * into three unwritten extent(at most). After IO complete, the part
3664 * being filled will be convert to initialized by the end_io callback function
3665 * via ext4_convert_unwritten_extents().
3666 *
3667 * Returns the size of unwritten extent to be written on success.
3668 */
3669static int ext4_split_convert_extents(handle_t *handle,
3670 struct inode *inode,
3671 struct ext4_map_blocks *map,
3672 struct ext4_ext_path **ppath,
3673 int flags)
3674{
3675 struct ext4_ext_path *path = *ppath;
3676 ext4_lblk_t eof_block;
3677 ext4_lblk_t ee_block;
3678 struct ext4_extent *ex;
3679 unsigned int ee_len;
3680 int split_flag = 0, depth;
3681
Olivier Deprez157378f2022-04-04 15:47:50 +02003682 ext_debug(inode, "logical block %llu, max_blocks %u\n",
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003683 (unsigned long long)map->m_lblk, map->m_len);
3684
Olivier Deprez0e641232021-09-23 10:07:05 +02003685 eof_block = (EXT4_I(inode)->i_disksize + inode->i_sb->s_blocksize - 1)
3686 >> inode->i_sb->s_blocksize_bits;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003687 if (eof_block < map->m_lblk + map->m_len)
3688 eof_block = map->m_lblk + map->m_len;
3689 /*
3690 * It is safe to convert extent to initialized via explicit
Olivier Deprez157378f2022-04-04 15:47:50 +02003691 * zeroout only if extent is fully inside i_size or new_size.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003692 */
3693 depth = ext_depth(inode);
3694 ex = path[depth].p_ext;
3695 ee_block = le32_to_cpu(ex->ee_block);
3696 ee_len = ext4_ext_get_actual_len(ex);
3697
3698 /* Convert to unwritten */
3699 if (flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN) {
3700 split_flag |= EXT4_EXT_DATA_VALID1;
3701 /* Convert to initialized */
3702 } else if (flags & EXT4_GET_BLOCKS_CONVERT) {
3703 split_flag |= ee_block + ee_len <= eof_block ?
3704 EXT4_EXT_MAY_ZEROOUT : 0;
3705 split_flag |= (EXT4_EXT_MARK_UNWRIT2 | EXT4_EXT_DATA_VALID2);
3706 }
3707 flags |= EXT4_GET_BLOCKS_PRE_IO;
3708 return ext4_split_extent(handle, inode, ppath, map, split_flag, flags);
3709}
3710
3711static int ext4_convert_unwritten_extents_endio(handle_t *handle,
3712 struct inode *inode,
3713 struct ext4_map_blocks *map,
3714 struct ext4_ext_path **ppath)
3715{
3716 struct ext4_ext_path *path = *ppath;
3717 struct ext4_extent *ex;
3718 ext4_lblk_t ee_block;
3719 unsigned int ee_len;
3720 int depth;
3721 int err = 0;
3722
3723 depth = ext_depth(inode);
3724 ex = path[depth].p_ext;
3725 ee_block = le32_to_cpu(ex->ee_block);
3726 ee_len = ext4_ext_get_actual_len(ex);
3727
Olivier Deprez157378f2022-04-04 15:47:50 +02003728 ext_debug(inode, "logical block %llu, max_blocks %u\n",
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003729 (unsigned long long)ee_block, ee_len);
3730
3731 /* If extent is larger than requested it is a clear sign that we still
3732 * have some extent state machine issues left. So extent_split is still
3733 * required.
3734 * TODO: Once all related issues will be fixed this situation should be
3735 * illegal.
3736 */
3737 if (ee_block != map->m_lblk || ee_len > map->m_len) {
David Brazdil0f672f62019-12-10 10:32:29 +00003738#ifdef CONFIG_EXT4_DEBUG
3739 ext4_warning(inode->i_sb, "Inode (%ld) finished: extent logical block %llu,"
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003740 " len %u; IO logical block %llu, len %u",
3741 inode->i_ino, (unsigned long long)ee_block, ee_len,
3742 (unsigned long long)map->m_lblk, map->m_len);
3743#endif
3744 err = ext4_split_convert_extents(handle, inode, map, ppath,
3745 EXT4_GET_BLOCKS_CONVERT);
3746 if (err < 0)
3747 return err;
3748 path = ext4_find_extent(inode, map->m_lblk, ppath, 0);
3749 if (IS_ERR(path))
3750 return PTR_ERR(path);
3751 depth = ext_depth(inode);
3752 ex = path[depth].p_ext;
3753 }
3754
3755 err = ext4_ext_get_access(handle, inode, path + depth);
3756 if (err)
3757 goto out;
3758 /* first mark the extent as initialized */
3759 ext4_ext_mark_initialized(ex);
3760
3761 /* note: ext4_ext_correct_indexes() isn't needed here because
3762 * borders are not changed
3763 */
3764 ext4_ext_try_to_merge(handle, inode, path, ex);
3765
3766 /* Mark modified extent as dirty */
3767 err = ext4_ext_dirty(handle, inode, path + path->p_depth);
3768out:
3769 ext4_ext_show_leaf(inode, path);
3770 return err;
3771}
3772
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003773static int
3774convert_initialized_extent(handle_t *handle, struct inode *inode,
3775 struct ext4_map_blocks *map,
3776 struct ext4_ext_path **ppath,
Olivier Deprez157378f2022-04-04 15:47:50 +02003777 unsigned int *allocated)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003778{
3779 struct ext4_ext_path *path = *ppath;
3780 struct ext4_extent *ex;
3781 ext4_lblk_t ee_block;
3782 unsigned int ee_len;
3783 int depth;
3784 int err = 0;
3785
3786 /*
3787 * Make sure that the extent is no bigger than we support with
3788 * unwritten extent
3789 */
3790 if (map->m_len > EXT_UNWRITTEN_MAX_LEN)
3791 map->m_len = EXT_UNWRITTEN_MAX_LEN / 2;
3792
3793 depth = ext_depth(inode);
3794 ex = path[depth].p_ext;
3795 ee_block = le32_to_cpu(ex->ee_block);
3796 ee_len = ext4_ext_get_actual_len(ex);
3797
Olivier Deprez157378f2022-04-04 15:47:50 +02003798 ext_debug(inode, "logical block %llu, max_blocks %u\n",
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003799 (unsigned long long)ee_block, ee_len);
3800
3801 if (ee_block != map->m_lblk || ee_len > map->m_len) {
3802 err = ext4_split_convert_extents(handle, inode, map, ppath,
3803 EXT4_GET_BLOCKS_CONVERT_UNWRITTEN);
3804 if (err < 0)
3805 return err;
3806 path = ext4_find_extent(inode, map->m_lblk, ppath, 0);
3807 if (IS_ERR(path))
3808 return PTR_ERR(path);
3809 depth = ext_depth(inode);
3810 ex = path[depth].p_ext;
3811 if (!ex) {
3812 EXT4_ERROR_INODE(inode, "unexpected hole at %lu",
3813 (unsigned long) map->m_lblk);
3814 return -EFSCORRUPTED;
3815 }
3816 }
3817
3818 err = ext4_ext_get_access(handle, inode, path + depth);
3819 if (err)
3820 return err;
3821 /* first mark the extent as unwritten */
3822 ext4_ext_mark_unwritten(ex);
3823
3824 /* note: ext4_ext_correct_indexes() isn't needed here because
3825 * borders are not changed
3826 */
3827 ext4_ext_try_to_merge(handle, inode, path, ex);
3828
3829 /* Mark modified extent as dirty */
3830 err = ext4_ext_dirty(handle, inode, path + path->p_depth);
3831 if (err)
3832 return err;
3833 ext4_ext_show_leaf(inode, path);
3834
3835 ext4_update_inode_fsync_trans(handle, inode, 1);
Olivier Deprez157378f2022-04-04 15:47:50 +02003836
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003837 map->m_flags |= EXT4_MAP_UNWRITTEN;
Olivier Deprez157378f2022-04-04 15:47:50 +02003838 if (*allocated > map->m_len)
3839 *allocated = map->m_len;
3840 map->m_len = *allocated;
3841 return 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003842}
3843
3844static int
3845ext4_ext_handle_unwritten_extents(handle_t *handle, struct inode *inode,
3846 struct ext4_map_blocks *map,
3847 struct ext4_ext_path **ppath, int flags,
3848 unsigned int allocated, ext4_fsblk_t newblock)
3849{
Olivier Deprez157378f2022-04-04 15:47:50 +02003850 struct ext4_ext_path __maybe_unused *path = *ppath;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003851 int ret = 0;
3852 int err = 0;
3853
Olivier Deprez157378f2022-04-04 15:47:50 +02003854 ext_debug(inode, "logical block %llu, max_blocks %u, flags 0x%x, allocated %u\n",
3855 (unsigned long long)map->m_lblk, map->m_len, flags,
3856 allocated);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003857 ext4_ext_show_leaf(inode, path);
3858
3859 /*
3860 * When writing into unwritten space, we should not fail to
3861 * allocate metadata blocks for the new extent block if needed.
3862 */
3863 flags |= EXT4_GET_BLOCKS_METADATA_NOFAIL;
3864
3865 trace_ext4_ext_handle_unwritten_extents(inode, map, flags,
3866 allocated, newblock);
3867
Olivier Deprez157378f2022-04-04 15:47:50 +02003868 /* get_block() before submitting IO, split the extent */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003869 if (flags & EXT4_GET_BLOCKS_PRE_IO) {
3870 ret = ext4_split_convert_extents(handle, inode, map, ppath,
3871 flags | EXT4_GET_BLOCKS_CONVERT);
Olivier Deprez157378f2022-04-04 15:47:50 +02003872 if (ret < 0) {
3873 err = ret;
3874 goto out2;
3875 }
3876 /*
3877 * shouldn't get a 0 return when splitting an extent unless
3878 * m_len is 0 (bug) or extent has been corrupted
3879 */
3880 if (unlikely(ret == 0)) {
3881 EXT4_ERROR_INODE(inode,
3882 "unexpected ret == 0, m_len = %u",
3883 map->m_len);
3884 err = -EFSCORRUPTED;
3885 goto out2;
3886 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003887 map->m_flags |= EXT4_MAP_UNWRITTEN;
3888 goto out;
3889 }
3890 /* IO end_io complete, convert the filled extent to written */
3891 if (flags & EXT4_GET_BLOCKS_CONVERT) {
Olivier Deprez157378f2022-04-04 15:47:50 +02003892 err = ext4_convert_unwritten_extents_endio(handle, inode, map,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003893 ppath);
Olivier Deprez157378f2022-04-04 15:47:50 +02003894 if (err < 0)
3895 goto out2;
3896 ext4_update_inode_fsync_trans(handle, inode, 1);
3897 goto map_out;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003898 }
Olivier Deprez157378f2022-04-04 15:47:50 +02003899 /* buffered IO cases */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003900 /*
3901 * repeat fallocate creation request
3902 * we already have an unwritten extent
3903 */
3904 if (flags & EXT4_GET_BLOCKS_UNWRIT_EXT) {
3905 map->m_flags |= EXT4_MAP_UNWRITTEN;
3906 goto map_out;
3907 }
3908
3909 /* buffered READ or buffered write_begin() lookup */
3910 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
3911 /*
3912 * We have blocks reserved already. We
3913 * return allocated blocks so that delalloc
3914 * won't do block reservation for us. But
3915 * the buffer head will be unmapped so that
3916 * a read from the block returns 0s.
3917 */
3918 map->m_flags |= EXT4_MAP_UNWRITTEN;
3919 goto out1;
3920 }
3921
Olivier Deprez157378f2022-04-04 15:47:50 +02003922 /*
3923 * Default case when (flags & EXT4_GET_BLOCKS_CREATE) == 1.
3924 * For buffered writes, at writepage time, etc. Convert a
3925 * discovered unwritten extent to written.
3926 */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003927 ret = ext4_ext_convert_to_initialized(handle, inode, map, ppath, flags);
Olivier Deprez157378f2022-04-04 15:47:50 +02003928 if (ret < 0) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003929 err = ret;
3930 goto out2;
Olivier Deprez157378f2022-04-04 15:47:50 +02003931 }
3932 ext4_update_inode_fsync_trans(handle, inode, 1);
3933 /*
3934 * shouldn't get a 0 return when converting an unwritten extent
3935 * unless m_len is 0 (bug) or extent has been corrupted
3936 */
3937 if (unlikely(ret == 0)) {
3938 EXT4_ERROR_INODE(inode, "unexpected ret == 0, m_len = %u",
3939 map->m_len);
3940 err = -EFSCORRUPTED;
3941 goto out2;
3942 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003943
Olivier Deprez157378f2022-04-04 15:47:50 +02003944out:
3945 allocated = ret;
3946 map->m_flags |= EXT4_MAP_NEW;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003947map_out:
3948 map->m_flags |= EXT4_MAP_MAPPED;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003949out1:
Olivier Deprez157378f2022-04-04 15:47:50 +02003950 map->m_pblk = newblock;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003951 if (allocated > map->m_len)
3952 allocated = map->m_len;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003953 map->m_len = allocated;
Olivier Deprez157378f2022-04-04 15:47:50 +02003954 ext4_ext_show_leaf(inode, path);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003955out2:
3956 return err ? err : allocated;
3957}
3958
3959/*
3960 * get_implied_cluster_alloc - check to see if the requested
3961 * allocation (in the map structure) overlaps with a cluster already
3962 * allocated in an extent.
3963 * @sb The filesystem superblock structure
3964 * @map The requested lblk->pblk mapping
3965 * @ex The extent structure which might contain an implied
3966 * cluster allocation
3967 *
3968 * This function is called by ext4_ext_map_blocks() after we failed to
3969 * find blocks that were already in the inode's extent tree. Hence,
3970 * we know that the beginning of the requested region cannot overlap
3971 * the extent from the inode's extent tree. There are three cases we
3972 * want to catch. The first is this case:
3973 *
3974 * |--- cluster # N--|
3975 * |--- extent ---| |---- requested region ---|
3976 * |==========|
3977 *
3978 * The second case that we need to test for is this one:
3979 *
3980 * |--------- cluster # N ----------------|
3981 * |--- requested region --| |------- extent ----|
3982 * |=======================|
3983 *
3984 * The third case is when the requested region lies between two extents
3985 * within the same cluster:
3986 * |------------- cluster # N-------------|
3987 * |----- ex -----| |---- ex_right ----|
3988 * |------ requested region ------|
3989 * |================|
3990 *
3991 * In each of the above cases, we need to set the map->m_pblk and
3992 * map->m_len so it corresponds to the return the extent labelled as
3993 * "|====|" from cluster #N, since it is already in use for data in
3994 * cluster EXT4_B2C(sbi, map->m_lblk). We will then return 1 to
3995 * signal to ext4_ext_map_blocks() that map->m_pblk should be treated
3996 * as a new "allocated" block region. Otherwise, we will return 0 and
3997 * ext4_ext_map_blocks() will then allocate one or more new clusters
3998 * by calling ext4_mb_new_blocks().
3999 */
4000static int get_implied_cluster_alloc(struct super_block *sb,
4001 struct ext4_map_blocks *map,
4002 struct ext4_extent *ex,
4003 struct ext4_ext_path *path)
4004{
4005 struct ext4_sb_info *sbi = EXT4_SB(sb);
4006 ext4_lblk_t c_offset = EXT4_LBLK_COFF(sbi, map->m_lblk);
4007 ext4_lblk_t ex_cluster_start, ex_cluster_end;
4008 ext4_lblk_t rr_cluster_start;
4009 ext4_lblk_t ee_block = le32_to_cpu(ex->ee_block);
4010 ext4_fsblk_t ee_start = ext4_ext_pblock(ex);
4011 unsigned short ee_len = ext4_ext_get_actual_len(ex);
4012
4013 /* The extent passed in that we are trying to match */
4014 ex_cluster_start = EXT4_B2C(sbi, ee_block);
4015 ex_cluster_end = EXT4_B2C(sbi, ee_block + ee_len - 1);
4016
4017 /* The requested region passed into ext4_map_blocks() */
4018 rr_cluster_start = EXT4_B2C(sbi, map->m_lblk);
4019
4020 if ((rr_cluster_start == ex_cluster_end) ||
4021 (rr_cluster_start == ex_cluster_start)) {
4022 if (rr_cluster_start == ex_cluster_end)
4023 ee_start += ee_len - 1;
4024 map->m_pblk = EXT4_PBLK_CMASK(sbi, ee_start) + c_offset;
4025 map->m_len = min(map->m_len,
4026 (unsigned) sbi->s_cluster_ratio - c_offset);
4027 /*
4028 * Check for and handle this case:
4029 *
4030 * |--------- cluster # N-------------|
4031 * |------- extent ----|
4032 * |--- requested region ---|
4033 * |===========|
4034 */
4035
4036 if (map->m_lblk < ee_block)
4037 map->m_len = min(map->m_len, ee_block - map->m_lblk);
4038
4039 /*
4040 * Check for the case where there is already another allocated
4041 * block to the right of 'ex' but before the end of the cluster.
4042 *
4043 * |------------- cluster # N-------------|
4044 * |----- ex -----| |---- ex_right ----|
4045 * |------ requested region ------|
4046 * |================|
4047 */
4048 if (map->m_lblk > ee_block) {
4049 ext4_lblk_t next = ext4_ext_next_allocated_block(path);
4050 map->m_len = min(map->m_len, next - map->m_lblk);
4051 }
4052
4053 trace_ext4_get_implied_cluster_alloc_exit(sb, map, 1);
4054 return 1;
4055 }
4056
4057 trace_ext4_get_implied_cluster_alloc_exit(sb, map, 0);
4058 return 0;
4059}
4060
4061
4062/*
4063 * Block allocation/map/preallocation routine for extents based files
4064 *
4065 *
4066 * Need to be called with
4067 * down_read(&EXT4_I(inode)->i_data_sem) if not allocating file system block
4068 * (ie, create is zero). Otherwise down_write(&EXT4_I(inode)->i_data_sem)
4069 *
Olivier Deprez157378f2022-04-04 15:47:50 +02004070 * return > 0, number of blocks already mapped/allocated
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004071 * if create == 0 and these are pre-allocated blocks
4072 * buffer head is unmapped
4073 * otherwise blocks are mapped
4074 *
4075 * return = 0, if plain look up failed (blocks have not been allocated)
4076 * buffer head is unmapped
4077 *
4078 * return < 0, error case.
4079 */
4080int ext4_ext_map_blocks(handle_t *handle, struct inode *inode,
4081 struct ext4_map_blocks *map, int flags)
4082{
4083 struct ext4_ext_path *path = NULL;
Olivier Deprez157378f2022-04-04 15:47:50 +02004084 struct ext4_extent newex, *ex, ex2;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004085 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
Olivier Deprez157378f2022-04-04 15:47:50 +02004086 ext4_fsblk_t newblock = 0, pblk;
4087 int err = 0, depth, ret;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004088 unsigned int allocated = 0, offset = 0;
4089 unsigned int allocated_clusters = 0;
4090 struct ext4_allocation_request ar;
4091 ext4_lblk_t cluster_offset;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004092
Olivier Deprez157378f2022-04-04 15:47:50 +02004093 ext_debug(inode, "blocks %u/%u requested\n", map->m_lblk, map->m_len);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004094 trace_ext4_ext_map_blocks_enter(inode, map->m_lblk, map->m_len, flags);
4095
4096 /* find extent for this block */
4097 path = ext4_find_extent(inode, map->m_lblk, NULL, 0);
4098 if (IS_ERR(path)) {
4099 err = PTR_ERR(path);
4100 path = NULL;
Olivier Deprez157378f2022-04-04 15:47:50 +02004101 goto out;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004102 }
4103
4104 depth = ext_depth(inode);
4105
4106 /*
4107 * consistent leaf must not be empty;
4108 * this situation is possible, though, _during_ tree modification;
4109 * this is why assert can't be put in ext4_find_extent()
4110 */
4111 if (unlikely(path[depth].p_ext == NULL && depth != 0)) {
4112 EXT4_ERROR_INODE(inode, "bad extent address "
4113 "lblock: %lu, depth: %d pblock %lld",
4114 (unsigned long) map->m_lblk, depth,
4115 path[depth].p_block);
4116 err = -EFSCORRUPTED;
Olivier Deprez157378f2022-04-04 15:47:50 +02004117 goto out;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004118 }
4119
4120 ex = path[depth].p_ext;
4121 if (ex) {
4122 ext4_lblk_t ee_block = le32_to_cpu(ex->ee_block);
4123 ext4_fsblk_t ee_start = ext4_ext_pblock(ex);
4124 unsigned short ee_len;
4125
4126
4127 /*
4128 * unwritten extents are treated as holes, except that
4129 * we split out initialized portions during a write.
4130 */
4131 ee_len = ext4_ext_get_actual_len(ex);
4132
4133 trace_ext4_ext_show_extent(inode, ee_block, ee_start, ee_len);
4134
4135 /* if found extent covers block, simply return it */
4136 if (in_range(map->m_lblk, ee_block, ee_len)) {
4137 newblock = map->m_lblk - ee_block + ee_start;
4138 /* number of remaining blocks in the extent */
4139 allocated = ee_len - (map->m_lblk - ee_block);
Olivier Deprez157378f2022-04-04 15:47:50 +02004140 ext_debug(inode, "%u fit into %u:%d -> %llu\n",
4141 map->m_lblk, ee_block, ee_len, newblock);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004142
4143 /*
4144 * If the extent is initialized check whether the
4145 * caller wants to convert it to unwritten.
4146 */
4147 if ((!ext4_ext_is_unwritten(ex)) &&
4148 (flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN)) {
Olivier Deprez157378f2022-04-04 15:47:50 +02004149 err = convert_initialized_extent(handle,
4150 inode, map, &path, &allocated);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004151 goto out;
Olivier Deprez157378f2022-04-04 15:47:50 +02004152 } else if (!ext4_ext_is_unwritten(ex)) {
4153 map->m_flags |= EXT4_MAP_MAPPED;
4154 map->m_pblk = newblock;
4155 if (allocated > map->m_len)
4156 allocated = map->m_len;
4157 map->m_len = allocated;
4158 ext4_ext_show_leaf(inode, path);
4159 goto out;
4160 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004161
4162 ret = ext4_ext_handle_unwritten_extents(
4163 handle, inode, map, &path, flags,
4164 allocated, newblock);
4165 if (ret < 0)
4166 err = ret;
4167 else
4168 allocated = ret;
Olivier Deprez157378f2022-04-04 15:47:50 +02004169 goto out;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004170 }
4171 }
4172
4173 /*
4174 * requested block isn't allocated yet;
4175 * we couldn't try to create block if create flag is zero
4176 */
4177 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
4178 ext4_lblk_t hole_start, hole_len;
4179
4180 hole_start = map->m_lblk;
4181 hole_len = ext4_ext_determine_hole(inode, path, &hole_start);
4182 /*
4183 * put just found gap into cache to speed up
4184 * subsequent requests
4185 */
4186 ext4_ext_put_gap_in_cache(inode, hole_start, hole_len);
4187
4188 /* Update hole_len to reflect hole size after map->m_lblk */
4189 if (hole_start != map->m_lblk)
4190 hole_len -= map->m_lblk - hole_start;
4191 map->m_pblk = 0;
4192 map->m_len = min_t(unsigned int, map->m_len, hole_len);
4193
Olivier Deprez157378f2022-04-04 15:47:50 +02004194 goto out;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004195 }
4196
4197 /*
4198 * Okay, we need to do block allocation.
4199 */
4200 newex.ee_block = cpu_to_le32(map->m_lblk);
4201 cluster_offset = EXT4_LBLK_COFF(sbi, map->m_lblk);
4202
4203 /*
4204 * If we are doing bigalloc, check to see if the extent returned
4205 * by ext4_find_extent() implies a cluster we can use.
4206 */
4207 if (cluster_offset && ex &&
4208 get_implied_cluster_alloc(inode->i_sb, map, ex, path)) {
4209 ar.len = allocated = map->m_len;
4210 newblock = map->m_pblk;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004211 goto got_allocated_blocks;
4212 }
4213
4214 /* find neighbour allocated blocks */
4215 ar.lleft = map->m_lblk;
4216 err = ext4_ext_search_left(inode, path, &ar.lleft, &ar.pleft);
4217 if (err)
Olivier Deprez157378f2022-04-04 15:47:50 +02004218 goto out;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004219 ar.lright = map->m_lblk;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004220 err = ext4_ext_search_right(inode, path, &ar.lright, &ar.pright, &ex2);
Olivier Deprez157378f2022-04-04 15:47:50 +02004221 if (err < 0)
4222 goto out;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004223
4224 /* Check if the extent after searching to the right implies a
4225 * cluster we can use. */
Olivier Deprez157378f2022-04-04 15:47:50 +02004226 if ((sbi->s_cluster_ratio > 1) && err &&
4227 get_implied_cluster_alloc(inode->i_sb, map, &ex2, path)) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004228 ar.len = allocated = map->m_len;
4229 newblock = map->m_pblk;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004230 goto got_allocated_blocks;
4231 }
4232
4233 /*
4234 * See if request is beyond maximum number of blocks we can have in
4235 * a single extent. For an initialized extent this limit is
4236 * EXT_INIT_MAX_LEN and for an unwritten extent this limit is
4237 * EXT_UNWRITTEN_MAX_LEN.
4238 */
4239 if (map->m_len > EXT_INIT_MAX_LEN &&
4240 !(flags & EXT4_GET_BLOCKS_UNWRIT_EXT))
4241 map->m_len = EXT_INIT_MAX_LEN;
4242 else if (map->m_len > EXT_UNWRITTEN_MAX_LEN &&
4243 (flags & EXT4_GET_BLOCKS_UNWRIT_EXT))
4244 map->m_len = EXT_UNWRITTEN_MAX_LEN;
4245
4246 /* Check if we can really insert (m_lblk)::(m_lblk + m_len) extent */
4247 newex.ee_len = cpu_to_le16(map->m_len);
4248 err = ext4_ext_check_overlap(sbi, inode, &newex, path);
4249 if (err)
4250 allocated = ext4_ext_get_actual_len(&newex);
4251 else
4252 allocated = map->m_len;
4253
4254 /* allocate new block */
4255 ar.inode = inode;
4256 ar.goal = ext4_ext_find_goal(inode, path, map->m_lblk);
4257 ar.logical = map->m_lblk;
4258 /*
4259 * We calculate the offset from the beginning of the cluster
4260 * for the logical block number, since when we allocate a
4261 * physical cluster, the physical block should start at the
4262 * same offset from the beginning of the cluster. This is
4263 * needed so that future calls to get_implied_cluster_alloc()
4264 * work correctly.
4265 */
4266 offset = EXT4_LBLK_COFF(sbi, map->m_lblk);
4267 ar.len = EXT4_NUM_B2C(sbi, offset+allocated);
4268 ar.goal -= offset;
4269 ar.logical -= offset;
4270 if (S_ISREG(inode->i_mode))
4271 ar.flags = EXT4_MB_HINT_DATA;
4272 else
4273 /* disable in-core preallocation for non-regular files */
4274 ar.flags = 0;
4275 if (flags & EXT4_GET_BLOCKS_NO_NORMALIZE)
4276 ar.flags |= EXT4_MB_HINT_NOPREALLOC;
4277 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
4278 ar.flags |= EXT4_MB_DELALLOC_RESERVED;
4279 if (flags & EXT4_GET_BLOCKS_METADATA_NOFAIL)
4280 ar.flags |= EXT4_MB_USE_RESERVED;
4281 newblock = ext4_mb_new_blocks(handle, &ar, &err);
4282 if (!newblock)
Olivier Deprez157378f2022-04-04 15:47:50 +02004283 goto out;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004284 allocated_clusters = ar.len;
4285 ar.len = EXT4_C2B(sbi, ar.len) - offset;
Olivier Deprez157378f2022-04-04 15:47:50 +02004286 ext_debug(inode, "allocate new block: goal %llu, found %llu/%u, requested %u\n",
4287 ar.goal, newblock, ar.len, allocated);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004288 if (ar.len > allocated)
4289 ar.len = allocated;
4290
4291got_allocated_blocks:
4292 /* try to insert new extent into found leaf and return */
Olivier Deprez157378f2022-04-04 15:47:50 +02004293 pblk = newblock + offset;
4294 ext4_ext_store_pblock(&newex, pblk);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004295 newex.ee_len = cpu_to_le16(ar.len);
4296 /* Mark unwritten */
Olivier Deprez157378f2022-04-04 15:47:50 +02004297 if (flags & EXT4_GET_BLOCKS_UNWRIT_EXT) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004298 ext4_ext_mark_unwritten(&newex);
4299 map->m_flags |= EXT4_MAP_UNWRITTEN;
4300 }
4301
Olivier Deprez157378f2022-04-04 15:47:50 +02004302 err = ext4_ext_insert_extent(handle, inode, &path, &newex, flags);
4303 if (err) {
4304 if (allocated_clusters) {
4305 int fb_flags = 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004306
Olivier Deprez157378f2022-04-04 15:47:50 +02004307 /*
4308 * free data blocks we just allocated.
4309 * not a good idea to call discard here directly,
4310 * but otherwise we'd need to call it every free().
4311 */
4312 ext4_discard_preallocations(inode, 0);
4313 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
4314 fb_flags = EXT4_FREE_BLOCKS_NO_QUOT_UPDATE;
4315 ext4_free_blocks(handle, inode, NULL, newblock,
4316 EXT4_C2B(sbi, allocated_clusters),
4317 fb_flags);
4318 }
4319 goto out;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004320 }
4321
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004322 /*
David Brazdil0f672f62019-12-10 10:32:29 +00004323 * Reduce the reserved cluster count to reflect successful deferred
4324 * allocation of delayed allocated clusters or direct allocation of
4325 * clusters discovered to be delayed allocated. Once allocated, a
4326 * cluster is not included in the reserved count.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004327 */
Olivier Deprez157378f2022-04-04 15:47:50 +02004328 if (test_opt(inode->i_sb, DELALLOC) && allocated_clusters) {
David Brazdil0f672f62019-12-10 10:32:29 +00004329 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004330 /*
David Brazdil0f672f62019-12-10 10:32:29 +00004331 * When allocating delayed allocated clusters, simply
4332 * reduce the reserved cluster count and claim quota
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004333 */
4334 ext4_da_update_reserve_space(inode, allocated_clusters,
4335 1);
David Brazdil0f672f62019-12-10 10:32:29 +00004336 } else {
4337 ext4_lblk_t lblk, len;
4338 unsigned int n;
4339
4340 /*
4341 * When allocating non-delayed allocated clusters
4342 * (from fallocate, filemap, DIO, or clusters
4343 * allocated when delalloc has been disabled by
4344 * ext4_nonda_switch), reduce the reserved cluster
4345 * count by the number of allocated clusters that
4346 * have previously been delayed allocated. Quota
4347 * has been claimed by ext4_mb_new_blocks() above,
4348 * so release the quota reservations made for any
4349 * previously delayed allocated clusters.
4350 */
4351 lblk = EXT4_LBLK_CMASK(sbi, map->m_lblk);
4352 len = allocated_clusters << sbi->s_cluster_bits;
4353 n = ext4_es_delayed_clu(inode, lblk, len);
4354 if (n > 0)
4355 ext4_da_update_reserve_space(inode, (int) n, 0);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004356 }
4357 }
4358
4359 /*
4360 * Cache the extent and update transaction to commit on fdatasync only
4361 * when it is _not_ an unwritten extent.
4362 */
4363 if ((flags & EXT4_GET_BLOCKS_UNWRIT_EXT) == 0)
4364 ext4_update_inode_fsync_trans(handle, inode, 1);
4365 else
4366 ext4_update_inode_fsync_trans(handle, inode, 0);
Olivier Deprez157378f2022-04-04 15:47:50 +02004367
4368 map->m_flags |= (EXT4_MAP_NEW | EXT4_MAP_MAPPED);
4369 map->m_pblk = pblk;
4370 map->m_len = ar.len;
4371 allocated = map->m_len;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004372 ext4_ext_show_leaf(inode, path);
Olivier Deprez157378f2022-04-04 15:47:50 +02004373out:
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004374 ext4_ext_drop_refs(path);
4375 kfree(path);
4376
4377 trace_ext4_ext_map_blocks_exit(inode, flags, map,
4378 err ? err : allocated);
4379 return err ? err : allocated;
4380}
4381
4382int ext4_ext_truncate(handle_t *handle, struct inode *inode)
4383{
4384 struct super_block *sb = inode->i_sb;
4385 ext4_lblk_t last_block;
4386 int err = 0;
4387
4388 /*
4389 * TODO: optimization is possible here.
4390 * Probably we need not scan at all,
4391 * because page truncation is enough.
4392 */
4393
4394 /* we have to know where to truncate from in crash case */
4395 EXT4_I(inode)->i_disksize = inode->i_size;
4396 err = ext4_mark_inode_dirty(handle, inode);
4397 if (err)
4398 return err;
4399
4400 last_block = (inode->i_size + sb->s_blocksize - 1)
4401 >> EXT4_BLOCK_SIZE_BITS(sb);
4402retry:
4403 err = ext4_es_remove_extent(inode, last_block,
4404 EXT_MAX_BLOCKS - last_block);
4405 if (err == -ENOMEM) {
4406 cond_resched();
4407 congestion_wait(BLK_RW_ASYNC, HZ/50);
4408 goto retry;
4409 }
4410 if (err)
4411 return err;
Olivier Deprez157378f2022-04-04 15:47:50 +02004412retry_remove_space:
4413 err = ext4_ext_remove_space(inode, last_block, EXT_MAX_BLOCKS - 1);
4414 if (err == -ENOMEM) {
4415 cond_resched();
4416 congestion_wait(BLK_RW_ASYNC, HZ/50);
4417 goto retry_remove_space;
4418 }
4419 return err;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004420}
4421
4422static int ext4_alloc_file_blocks(struct file *file, ext4_lblk_t offset,
4423 ext4_lblk_t len, loff_t new_size,
4424 int flags)
4425{
4426 struct inode *inode = file_inode(file);
4427 handle_t *handle;
4428 int ret = 0;
Olivier Deprez157378f2022-04-04 15:47:50 +02004429 int ret2 = 0, ret3 = 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004430 int retries = 0;
4431 int depth = 0;
4432 struct ext4_map_blocks map;
4433 unsigned int credits;
4434 loff_t epos;
4435
4436 BUG_ON(!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS));
4437 map.m_lblk = offset;
4438 map.m_len = len;
4439 /*
4440 * Don't normalize the request if it can fit in one extent so
4441 * that it doesn't get unnecessarily split into multiple
4442 * extents.
4443 */
4444 if (len <= EXT_UNWRITTEN_MAX_LEN)
4445 flags |= EXT4_GET_BLOCKS_NO_NORMALIZE;
4446
4447 /*
4448 * credits to insert 1 extent into extent tree
4449 */
4450 credits = ext4_chunk_trans_blocks(inode, len);
4451 depth = ext_depth(inode);
4452
4453retry:
4454 while (ret >= 0 && len) {
4455 /*
4456 * Recalculate credits when extent tree depth changes.
4457 */
4458 if (depth != ext_depth(inode)) {
4459 credits = ext4_chunk_trans_blocks(inode, len);
4460 depth = ext_depth(inode);
4461 }
4462
4463 handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS,
4464 credits);
4465 if (IS_ERR(handle)) {
4466 ret = PTR_ERR(handle);
4467 break;
4468 }
4469 ret = ext4_map_blocks(handle, inode, &map, flags);
4470 if (ret <= 0) {
4471 ext4_debug("inode #%lu: block %u: len %u: "
4472 "ext4_ext_map_blocks returned %d",
4473 inode->i_ino, map.m_lblk,
4474 map.m_len, ret);
4475 ext4_mark_inode_dirty(handle, inode);
4476 ret2 = ext4_journal_stop(handle);
4477 break;
4478 }
4479 map.m_lblk += ret;
4480 map.m_len = len = len - ret;
4481 epos = (loff_t)map.m_lblk << inode->i_blkbits;
4482 inode->i_ctime = current_time(inode);
4483 if (new_size) {
4484 if (epos > new_size)
4485 epos = new_size;
4486 if (ext4_update_inode_size(inode, epos) & 0x1)
4487 inode->i_mtime = inode->i_ctime;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004488 }
Olivier Deprez157378f2022-04-04 15:47:50 +02004489 ret2 = ext4_mark_inode_dirty(handle, inode);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004490 ext4_update_inode_fsync_trans(handle, inode, 1);
Olivier Deprez157378f2022-04-04 15:47:50 +02004491 ret3 = ext4_journal_stop(handle);
4492 ret2 = ret3 ? ret3 : ret2;
4493 if (unlikely(ret2))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004494 break;
4495 }
4496 if (ret == -ENOSPC &&
4497 ext4_should_retry_alloc(inode->i_sb, &retries)) {
4498 ret = 0;
4499 goto retry;
4500 }
4501
4502 return ret > 0 ? ret2 : ret;
4503}
4504
Olivier Deprez92d4c212022-12-06 15:05:30 +01004505static int ext4_collapse_range(struct file *file, loff_t offset, loff_t len);
Olivier Deprez157378f2022-04-04 15:47:50 +02004506
Olivier Deprez92d4c212022-12-06 15:05:30 +01004507static int ext4_insert_range(struct file *file, loff_t offset, loff_t len);
Olivier Deprez157378f2022-04-04 15:47:50 +02004508
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004509static long ext4_zero_range(struct file *file, loff_t offset,
4510 loff_t len, int mode)
4511{
4512 struct inode *inode = file_inode(file);
4513 handle_t *handle = NULL;
4514 unsigned int max_blocks;
4515 loff_t new_size = 0;
4516 int ret = 0;
4517 int flags;
4518 int credits;
4519 int partial_begin, partial_end;
4520 loff_t start, end;
4521 ext4_lblk_t lblk;
4522 unsigned int blkbits = inode->i_blkbits;
4523
4524 trace_ext4_zero_range(inode, offset, len, mode);
4525
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004526 /* Call ext4_force_commit to flush all data in case of data=journal. */
4527 if (ext4_should_journal_data(inode)) {
4528 ret = ext4_force_commit(inode->i_sb);
4529 if (ret)
4530 return ret;
4531 }
4532
4533 /*
Olivier Deprez157378f2022-04-04 15:47:50 +02004534 * Round up offset. This is not fallocate, we need to zero out
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004535 * blocks, so convert interior block aligned part of the range to
4536 * unwritten and possibly manually zero out unaligned parts of the
4537 * range.
4538 */
4539 start = round_up(offset, 1 << blkbits);
4540 end = round_down((offset + len), 1 << blkbits);
4541
4542 if (start < offset || end > offset + len)
4543 return -EINVAL;
4544 partial_begin = offset & ((1 << blkbits) - 1);
4545 partial_end = (offset + len) & ((1 << blkbits) - 1);
4546
4547 lblk = start >> blkbits;
4548 max_blocks = (end >> blkbits);
4549 if (max_blocks < lblk)
4550 max_blocks = 0;
4551 else
4552 max_blocks -= lblk;
4553
4554 inode_lock(inode);
4555
4556 /*
Olivier Deprez157378f2022-04-04 15:47:50 +02004557 * Indirect files do not support unwritten extents
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004558 */
4559 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
4560 ret = -EOPNOTSUPP;
4561 goto out_mutex;
4562 }
4563
4564 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
Olivier Deprez157378f2022-04-04 15:47:50 +02004565 (offset + len > inode->i_size ||
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004566 offset + len > EXT4_I(inode)->i_disksize)) {
4567 new_size = offset + len;
4568 ret = inode_newsize_ok(inode, new_size);
4569 if (ret)
4570 goto out_mutex;
4571 }
4572
4573 flags = EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004574
4575 /* Wait all existing dio workers, newcomers will block on i_mutex */
4576 inode_dio_wait(inode);
4577
Olivier Deprez92d4c212022-12-06 15:05:30 +01004578 ret = file_modified(file);
4579 if (ret)
4580 goto out_mutex;
4581
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004582 /* Preallocate the range including the unaligned edges */
4583 if (partial_begin || partial_end) {
4584 ret = ext4_alloc_file_blocks(file,
4585 round_down(offset, 1 << blkbits) >> blkbits,
4586 (round_up((offset + len), 1 << blkbits) -
4587 round_down(offset, 1 << blkbits)) >> blkbits,
4588 new_size, flags);
4589 if (ret)
4590 goto out_mutex;
4591
4592 }
4593
4594 /* Zero range excluding the unaligned edges */
4595 if (max_blocks > 0) {
4596 flags |= (EXT4_GET_BLOCKS_CONVERT_UNWRITTEN |
4597 EXT4_EX_NOCACHE);
4598
4599 /*
4600 * Prevent page faults from reinstantiating pages we have
4601 * released from page cache.
4602 */
4603 down_write(&EXT4_I(inode)->i_mmap_sem);
4604
4605 ret = ext4_break_layouts(inode);
4606 if (ret) {
4607 up_write(&EXT4_I(inode)->i_mmap_sem);
4608 goto out_mutex;
4609 }
4610
4611 ret = ext4_update_disksize_before_punch(inode, offset, len);
4612 if (ret) {
4613 up_write(&EXT4_I(inode)->i_mmap_sem);
4614 goto out_mutex;
4615 }
4616 /* Now release the pages and zero block aligned part of pages */
4617 truncate_pagecache_range(inode, start, end - 1);
4618 inode->i_mtime = inode->i_ctime = current_time(inode);
4619
4620 ret = ext4_alloc_file_blocks(file, lblk, max_blocks, new_size,
4621 flags);
4622 up_write(&EXT4_I(inode)->i_mmap_sem);
4623 if (ret)
4624 goto out_mutex;
4625 }
4626 if (!partial_begin && !partial_end)
4627 goto out_mutex;
4628
4629 /*
4630 * In worst case we have to writeout two nonadjacent unwritten
4631 * blocks and update the inode
4632 */
4633 credits = (2 * ext4_ext_index_trans_blocks(inode, 2)) + 1;
4634 if (ext4_should_journal_data(inode))
4635 credits += 2;
4636 handle = ext4_journal_start(inode, EXT4_HT_MISC, credits);
4637 if (IS_ERR(handle)) {
4638 ret = PTR_ERR(handle);
4639 ext4_std_error(inode->i_sb, ret);
4640 goto out_mutex;
4641 }
4642
4643 inode->i_mtime = inode->i_ctime = current_time(inode);
Olivier Deprez157378f2022-04-04 15:47:50 +02004644 if (new_size)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004645 ext4_update_inode_size(inode, new_size);
Olivier Deprez157378f2022-04-04 15:47:50 +02004646 ret = ext4_mark_inode_dirty(handle, inode);
4647 if (unlikely(ret))
4648 goto out_handle;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004649 /* Zero out partial block at the edges of the range */
4650 ret = ext4_zero_partial_blocks(handle, inode, offset, len);
4651 if (ret >= 0)
4652 ext4_update_inode_fsync_trans(handle, inode, 1);
4653
4654 if (file->f_flags & O_SYNC)
4655 ext4_handle_sync(handle);
4656
Olivier Deprez157378f2022-04-04 15:47:50 +02004657out_handle:
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004658 ext4_journal_stop(handle);
4659out_mutex:
4660 inode_unlock(inode);
4661 return ret;
4662}
4663
4664/*
4665 * preallocate space for a file. This implements ext4's fallocate file
4666 * operation, which gets called from sys_fallocate system call.
4667 * For block-mapped files, posix_fallocate should fall back to the method
4668 * of writing zeroes to the required new blocks (the same behavior which is
4669 * expected for file systems which do not support fallocate() system call).
4670 */
4671long ext4_fallocate(struct file *file, int mode, loff_t offset, loff_t len)
4672{
4673 struct inode *inode = file_inode(file);
4674 loff_t new_size = 0;
4675 unsigned int max_blocks;
4676 int ret = 0;
4677 int flags;
4678 ext4_lblk_t lblk;
4679 unsigned int blkbits = inode->i_blkbits;
4680
4681 /*
4682 * Encrypted inodes can't handle collapse range or insert
4683 * range since we would need to re-encrypt blocks with a
4684 * different IV or XTS tweak (which are based on the logical
4685 * block number).
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004686 */
David Brazdil0f672f62019-12-10 10:32:29 +00004687 if (IS_ENCRYPTED(inode) &&
Olivier Deprez157378f2022-04-04 15:47:50 +02004688 (mode & (FALLOC_FL_COLLAPSE_RANGE | FALLOC_FL_INSERT_RANGE)))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004689 return -EOPNOTSUPP;
4690
4691 /* Return error if mode is not supported */
4692 if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE |
4693 FALLOC_FL_COLLAPSE_RANGE | FALLOC_FL_ZERO_RANGE |
4694 FALLOC_FL_INSERT_RANGE))
4695 return -EOPNOTSUPP;
4696
Olivier Deprez157378f2022-04-04 15:47:50 +02004697 ext4_fc_start_update(inode);
Olivier Deprez92d4c212022-12-06 15:05:30 +01004698 inode_lock(inode);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004699 ret = ext4_convert_inline_data(inode);
Olivier Deprez92d4c212022-12-06 15:05:30 +01004700 inode_unlock(inode);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004701 if (ret)
Olivier Deprez157378f2022-04-04 15:47:50 +02004702 goto exit;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004703
Olivier Deprez92d4c212022-12-06 15:05:30 +01004704 if (mode & FALLOC_FL_PUNCH_HOLE) {
4705 ret = ext4_punch_hole(file, offset, len);
4706 goto exit;
4707 }
4708
Olivier Deprez157378f2022-04-04 15:47:50 +02004709 if (mode & FALLOC_FL_COLLAPSE_RANGE) {
Olivier Deprez92d4c212022-12-06 15:05:30 +01004710 ret = ext4_collapse_range(file, offset, len);
Olivier Deprez157378f2022-04-04 15:47:50 +02004711 goto exit;
4712 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004713
Olivier Deprez157378f2022-04-04 15:47:50 +02004714 if (mode & FALLOC_FL_INSERT_RANGE) {
Olivier Deprez92d4c212022-12-06 15:05:30 +01004715 ret = ext4_insert_range(file, offset, len);
Olivier Deprez157378f2022-04-04 15:47:50 +02004716 goto exit;
4717 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004718
Olivier Deprez157378f2022-04-04 15:47:50 +02004719 if (mode & FALLOC_FL_ZERO_RANGE) {
4720 ret = ext4_zero_range(file, offset, len, mode);
4721 goto exit;
4722 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004723 trace_ext4_fallocate_enter(inode, offset, len, mode);
4724 lblk = offset >> blkbits;
4725
4726 max_blocks = EXT4_MAX_BLOCKS(len, offset, blkbits);
4727 flags = EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004728
4729 inode_lock(inode);
4730
4731 /*
4732 * We only support preallocation for extent-based files only
4733 */
4734 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
4735 ret = -EOPNOTSUPP;
4736 goto out;
4737 }
4738
4739 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
Olivier Deprez157378f2022-04-04 15:47:50 +02004740 (offset + len > inode->i_size ||
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004741 offset + len > EXT4_I(inode)->i_disksize)) {
4742 new_size = offset + len;
4743 ret = inode_newsize_ok(inode, new_size);
4744 if (ret)
4745 goto out;
4746 }
4747
4748 /* Wait all existing dio workers, newcomers will block on i_mutex */
4749 inode_dio_wait(inode);
4750
Olivier Deprez92d4c212022-12-06 15:05:30 +01004751 ret = file_modified(file);
4752 if (ret)
4753 goto out;
4754
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004755 ret = ext4_alloc_file_blocks(file, lblk, max_blocks, new_size, flags);
4756 if (ret)
4757 goto out;
4758
4759 if (file->f_flags & O_SYNC && EXT4_SB(inode->i_sb)->s_journal) {
Olivier Deprez157378f2022-04-04 15:47:50 +02004760 ret = ext4_fc_commit(EXT4_SB(inode->i_sb)->s_journal,
4761 EXT4_I(inode)->i_sync_tid);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004762 }
4763out:
4764 inode_unlock(inode);
4765 trace_ext4_fallocate_exit(inode, offset, max_blocks, ret);
Olivier Deprez157378f2022-04-04 15:47:50 +02004766exit:
4767 ext4_fc_stop_update(inode);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004768 return ret;
4769}
4770
4771/*
4772 * This function convert a range of blocks to written extents
4773 * The caller of this function will pass the start offset and the size.
4774 * all unwritten extents within this range will be converted to
4775 * written extents.
4776 *
4777 * This function is called from the direct IO end io call back
4778 * function, to convert the fallocated extents after IO is completed.
4779 * Returns 0 on success.
4780 */
4781int ext4_convert_unwritten_extents(handle_t *handle, struct inode *inode,
4782 loff_t offset, ssize_t len)
4783{
4784 unsigned int max_blocks;
Olivier Deprez157378f2022-04-04 15:47:50 +02004785 int ret = 0, ret2 = 0, ret3 = 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004786 struct ext4_map_blocks map;
Olivier Deprez157378f2022-04-04 15:47:50 +02004787 unsigned int blkbits = inode->i_blkbits;
4788 unsigned int credits = 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004789
4790 map.m_lblk = offset >> blkbits;
4791 max_blocks = EXT4_MAX_BLOCKS(len, offset, blkbits);
4792
Olivier Deprez157378f2022-04-04 15:47:50 +02004793 if (!handle) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004794 /*
4795 * credits to insert 1 extent into extent tree
4796 */
4797 credits = ext4_chunk_trans_blocks(inode, max_blocks);
4798 }
4799 while (ret >= 0 && ret < max_blocks) {
4800 map.m_lblk += ret;
4801 map.m_len = (max_blocks -= ret);
4802 if (credits) {
4803 handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS,
4804 credits);
4805 if (IS_ERR(handle)) {
4806 ret = PTR_ERR(handle);
4807 break;
4808 }
4809 }
4810 ret = ext4_map_blocks(handle, inode, &map,
4811 EXT4_GET_BLOCKS_IO_CONVERT_EXT);
4812 if (ret <= 0)
4813 ext4_warning(inode->i_sb,
4814 "inode #%lu: block %u: len %u: "
4815 "ext4_ext_map_blocks returned %d",
4816 inode->i_ino, map.m_lblk,
4817 map.m_len, ret);
Olivier Deprez157378f2022-04-04 15:47:50 +02004818 ret2 = ext4_mark_inode_dirty(handle, inode);
4819 if (credits) {
4820 ret3 = ext4_journal_stop(handle);
4821 if (unlikely(ret3))
4822 ret2 = ret3;
4823 }
4824
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004825 if (ret <= 0 || ret2)
4826 break;
4827 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004828 return ret > 0 ? ret2 : ret;
4829}
4830
Olivier Deprez157378f2022-04-04 15:47:50 +02004831int ext4_convert_unwritten_io_end_vec(handle_t *handle, ext4_io_end_t *io_end)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004832{
Olivier Deprez157378f2022-04-04 15:47:50 +02004833 int ret = 0, err = 0;
4834 struct ext4_io_end_vec *io_end_vec;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004835
Olivier Deprez157378f2022-04-04 15:47:50 +02004836 /*
4837 * This is somewhat ugly but the idea is clear: When transaction is
4838 * reserved, everything goes into it. Otherwise we rather start several
4839 * smaller transactions for conversion of each extent separately.
4840 */
4841 if (handle) {
4842 handle = ext4_journal_start_reserved(handle,
4843 EXT4_HT_EXT_CONVERT);
4844 if (IS_ERR(handle))
4845 return PTR_ERR(handle);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004846 }
4847
Olivier Deprez157378f2022-04-04 15:47:50 +02004848 list_for_each_entry(io_end_vec, &io_end->list_vec, list) {
4849 ret = ext4_convert_unwritten_extents(handle, io_end->inode,
4850 io_end_vec->offset,
4851 io_end_vec->size);
4852 if (ret)
4853 break;
4854 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004855
Olivier Deprez157378f2022-04-04 15:47:50 +02004856 if (handle)
4857 err = ext4_journal_stop(handle);
4858
4859 return ret < 0 ? ret : err;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004860}
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004861
Olivier Deprez157378f2022-04-04 15:47:50 +02004862static int ext4_iomap_xattr_fiemap(struct inode *inode, struct iomap *iomap)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004863{
4864 __u64 physical = 0;
Olivier Deprez157378f2022-04-04 15:47:50 +02004865 __u64 length = 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004866 int blockbits = inode->i_sb->s_blocksize_bits;
4867 int error = 0;
Olivier Deprez157378f2022-04-04 15:47:50 +02004868 u16 iomap_type;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004869
4870 /* in-inode? */
4871 if (ext4_test_inode_state(inode, EXT4_STATE_XATTR)) {
4872 struct ext4_iloc iloc;
4873 int offset; /* offset of xattr in inode */
4874
4875 error = ext4_get_inode_loc(inode, &iloc);
4876 if (error)
4877 return error;
4878 physical = (__u64)iloc.bh->b_blocknr << blockbits;
4879 offset = EXT4_GOOD_OLD_INODE_SIZE +
4880 EXT4_I(inode)->i_extra_isize;
4881 physical += offset;
4882 length = EXT4_SB(inode->i_sb)->s_inode_size - offset;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004883 brelse(iloc.bh);
Olivier Deprez157378f2022-04-04 15:47:50 +02004884 iomap_type = IOMAP_INLINE;
4885 } else if (EXT4_I(inode)->i_file_acl) { /* external block */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004886 physical = (__u64)EXT4_I(inode)->i_file_acl << blockbits;
4887 length = inode->i_sb->s_blocksize;
Olivier Deprez157378f2022-04-04 15:47:50 +02004888 iomap_type = IOMAP_MAPPED;
4889 } else {
4890 /* no in-inode or external block for xattr, so return -ENOENT */
4891 error = -ENOENT;
4892 goto out;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004893 }
4894
Olivier Deprez157378f2022-04-04 15:47:50 +02004895 iomap->addr = physical;
4896 iomap->offset = 0;
4897 iomap->length = length;
4898 iomap->type = iomap_type;
4899 iomap->flags = 0;
4900out:
4901 return error;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004902}
4903
Olivier Deprez157378f2022-04-04 15:47:50 +02004904static int ext4_iomap_xattr_begin(struct inode *inode, loff_t offset,
4905 loff_t length, unsigned flags,
4906 struct iomap *iomap, struct iomap *srcmap)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004907{
Olivier Deprez157378f2022-04-04 15:47:50 +02004908 int error;
David Brazdil0f672f62019-12-10 10:32:29 +00004909
Olivier Deprez157378f2022-04-04 15:47:50 +02004910 error = ext4_iomap_xattr_fiemap(inode, iomap);
4911 if (error == 0 && (offset >= iomap->length))
4912 error = -ENOENT;
4913 return error;
4914}
4915
4916static const struct iomap_ops ext4_iomap_xattr_ops = {
4917 .iomap_begin = ext4_iomap_xattr_begin,
4918};
4919
4920static int ext4_fiemap_check_ranges(struct inode *inode, u64 start, u64 *len)
4921{
4922 u64 maxbytes;
4923
4924 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4925 maxbytes = inode->i_sb->s_maxbytes;
4926 else
4927 maxbytes = EXT4_SB(inode->i_sb)->s_bitmap_maxbytes;
4928
4929 if (*len == 0)
4930 return -EINVAL;
4931 if (start > maxbytes)
4932 return -EFBIG;
4933
4934 /*
4935 * Shrink request scope to what the fs can actually handle.
4936 */
4937 if (*len > maxbytes || (maxbytes - *len) < start)
4938 *len = maxbytes - start;
4939 return 0;
4940}
4941
4942int ext4_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
4943 u64 start, u64 len)
4944{
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004945 int error = 0;
4946
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004947 if (fieinfo->fi_flags & FIEMAP_FLAG_CACHE) {
4948 error = ext4_ext_precache(inode);
4949 if (error)
4950 return error;
David Brazdil0f672f62019-12-10 10:32:29 +00004951 fieinfo->fi_flags &= ~FIEMAP_FLAG_CACHE;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004952 }
4953
Olivier Deprez157378f2022-04-04 15:47:50 +02004954 /*
4955 * For bitmap files the maximum size limit could be smaller than
4956 * s_maxbytes, so check len here manually instead of just relying on the
4957 * generic check.
4958 */
4959 error = ext4_fiemap_check_ranges(inode, start, &len);
4960 if (error)
4961 return error;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004962
4963 if (fieinfo->fi_flags & FIEMAP_FLAG_XATTR) {
Olivier Deprez157378f2022-04-04 15:47:50 +02004964 fieinfo->fi_flags &= ~FIEMAP_FLAG_XATTR;
4965 return iomap_fiemap(inode, fieinfo, start, len,
4966 &ext4_iomap_xattr_ops);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004967 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004968
Olivier Deprez157378f2022-04-04 15:47:50 +02004969 return iomap_fiemap(inode, fieinfo, start, len, &ext4_iomap_report_ops);
David Brazdil0f672f62019-12-10 10:32:29 +00004970}
4971
4972int ext4_get_es_cache(struct inode *inode, struct fiemap_extent_info *fieinfo,
4973 __u64 start, __u64 len)
4974{
Olivier Deprez157378f2022-04-04 15:47:50 +02004975 ext4_lblk_t start_blk, len_blks;
4976 __u64 last_blk;
4977 int error = 0;
4978
David Brazdil0f672f62019-12-10 10:32:29 +00004979 if (ext4_has_inline_data(inode)) {
4980 int has_inline;
4981
4982 down_read(&EXT4_I(inode)->xattr_sem);
4983 has_inline = ext4_has_inline_data(inode);
4984 up_read(&EXT4_I(inode)->xattr_sem);
4985 if (has_inline)
4986 return 0;
4987 }
4988
Olivier Deprez157378f2022-04-04 15:47:50 +02004989 if (fieinfo->fi_flags & FIEMAP_FLAG_CACHE) {
4990 error = ext4_ext_precache(inode);
4991 if (error)
4992 return error;
4993 fieinfo->fi_flags &= ~FIEMAP_FLAG_CACHE;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004994 }
4995
Olivier Deprez157378f2022-04-04 15:47:50 +02004996 error = fiemap_prep(inode, fieinfo, start, &len, 0);
4997 if (error)
4998 return error;
4999
5000 error = ext4_fiemap_check_ranges(inode, start, &len);
5001 if (error)
5002 return error;
5003
5004 start_blk = start >> inode->i_sb->s_blocksize_bits;
5005 last_blk = (start + len - 1) >> inode->i_sb->s_blocksize_bits;
5006 if (last_blk >= EXT_MAX_BLOCKS)
5007 last_blk = EXT_MAX_BLOCKS-1;
5008 len_blks = ((ext4_lblk_t) last_blk) - start_blk + 1;
5009
5010 /*
5011 * Walk the extent tree gathering extent information
5012 * and pushing extents back to the user.
5013 */
5014 return ext4_fill_es_cache_info(inode, start_blk, len_blks, fieinfo);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005015}
5016
5017/*
5018 * ext4_ext_shift_path_extents:
5019 * Shift the extents of a path structure lying between path[depth].p_ext
5020 * and EXT_LAST_EXTENT(path[depth].p_hdr), by @shift blocks. @SHIFT tells
5021 * if it is right shift or left shift operation.
5022 */
5023static int
5024ext4_ext_shift_path_extents(struct ext4_ext_path *path, ext4_lblk_t shift,
5025 struct inode *inode, handle_t *handle,
5026 enum SHIFT_DIRECTION SHIFT)
5027{
5028 int depth, err = 0;
5029 struct ext4_extent *ex_start, *ex_last;
Olivier Deprez157378f2022-04-04 15:47:50 +02005030 bool update = false;
5031 int credits, restart_credits;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005032 depth = path->p_depth;
5033
5034 while (depth >= 0) {
5035 if (depth == path->p_depth) {
5036 ex_start = path[depth].p_ext;
5037 if (!ex_start)
5038 return -EFSCORRUPTED;
5039
5040 ex_last = EXT_LAST_EXTENT(path[depth].p_hdr);
Olivier Deprez157378f2022-04-04 15:47:50 +02005041 /* leaf + sb + inode */
5042 credits = 3;
5043 if (ex_start == EXT_FIRST_EXTENT(path[depth].p_hdr)) {
5044 update = true;
5045 /* extent tree + sb + inode */
5046 credits = depth + 2;
5047 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005048
Olivier Deprez157378f2022-04-04 15:47:50 +02005049 restart_credits = ext4_writepage_trans_blocks(inode);
5050 err = ext4_datasem_ensure_credits(handle, inode, credits,
5051 restart_credits, 0);
5052 if (err) {
5053 if (err > 0)
5054 err = -EAGAIN;
5055 goto out;
5056 }
5057
5058 err = ext4_ext_get_access(handle, inode, path + depth);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005059 if (err)
5060 goto out;
5061
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005062 while (ex_start <= ex_last) {
5063 if (SHIFT == SHIFT_LEFT) {
5064 le32_add_cpu(&ex_start->ee_block,
5065 -shift);
5066 /* Try to merge to the left. */
5067 if ((ex_start >
5068 EXT_FIRST_EXTENT(path[depth].p_hdr))
5069 &&
5070 ext4_ext_try_to_merge_right(inode,
5071 path, ex_start - 1))
5072 ex_last--;
5073 else
5074 ex_start++;
5075 } else {
5076 le32_add_cpu(&ex_last->ee_block, shift);
5077 ext4_ext_try_to_merge_right(inode, path,
5078 ex_last);
5079 ex_last--;
5080 }
5081 }
5082 err = ext4_ext_dirty(handle, inode, path + depth);
5083 if (err)
5084 goto out;
5085
5086 if (--depth < 0 || !update)
5087 break;
5088 }
5089
5090 /* Update index too */
Olivier Deprez157378f2022-04-04 15:47:50 +02005091 err = ext4_ext_get_access(handle, inode, path + depth);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005092 if (err)
5093 goto out;
5094
5095 if (SHIFT == SHIFT_LEFT)
5096 le32_add_cpu(&path[depth].p_idx->ei_block, -shift);
5097 else
5098 le32_add_cpu(&path[depth].p_idx->ei_block, shift);
5099 err = ext4_ext_dirty(handle, inode, path + depth);
5100 if (err)
5101 goto out;
5102
5103 /* we are done if current index is not a starting index */
5104 if (path[depth].p_idx != EXT_FIRST_INDEX(path[depth].p_hdr))
5105 break;
5106
5107 depth--;
5108 }
5109
5110out:
5111 return err;
5112}
5113
5114/*
5115 * ext4_ext_shift_extents:
5116 * All the extents which lies in the range from @start to the last allocated
5117 * block for the @inode are shifted either towards left or right (depending
5118 * upon @SHIFT) by @shift blocks.
5119 * On success, 0 is returned, error otherwise.
5120 */
5121static int
5122ext4_ext_shift_extents(struct inode *inode, handle_t *handle,
5123 ext4_lblk_t start, ext4_lblk_t shift,
5124 enum SHIFT_DIRECTION SHIFT)
5125{
5126 struct ext4_ext_path *path;
5127 int ret = 0, depth;
5128 struct ext4_extent *extent;
5129 ext4_lblk_t stop, *iterator, ex_start, ex_end;
Olivier Deprez157378f2022-04-04 15:47:50 +02005130 ext4_lblk_t tmp = EXT_MAX_BLOCKS;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005131
5132 /* Let path point to the last extent */
5133 path = ext4_find_extent(inode, EXT_MAX_BLOCKS - 1, NULL,
5134 EXT4_EX_NOCACHE);
5135 if (IS_ERR(path))
5136 return PTR_ERR(path);
5137
5138 depth = path->p_depth;
5139 extent = path[depth].p_ext;
5140 if (!extent)
5141 goto out;
5142
5143 stop = le32_to_cpu(extent->ee_block);
5144
5145 /*
5146 * For left shifts, make sure the hole on the left is big enough to
5147 * accommodate the shift. For right shifts, make sure the last extent
5148 * won't be shifted beyond EXT_MAX_BLOCKS.
5149 */
5150 if (SHIFT == SHIFT_LEFT) {
5151 path = ext4_find_extent(inode, start - 1, &path,
5152 EXT4_EX_NOCACHE);
5153 if (IS_ERR(path))
5154 return PTR_ERR(path);
5155 depth = path->p_depth;
5156 extent = path[depth].p_ext;
5157 if (extent) {
5158 ex_start = le32_to_cpu(extent->ee_block);
5159 ex_end = le32_to_cpu(extent->ee_block) +
5160 ext4_ext_get_actual_len(extent);
5161 } else {
5162 ex_start = 0;
5163 ex_end = 0;
5164 }
5165
5166 if ((start == ex_start && shift > ex_start) ||
5167 (shift > start - ex_end)) {
5168 ret = -EINVAL;
5169 goto out;
5170 }
5171 } else {
5172 if (shift > EXT_MAX_BLOCKS -
5173 (stop + ext4_ext_get_actual_len(extent))) {
5174 ret = -EINVAL;
5175 goto out;
5176 }
5177 }
5178
5179 /*
5180 * In case of left shift, iterator points to start and it is increased
5181 * till we reach stop. In case of right shift, iterator points to stop
5182 * and it is decreased till we reach start.
5183 */
Olivier Deprez157378f2022-04-04 15:47:50 +02005184again:
Olivier Deprez92d4c212022-12-06 15:05:30 +01005185 ret = 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005186 if (SHIFT == SHIFT_LEFT)
5187 iterator = &start;
5188 else
5189 iterator = &stop;
5190
Olivier Deprez157378f2022-04-04 15:47:50 +02005191 if (tmp != EXT_MAX_BLOCKS)
5192 *iterator = tmp;
5193
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005194 /*
5195 * Its safe to start updating extents. Start and stop are unsigned, so
5196 * in case of right shift if extent with 0 block is reached, iterator
5197 * becomes NULL to indicate the end of the loop.
5198 */
5199 while (iterator && start <= stop) {
5200 path = ext4_find_extent(inode, *iterator, &path,
5201 EXT4_EX_NOCACHE);
5202 if (IS_ERR(path))
5203 return PTR_ERR(path);
5204 depth = path->p_depth;
5205 extent = path[depth].p_ext;
5206 if (!extent) {
5207 EXT4_ERROR_INODE(inode, "unexpected hole at %lu",
5208 (unsigned long) *iterator);
5209 return -EFSCORRUPTED;
5210 }
5211 if (SHIFT == SHIFT_LEFT && *iterator >
5212 le32_to_cpu(extent->ee_block)) {
5213 /* Hole, move to the next extent */
5214 if (extent < EXT_LAST_EXTENT(path[depth].p_hdr)) {
5215 path[depth].p_ext++;
5216 } else {
5217 *iterator = ext4_ext_next_allocated_block(path);
5218 continue;
5219 }
5220 }
5221
Olivier Deprez157378f2022-04-04 15:47:50 +02005222 tmp = *iterator;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005223 if (SHIFT == SHIFT_LEFT) {
5224 extent = EXT_LAST_EXTENT(path[depth].p_hdr);
5225 *iterator = le32_to_cpu(extent->ee_block) +
5226 ext4_ext_get_actual_len(extent);
5227 } else {
5228 extent = EXT_FIRST_EXTENT(path[depth].p_hdr);
Olivier Deprez92d4c212022-12-06 15:05:30 +01005229 if (le32_to_cpu(extent->ee_block) > start)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005230 *iterator = le32_to_cpu(extent->ee_block) - 1;
Olivier Deprez92d4c212022-12-06 15:05:30 +01005231 else if (le32_to_cpu(extent->ee_block) == start)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005232 iterator = NULL;
Olivier Deprez92d4c212022-12-06 15:05:30 +01005233 else {
5234 extent = EXT_LAST_EXTENT(path[depth].p_hdr);
5235 while (le32_to_cpu(extent->ee_block) >= start)
5236 extent--;
5237
5238 if (extent == EXT_LAST_EXTENT(path[depth].p_hdr))
5239 break;
5240
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005241 extent++;
Olivier Deprez92d4c212022-12-06 15:05:30 +01005242 iterator = NULL;
5243 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005244 path[depth].p_ext = extent;
5245 }
5246 ret = ext4_ext_shift_path_extents(path, shift, inode,
5247 handle, SHIFT);
Olivier Deprez157378f2022-04-04 15:47:50 +02005248 /* iterator can be NULL which means we should break */
5249 if (ret == -EAGAIN)
5250 goto again;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005251 if (ret)
5252 break;
5253 }
5254out:
5255 ext4_ext_drop_refs(path);
5256 kfree(path);
5257 return ret;
5258}
5259
5260/*
5261 * ext4_collapse_range:
5262 * This implements the fallocate's collapse range functionality for ext4
5263 * Returns: 0 and non-zero on error.
5264 */
Olivier Deprez92d4c212022-12-06 15:05:30 +01005265static int ext4_collapse_range(struct file *file, loff_t offset, loff_t len)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005266{
Olivier Deprez92d4c212022-12-06 15:05:30 +01005267 struct inode *inode = file_inode(file);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005268 struct super_block *sb = inode->i_sb;
5269 ext4_lblk_t punch_start, punch_stop;
5270 handle_t *handle;
5271 unsigned int credits;
5272 loff_t new_size, ioffset;
5273 int ret;
5274
5275 /*
5276 * We need to test this early because xfstests assumes that a
5277 * collapse range of (0, 1) will return EOPNOTSUPP if the file
5278 * system does not support collapse range.
5279 */
5280 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
5281 return -EOPNOTSUPP;
5282
Olivier Deprez157378f2022-04-04 15:47:50 +02005283 /* Collapse range works only on fs cluster size aligned regions. */
5284 if (!IS_ALIGNED(offset | len, EXT4_CLUSTER_SIZE(sb)))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005285 return -EINVAL;
5286
5287 trace_ext4_collapse_range(inode, offset, len);
5288
5289 punch_start = offset >> EXT4_BLOCK_SIZE_BITS(sb);
5290 punch_stop = (offset + len) >> EXT4_BLOCK_SIZE_BITS(sb);
5291
5292 /* Call ext4_force_commit to flush all data in case of data=journal. */
5293 if (ext4_should_journal_data(inode)) {
5294 ret = ext4_force_commit(inode->i_sb);
5295 if (ret)
5296 return ret;
5297 }
5298
5299 inode_lock(inode);
5300 /*
5301 * There is no need to overlap collapse range with EOF, in which case
5302 * it is effectively a truncate operation
5303 */
Olivier Deprez157378f2022-04-04 15:47:50 +02005304 if (offset + len >= inode->i_size) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005305 ret = -EINVAL;
5306 goto out_mutex;
5307 }
5308
5309 /* Currently just for extent based files */
5310 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
5311 ret = -EOPNOTSUPP;
5312 goto out_mutex;
5313 }
5314
5315 /* Wait for existing dio to complete */
5316 inode_dio_wait(inode);
5317
Olivier Deprez92d4c212022-12-06 15:05:30 +01005318 ret = file_modified(file);
5319 if (ret)
5320 goto out_mutex;
5321
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005322 /*
5323 * Prevent page faults from reinstantiating pages we have released from
5324 * page cache.
5325 */
5326 down_write(&EXT4_I(inode)->i_mmap_sem);
5327
5328 ret = ext4_break_layouts(inode);
5329 if (ret)
5330 goto out_mmap;
5331
5332 /*
5333 * Need to round down offset to be aligned with page size boundary
5334 * for page size > block size.
5335 */
5336 ioffset = round_down(offset, PAGE_SIZE);
5337 /*
5338 * Write tail of the last page before removed range since it will get
5339 * removed from the page cache below.
5340 */
5341 ret = filemap_write_and_wait_range(inode->i_mapping, ioffset, offset);
5342 if (ret)
5343 goto out_mmap;
5344 /*
5345 * Write data that will be shifted to preserve them when discarding
5346 * page cache below. We are also protected from pages becoming dirty
5347 * by i_mmap_sem.
5348 */
5349 ret = filemap_write_and_wait_range(inode->i_mapping, offset + len,
5350 LLONG_MAX);
5351 if (ret)
5352 goto out_mmap;
5353 truncate_pagecache(inode, ioffset);
5354
5355 credits = ext4_writepage_trans_blocks(inode);
5356 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
5357 if (IS_ERR(handle)) {
5358 ret = PTR_ERR(handle);
5359 goto out_mmap;
5360 }
Olivier Deprez157378f2022-04-04 15:47:50 +02005361 ext4_fc_start_ineligible(sb, EXT4_FC_REASON_FALLOC_RANGE);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005362
5363 down_write(&EXT4_I(inode)->i_data_sem);
Olivier Deprez157378f2022-04-04 15:47:50 +02005364 ext4_discard_preallocations(inode, 0);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005365
5366 ret = ext4_es_remove_extent(inode, punch_start,
5367 EXT_MAX_BLOCKS - punch_start);
5368 if (ret) {
5369 up_write(&EXT4_I(inode)->i_data_sem);
5370 goto out_stop;
5371 }
5372
5373 ret = ext4_ext_remove_space(inode, punch_start, punch_stop - 1);
5374 if (ret) {
5375 up_write(&EXT4_I(inode)->i_data_sem);
5376 goto out_stop;
5377 }
Olivier Deprez157378f2022-04-04 15:47:50 +02005378 ext4_discard_preallocations(inode, 0);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005379
5380 ret = ext4_ext_shift_extents(inode, handle, punch_stop,
5381 punch_stop - punch_start, SHIFT_LEFT);
5382 if (ret) {
5383 up_write(&EXT4_I(inode)->i_data_sem);
5384 goto out_stop;
5385 }
5386
Olivier Deprez157378f2022-04-04 15:47:50 +02005387 new_size = inode->i_size - len;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005388 i_size_write(inode, new_size);
5389 EXT4_I(inode)->i_disksize = new_size;
5390
5391 up_write(&EXT4_I(inode)->i_data_sem);
5392 if (IS_SYNC(inode))
5393 ext4_handle_sync(handle);
5394 inode->i_mtime = inode->i_ctime = current_time(inode);
Olivier Deprez157378f2022-04-04 15:47:50 +02005395 ret = ext4_mark_inode_dirty(handle, inode);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005396 ext4_update_inode_fsync_trans(handle, inode, 1);
5397
5398out_stop:
5399 ext4_journal_stop(handle);
Olivier Deprez157378f2022-04-04 15:47:50 +02005400 ext4_fc_stop_ineligible(sb);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005401out_mmap:
5402 up_write(&EXT4_I(inode)->i_mmap_sem);
5403out_mutex:
5404 inode_unlock(inode);
5405 return ret;
5406}
5407
5408/*
5409 * ext4_insert_range:
5410 * This function implements the FALLOC_FL_INSERT_RANGE flag of fallocate.
5411 * The data blocks starting from @offset to the EOF are shifted by @len
5412 * towards right to create a hole in the @inode. Inode size is increased
5413 * by len bytes.
5414 * Returns 0 on success, error otherwise.
5415 */
Olivier Deprez92d4c212022-12-06 15:05:30 +01005416static int ext4_insert_range(struct file *file, loff_t offset, loff_t len)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005417{
Olivier Deprez92d4c212022-12-06 15:05:30 +01005418 struct inode *inode = file_inode(file);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005419 struct super_block *sb = inode->i_sb;
5420 handle_t *handle;
5421 struct ext4_ext_path *path;
5422 struct ext4_extent *extent;
5423 ext4_lblk_t offset_lblk, len_lblk, ee_start_lblk = 0;
5424 unsigned int credits, ee_len;
5425 int ret = 0, depth, split_flag = 0;
5426 loff_t ioffset;
5427
5428 /*
5429 * We need to test this early because xfstests assumes that an
5430 * insert range of (0, 1) will return EOPNOTSUPP if the file
5431 * system does not support insert range.
5432 */
5433 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
5434 return -EOPNOTSUPP;
5435
Olivier Deprez157378f2022-04-04 15:47:50 +02005436 /* Insert range works only on fs cluster size aligned regions. */
5437 if (!IS_ALIGNED(offset | len, EXT4_CLUSTER_SIZE(sb)))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005438 return -EINVAL;
5439
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005440 trace_ext4_insert_range(inode, offset, len);
5441
5442 offset_lblk = offset >> EXT4_BLOCK_SIZE_BITS(sb);
5443 len_lblk = len >> EXT4_BLOCK_SIZE_BITS(sb);
5444
5445 /* Call ext4_force_commit to flush all data in case of data=journal */
5446 if (ext4_should_journal_data(inode)) {
5447 ret = ext4_force_commit(inode->i_sb);
5448 if (ret)
5449 return ret;
5450 }
5451
5452 inode_lock(inode);
5453 /* Currently just for extent based files */
5454 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
5455 ret = -EOPNOTSUPP;
5456 goto out_mutex;
5457 }
5458
Olivier Deprez157378f2022-04-04 15:47:50 +02005459 /* Check whether the maximum file size would be exceeded */
5460 if (len > inode->i_sb->s_maxbytes - inode->i_size) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005461 ret = -EFBIG;
5462 goto out_mutex;
5463 }
5464
Olivier Deprez157378f2022-04-04 15:47:50 +02005465 /* Offset must be less than i_size */
5466 if (offset >= inode->i_size) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005467 ret = -EINVAL;
5468 goto out_mutex;
5469 }
5470
5471 /* Wait for existing dio to complete */
5472 inode_dio_wait(inode);
5473
Olivier Deprez92d4c212022-12-06 15:05:30 +01005474 ret = file_modified(file);
5475 if (ret)
5476 goto out_mutex;
5477
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005478 /*
5479 * Prevent page faults from reinstantiating pages we have released from
5480 * page cache.
5481 */
5482 down_write(&EXT4_I(inode)->i_mmap_sem);
5483
5484 ret = ext4_break_layouts(inode);
5485 if (ret)
5486 goto out_mmap;
5487
5488 /*
5489 * Need to round down to align start offset to page size boundary
5490 * for page size > block size.
5491 */
5492 ioffset = round_down(offset, PAGE_SIZE);
5493 /* Write out all dirty pages */
5494 ret = filemap_write_and_wait_range(inode->i_mapping, ioffset,
5495 LLONG_MAX);
5496 if (ret)
5497 goto out_mmap;
5498 truncate_pagecache(inode, ioffset);
5499
5500 credits = ext4_writepage_trans_blocks(inode);
5501 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
5502 if (IS_ERR(handle)) {
5503 ret = PTR_ERR(handle);
5504 goto out_mmap;
5505 }
Olivier Deprez157378f2022-04-04 15:47:50 +02005506 ext4_fc_start_ineligible(sb, EXT4_FC_REASON_FALLOC_RANGE);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005507
5508 /* Expand file to avoid data loss if there is error while shifting */
5509 inode->i_size += len;
5510 EXT4_I(inode)->i_disksize += len;
5511 inode->i_mtime = inode->i_ctime = current_time(inode);
5512 ret = ext4_mark_inode_dirty(handle, inode);
5513 if (ret)
5514 goto out_stop;
5515
5516 down_write(&EXT4_I(inode)->i_data_sem);
Olivier Deprez157378f2022-04-04 15:47:50 +02005517 ext4_discard_preallocations(inode, 0);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005518
5519 path = ext4_find_extent(inode, offset_lblk, NULL, 0);
5520 if (IS_ERR(path)) {
5521 up_write(&EXT4_I(inode)->i_data_sem);
5522 goto out_stop;
5523 }
5524
5525 depth = ext_depth(inode);
5526 extent = path[depth].p_ext;
5527 if (extent) {
5528 ee_start_lblk = le32_to_cpu(extent->ee_block);
5529 ee_len = ext4_ext_get_actual_len(extent);
5530
5531 /*
5532 * If offset_lblk is not the starting block of extent, split
5533 * the extent @offset_lblk
5534 */
5535 if ((offset_lblk > ee_start_lblk) &&
5536 (offset_lblk < (ee_start_lblk + ee_len))) {
5537 if (ext4_ext_is_unwritten(extent))
5538 split_flag = EXT4_EXT_MARK_UNWRIT1 |
5539 EXT4_EXT_MARK_UNWRIT2;
5540 ret = ext4_split_extent_at(handle, inode, &path,
5541 offset_lblk, split_flag,
5542 EXT4_EX_NOCACHE |
5543 EXT4_GET_BLOCKS_PRE_IO |
5544 EXT4_GET_BLOCKS_METADATA_NOFAIL);
5545 }
5546
5547 ext4_ext_drop_refs(path);
5548 kfree(path);
5549 if (ret < 0) {
5550 up_write(&EXT4_I(inode)->i_data_sem);
5551 goto out_stop;
5552 }
5553 } else {
5554 ext4_ext_drop_refs(path);
5555 kfree(path);
5556 }
5557
5558 ret = ext4_es_remove_extent(inode, offset_lblk,
5559 EXT_MAX_BLOCKS - offset_lblk);
5560 if (ret) {
5561 up_write(&EXT4_I(inode)->i_data_sem);
5562 goto out_stop;
5563 }
5564
5565 /*
5566 * if offset_lblk lies in a hole which is at start of file, use
5567 * ee_start_lblk to shift extents
5568 */
5569 ret = ext4_ext_shift_extents(inode, handle,
5570 ee_start_lblk > offset_lblk ? ee_start_lblk : offset_lblk,
5571 len_lblk, SHIFT_RIGHT);
5572
5573 up_write(&EXT4_I(inode)->i_data_sem);
5574 if (IS_SYNC(inode))
5575 ext4_handle_sync(handle);
5576 if (ret >= 0)
5577 ext4_update_inode_fsync_trans(handle, inode, 1);
5578
5579out_stop:
5580 ext4_journal_stop(handle);
Olivier Deprez157378f2022-04-04 15:47:50 +02005581 ext4_fc_stop_ineligible(sb);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005582out_mmap:
5583 up_write(&EXT4_I(inode)->i_mmap_sem);
5584out_mutex:
5585 inode_unlock(inode);
5586 return ret;
5587}
5588
5589/**
David Brazdil0f672f62019-12-10 10:32:29 +00005590 * ext4_swap_extents() - Swap extents between two inodes
5591 * @handle: handle for this transaction
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005592 * @inode1: First inode
5593 * @inode2: Second inode
5594 * @lblk1: Start block for first inode
5595 * @lblk2: Start block for second inode
5596 * @count: Number of blocks to swap
5597 * @unwritten: Mark second inode's extents as unwritten after swap
5598 * @erp: Pointer to save error value
5599 *
5600 * This helper routine does exactly what is promise "swap extents". All other
5601 * stuff such as page-cache locking consistency, bh mapping consistency or
5602 * extent's data copying must be performed by caller.
5603 * Locking:
5604 * i_mutex is held for both inodes
5605 * i_data_sem is locked for write for both inodes
5606 * Assumptions:
5607 * All pages from requested range are locked for both inodes
5608 */
5609int
5610ext4_swap_extents(handle_t *handle, struct inode *inode1,
5611 struct inode *inode2, ext4_lblk_t lblk1, ext4_lblk_t lblk2,
5612 ext4_lblk_t count, int unwritten, int *erp)
5613{
5614 struct ext4_ext_path *path1 = NULL;
5615 struct ext4_ext_path *path2 = NULL;
5616 int replaced_count = 0;
5617
5618 BUG_ON(!rwsem_is_locked(&EXT4_I(inode1)->i_data_sem));
5619 BUG_ON(!rwsem_is_locked(&EXT4_I(inode2)->i_data_sem));
5620 BUG_ON(!inode_is_locked(inode1));
5621 BUG_ON(!inode_is_locked(inode2));
5622
5623 *erp = ext4_es_remove_extent(inode1, lblk1, count);
5624 if (unlikely(*erp))
5625 return 0;
5626 *erp = ext4_es_remove_extent(inode2, lblk2, count);
5627 if (unlikely(*erp))
5628 return 0;
5629
5630 while (count) {
5631 struct ext4_extent *ex1, *ex2, tmp_ex;
5632 ext4_lblk_t e1_blk, e2_blk;
5633 int e1_len, e2_len, len;
5634 int split = 0;
5635
5636 path1 = ext4_find_extent(inode1, lblk1, NULL, EXT4_EX_NOCACHE);
5637 if (IS_ERR(path1)) {
5638 *erp = PTR_ERR(path1);
5639 path1 = NULL;
5640 finish:
5641 count = 0;
5642 goto repeat;
5643 }
5644 path2 = ext4_find_extent(inode2, lblk2, NULL, EXT4_EX_NOCACHE);
5645 if (IS_ERR(path2)) {
5646 *erp = PTR_ERR(path2);
5647 path2 = NULL;
5648 goto finish;
5649 }
5650 ex1 = path1[path1->p_depth].p_ext;
5651 ex2 = path2[path2->p_depth].p_ext;
Olivier Deprez157378f2022-04-04 15:47:50 +02005652 /* Do we have something to swap ? */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005653 if (unlikely(!ex2 || !ex1))
5654 goto finish;
5655
5656 e1_blk = le32_to_cpu(ex1->ee_block);
5657 e2_blk = le32_to_cpu(ex2->ee_block);
5658 e1_len = ext4_ext_get_actual_len(ex1);
5659 e2_len = ext4_ext_get_actual_len(ex2);
5660
5661 /* Hole handling */
5662 if (!in_range(lblk1, e1_blk, e1_len) ||
5663 !in_range(lblk2, e2_blk, e2_len)) {
5664 ext4_lblk_t next1, next2;
5665
5666 /* if hole after extent, then go to next extent */
5667 next1 = ext4_ext_next_allocated_block(path1);
5668 next2 = ext4_ext_next_allocated_block(path2);
5669 /* If hole before extent, then shift to that extent */
5670 if (e1_blk > lblk1)
5671 next1 = e1_blk;
5672 if (e2_blk > lblk2)
5673 next2 = e2_blk;
5674 /* Do we have something to swap */
5675 if (next1 == EXT_MAX_BLOCKS || next2 == EXT_MAX_BLOCKS)
5676 goto finish;
5677 /* Move to the rightest boundary */
5678 len = next1 - lblk1;
5679 if (len < next2 - lblk2)
5680 len = next2 - lblk2;
5681 if (len > count)
5682 len = count;
5683 lblk1 += len;
5684 lblk2 += len;
5685 count -= len;
5686 goto repeat;
5687 }
5688
5689 /* Prepare left boundary */
5690 if (e1_blk < lblk1) {
5691 split = 1;
5692 *erp = ext4_force_split_extent_at(handle, inode1,
5693 &path1, lblk1, 0);
5694 if (unlikely(*erp))
5695 goto finish;
5696 }
5697 if (e2_blk < lblk2) {
5698 split = 1;
5699 *erp = ext4_force_split_extent_at(handle, inode2,
5700 &path2, lblk2, 0);
5701 if (unlikely(*erp))
5702 goto finish;
5703 }
5704 /* ext4_split_extent_at() may result in leaf extent split,
5705 * path must to be revalidated. */
5706 if (split)
5707 goto repeat;
5708
5709 /* Prepare right boundary */
5710 len = count;
5711 if (len > e1_blk + e1_len - lblk1)
5712 len = e1_blk + e1_len - lblk1;
5713 if (len > e2_blk + e2_len - lblk2)
5714 len = e2_blk + e2_len - lblk2;
5715
5716 if (len != e1_len) {
5717 split = 1;
5718 *erp = ext4_force_split_extent_at(handle, inode1,
5719 &path1, lblk1 + len, 0);
5720 if (unlikely(*erp))
5721 goto finish;
5722 }
5723 if (len != e2_len) {
5724 split = 1;
5725 *erp = ext4_force_split_extent_at(handle, inode2,
5726 &path2, lblk2 + len, 0);
5727 if (*erp)
5728 goto finish;
5729 }
5730 /* ext4_split_extent_at() may result in leaf extent split,
5731 * path must to be revalidated. */
5732 if (split)
5733 goto repeat;
5734
5735 BUG_ON(e2_len != e1_len);
5736 *erp = ext4_ext_get_access(handle, inode1, path1 + path1->p_depth);
5737 if (unlikely(*erp))
5738 goto finish;
5739 *erp = ext4_ext_get_access(handle, inode2, path2 + path2->p_depth);
5740 if (unlikely(*erp))
5741 goto finish;
5742
5743 /* Both extents are fully inside boundaries. Swap it now */
5744 tmp_ex = *ex1;
5745 ext4_ext_store_pblock(ex1, ext4_ext_pblock(ex2));
5746 ext4_ext_store_pblock(ex2, ext4_ext_pblock(&tmp_ex));
5747 ex1->ee_len = cpu_to_le16(e2_len);
5748 ex2->ee_len = cpu_to_le16(e1_len);
5749 if (unwritten)
5750 ext4_ext_mark_unwritten(ex2);
5751 if (ext4_ext_is_unwritten(&tmp_ex))
5752 ext4_ext_mark_unwritten(ex1);
5753
5754 ext4_ext_try_to_merge(handle, inode2, path2, ex2);
5755 ext4_ext_try_to_merge(handle, inode1, path1, ex1);
5756 *erp = ext4_ext_dirty(handle, inode2, path2 +
5757 path2->p_depth);
5758 if (unlikely(*erp))
5759 goto finish;
5760 *erp = ext4_ext_dirty(handle, inode1, path1 +
5761 path1->p_depth);
5762 /*
5763 * Looks scarry ah..? second inode already points to new blocks,
5764 * and it was successfully dirtied. But luckily error may happen
5765 * only due to journal error, so full transaction will be
5766 * aborted anyway.
5767 */
5768 if (unlikely(*erp))
5769 goto finish;
5770 lblk1 += len;
5771 lblk2 += len;
5772 replaced_count += len;
5773 count -= len;
5774
5775 repeat:
5776 ext4_ext_drop_refs(path1);
5777 kfree(path1);
5778 ext4_ext_drop_refs(path2);
5779 kfree(path2);
5780 path1 = path2 = NULL;
5781 }
5782 return replaced_count;
5783}
David Brazdil0f672f62019-12-10 10:32:29 +00005784
5785/*
5786 * ext4_clu_mapped - determine whether any block in a logical cluster has
5787 * been mapped to a physical cluster
5788 *
5789 * @inode - file containing the logical cluster
5790 * @lclu - logical cluster of interest
5791 *
5792 * Returns 1 if any block in the logical cluster is mapped, signifying
5793 * that a physical cluster has been allocated for it. Otherwise,
5794 * returns 0. Can also return negative error codes. Derived from
5795 * ext4_ext_map_blocks().
5796 */
5797int ext4_clu_mapped(struct inode *inode, ext4_lblk_t lclu)
5798{
5799 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5800 struct ext4_ext_path *path;
5801 int depth, mapped = 0, err = 0;
5802 struct ext4_extent *extent;
5803 ext4_lblk_t first_lblk, first_lclu, last_lclu;
5804
5805 /* search for the extent closest to the first block in the cluster */
5806 path = ext4_find_extent(inode, EXT4_C2B(sbi, lclu), NULL, 0);
5807 if (IS_ERR(path)) {
5808 err = PTR_ERR(path);
5809 path = NULL;
5810 goto out;
5811 }
5812
5813 depth = ext_depth(inode);
5814
5815 /*
5816 * A consistent leaf must not be empty. This situation is possible,
5817 * though, _during_ tree modification, and it's why an assert can't
5818 * be put in ext4_find_extent().
5819 */
5820 if (unlikely(path[depth].p_ext == NULL && depth != 0)) {
5821 EXT4_ERROR_INODE(inode,
5822 "bad extent address - lblock: %lu, depth: %d, pblock: %lld",
5823 (unsigned long) EXT4_C2B(sbi, lclu),
5824 depth, path[depth].p_block);
5825 err = -EFSCORRUPTED;
5826 goto out;
5827 }
5828
5829 extent = path[depth].p_ext;
5830
5831 /* can't be mapped if the extent tree is empty */
5832 if (extent == NULL)
5833 goto out;
5834
5835 first_lblk = le32_to_cpu(extent->ee_block);
5836 first_lclu = EXT4_B2C(sbi, first_lblk);
5837
5838 /*
5839 * Three possible outcomes at this point - found extent spanning
5840 * the target cluster, to the left of the target cluster, or to the
5841 * right of the target cluster. The first two cases are handled here.
5842 * The last case indicates the target cluster is not mapped.
5843 */
5844 if (lclu >= first_lclu) {
5845 last_lclu = EXT4_B2C(sbi, first_lblk +
5846 ext4_ext_get_actual_len(extent) - 1);
5847 if (lclu <= last_lclu) {
5848 mapped = 1;
5849 } else {
5850 first_lblk = ext4_ext_next_allocated_block(path);
5851 first_lclu = EXT4_B2C(sbi, first_lblk);
5852 if (lclu == first_lclu)
5853 mapped = 1;
5854 }
5855 }
5856
5857out:
5858 ext4_ext_drop_refs(path);
5859 kfree(path);
5860
5861 return err ? err : mapped;
5862}
Olivier Deprez157378f2022-04-04 15:47:50 +02005863
5864/*
5865 * Updates physical block address and unwritten status of extent
5866 * starting at lblk start and of len. If such an extent doesn't exist,
5867 * this function splits the extent tree appropriately to create an
5868 * extent like this. This function is called in the fast commit
5869 * replay path. Returns 0 on success and error on failure.
5870 */
5871int ext4_ext_replay_update_ex(struct inode *inode, ext4_lblk_t start,
5872 int len, int unwritten, ext4_fsblk_t pblk)
5873{
5874 struct ext4_ext_path *path = NULL, *ppath;
5875 struct ext4_extent *ex;
5876 int ret;
5877
5878 path = ext4_find_extent(inode, start, NULL, 0);
5879 if (IS_ERR(path))
5880 return PTR_ERR(path);
5881 ex = path[path->p_depth].p_ext;
5882 if (!ex) {
5883 ret = -EFSCORRUPTED;
5884 goto out;
5885 }
5886
5887 if (le32_to_cpu(ex->ee_block) != start ||
5888 ext4_ext_get_actual_len(ex) != len) {
5889 /* We need to split this extent to match our extent first */
5890 ppath = path;
5891 down_write(&EXT4_I(inode)->i_data_sem);
5892 ret = ext4_force_split_extent_at(NULL, inode, &ppath, start, 1);
5893 up_write(&EXT4_I(inode)->i_data_sem);
5894 if (ret)
5895 goto out;
5896 kfree(path);
5897 path = ext4_find_extent(inode, start, NULL, 0);
5898 if (IS_ERR(path))
5899 return -1;
5900 ppath = path;
5901 ex = path[path->p_depth].p_ext;
5902 WARN_ON(le32_to_cpu(ex->ee_block) != start);
5903 if (ext4_ext_get_actual_len(ex) != len) {
5904 down_write(&EXT4_I(inode)->i_data_sem);
5905 ret = ext4_force_split_extent_at(NULL, inode, &ppath,
5906 start + len, 1);
5907 up_write(&EXT4_I(inode)->i_data_sem);
5908 if (ret)
5909 goto out;
5910 kfree(path);
5911 path = ext4_find_extent(inode, start, NULL, 0);
5912 if (IS_ERR(path))
5913 return -EINVAL;
5914 ex = path[path->p_depth].p_ext;
5915 }
5916 }
5917 if (unwritten)
5918 ext4_ext_mark_unwritten(ex);
5919 else
5920 ext4_ext_mark_initialized(ex);
5921 ext4_ext_store_pblock(ex, pblk);
5922 down_write(&EXT4_I(inode)->i_data_sem);
5923 ret = ext4_ext_dirty(NULL, inode, &path[path->p_depth]);
5924 up_write(&EXT4_I(inode)->i_data_sem);
5925out:
5926 ext4_ext_drop_refs(path);
5927 kfree(path);
5928 ext4_mark_inode_dirty(NULL, inode);
5929 return ret;
5930}
5931
5932/* Try to shrink the extent tree */
5933void ext4_ext_replay_shrink_inode(struct inode *inode, ext4_lblk_t end)
5934{
5935 struct ext4_ext_path *path = NULL;
5936 struct ext4_extent *ex;
5937 ext4_lblk_t old_cur, cur = 0;
5938
5939 while (cur < end) {
5940 path = ext4_find_extent(inode, cur, NULL, 0);
5941 if (IS_ERR(path))
5942 return;
5943 ex = path[path->p_depth].p_ext;
5944 if (!ex) {
5945 ext4_ext_drop_refs(path);
5946 kfree(path);
5947 ext4_mark_inode_dirty(NULL, inode);
5948 return;
5949 }
5950 old_cur = cur;
5951 cur = le32_to_cpu(ex->ee_block) + ext4_ext_get_actual_len(ex);
5952 if (cur <= old_cur)
5953 cur = old_cur + 1;
5954 ext4_ext_try_to_merge(NULL, inode, path, ex);
5955 down_write(&EXT4_I(inode)->i_data_sem);
5956 ext4_ext_dirty(NULL, inode, &path[path->p_depth]);
5957 up_write(&EXT4_I(inode)->i_data_sem);
5958 ext4_mark_inode_dirty(NULL, inode);
5959 ext4_ext_drop_refs(path);
5960 kfree(path);
5961 }
5962}
5963
5964/* Check if *cur is a hole and if it is, skip it */
5965static int skip_hole(struct inode *inode, ext4_lblk_t *cur)
5966{
5967 int ret;
5968 struct ext4_map_blocks map;
5969
5970 map.m_lblk = *cur;
5971 map.m_len = ((inode->i_size) >> inode->i_sb->s_blocksize_bits) - *cur;
5972
5973 ret = ext4_map_blocks(NULL, inode, &map, 0);
5974 if (ret < 0)
5975 return ret;
5976 if (ret != 0)
5977 return 0;
5978 *cur = *cur + map.m_len;
5979 return 0;
5980}
5981
5982/* Count number of blocks used by this inode and update i_blocks */
5983int ext4_ext_replay_set_iblocks(struct inode *inode)
5984{
5985 struct ext4_ext_path *path = NULL, *path2 = NULL;
5986 struct ext4_extent *ex;
5987 ext4_lblk_t cur = 0, end;
5988 int numblks = 0, i, ret = 0;
5989 ext4_fsblk_t cmp1, cmp2;
5990 struct ext4_map_blocks map;
5991
5992 /* Determin the size of the file first */
5993 path = ext4_find_extent(inode, EXT_MAX_BLOCKS - 1, NULL,
5994 EXT4_EX_NOCACHE);
5995 if (IS_ERR(path))
5996 return PTR_ERR(path);
5997 ex = path[path->p_depth].p_ext;
5998 if (!ex) {
5999 ext4_ext_drop_refs(path);
6000 kfree(path);
6001 goto out;
6002 }
6003 end = le32_to_cpu(ex->ee_block) + ext4_ext_get_actual_len(ex);
6004 ext4_ext_drop_refs(path);
6005 kfree(path);
6006
6007 /* Count the number of data blocks */
6008 cur = 0;
6009 while (cur < end) {
6010 map.m_lblk = cur;
6011 map.m_len = end - cur;
6012 ret = ext4_map_blocks(NULL, inode, &map, 0);
6013 if (ret < 0)
6014 break;
6015 if (ret > 0)
6016 numblks += ret;
6017 cur = cur + map.m_len;
6018 }
6019
6020 /*
6021 * Count the number of extent tree blocks. We do it by looking up
6022 * two successive extents and determining the difference between
6023 * their paths. When path is different for 2 successive extents
6024 * we compare the blocks in the path at each level and increment
6025 * iblocks by total number of differences found.
6026 */
6027 cur = 0;
6028 ret = skip_hole(inode, &cur);
6029 if (ret < 0)
6030 goto out;
6031 path = ext4_find_extent(inode, cur, NULL, 0);
6032 if (IS_ERR(path))
6033 goto out;
6034 numblks += path->p_depth;
6035 ext4_ext_drop_refs(path);
6036 kfree(path);
6037 while (cur < end) {
6038 path = ext4_find_extent(inode, cur, NULL, 0);
6039 if (IS_ERR(path))
6040 break;
6041 ex = path[path->p_depth].p_ext;
6042 if (!ex) {
6043 ext4_ext_drop_refs(path);
6044 kfree(path);
6045 return 0;
6046 }
6047 cur = max(cur + 1, le32_to_cpu(ex->ee_block) +
6048 ext4_ext_get_actual_len(ex));
6049 ret = skip_hole(inode, &cur);
6050 if (ret < 0) {
6051 ext4_ext_drop_refs(path);
6052 kfree(path);
6053 break;
6054 }
6055 path2 = ext4_find_extent(inode, cur, NULL, 0);
6056 if (IS_ERR(path2)) {
6057 ext4_ext_drop_refs(path);
6058 kfree(path);
6059 break;
6060 }
6061 ex = path2[path2->p_depth].p_ext;
6062 for (i = 0; i <= max(path->p_depth, path2->p_depth); i++) {
6063 cmp1 = cmp2 = 0;
6064 if (i <= path->p_depth)
6065 cmp1 = path[i].p_bh ?
6066 path[i].p_bh->b_blocknr : 0;
6067 if (i <= path2->p_depth)
6068 cmp2 = path2[i].p_bh ?
6069 path2[i].p_bh->b_blocknr : 0;
6070 if (cmp1 != cmp2 && cmp2 != 0)
6071 numblks++;
6072 }
6073 ext4_ext_drop_refs(path);
6074 ext4_ext_drop_refs(path2);
6075 kfree(path);
6076 kfree(path2);
6077 }
6078
6079out:
6080 inode->i_blocks = numblks << (inode->i_sb->s_blocksize_bits - 9);
6081 ext4_mark_inode_dirty(NULL, inode);
6082 return 0;
6083}
6084
6085int ext4_ext_clear_bb(struct inode *inode)
6086{
6087 struct ext4_ext_path *path = NULL;
6088 struct ext4_extent *ex;
6089 ext4_lblk_t cur = 0, end;
6090 int j, ret = 0;
6091 struct ext4_map_blocks map;
6092
6093 /* Determin the size of the file first */
6094 path = ext4_find_extent(inode, EXT_MAX_BLOCKS - 1, NULL,
6095 EXT4_EX_NOCACHE);
6096 if (IS_ERR(path))
6097 return PTR_ERR(path);
6098 ex = path[path->p_depth].p_ext;
6099 if (!ex) {
6100 ext4_ext_drop_refs(path);
6101 kfree(path);
6102 return 0;
6103 }
6104 end = le32_to_cpu(ex->ee_block) + ext4_ext_get_actual_len(ex);
6105 ext4_ext_drop_refs(path);
6106 kfree(path);
6107
6108 cur = 0;
6109 while (cur < end) {
6110 map.m_lblk = cur;
6111 map.m_len = end - cur;
6112 ret = ext4_map_blocks(NULL, inode, &map, 0);
6113 if (ret < 0)
6114 break;
6115 if (ret > 0) {
6116 path = ext4_find_extent(inode, map.m_lblk, NULL, 0);
6117 if (!IS_ERR_OR_NULL(path)) {
6118 for (j = 0; j < path->p_depth; j++) {
6119
6120 ext4_mb_mark_bb(inode->i_sb,
6121 path[j].p_block, 1, 0);
6122 ext4_fc_record_regions(inode->i_sb, inode->i_ino,
6123 0, path[j].p_block, 1, 1);
6124 }
6125 ext4_ext_drop_refs(path);
6126 kfree(path);
6127 }
6128 ext4_mb_mark_bb(inode->i_sb, map.m_pblk, map.m_len, 0);
6129 ext4_fc_record_regions(inode->i_sb, inode->i_ino,
6130 map.m_lblk, map.m_pblk, map.m_len, 1);
6131 }
6132 cur = cur + map.m_len;
6133 }
6134
6135 return 0;
6136}