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